LCOV - code coverage report
Current view: top level - source/scriptinterface - Interface.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 294 372 79.0 %
Date: 2026-12-03 01:19:39 Functions: 38 41 92.7 %

          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             : #include "precompiled.h"
      19             : 
      20             : #include "Interface.h"
      21             : 
      22             : #include "lib/debug.h"
      23             : #include "lib/file/vfs/vfs_path.h"
      24             : #include "lib/file/vfs/vfs_util.h"
      25             : #include "lib/utf8.h"
      26             : #include "ps/CLogger.h"
      27             : #include "ps/CStr.h"
      28             : #include "ps/Filesystem.h"
      29             : #include "ps/Profile.h"
      30             : #include "ps/Profiler2.h"
      31             : #include "ps/ThreadUtil.h"
      32             : #include "scriptinterface/FunctionWrapper.h"
      33             : #include "scriptinterface/ModuleLoader.h"
      34             : #include "scriptinterface/Object.h"
      35             : #include "scriptinterface/Context.h"
      36             : #include "scriptinterface/Stats.h"
      37             : #include "scriptinterface/StructuredClone.h"
      38             : 
      39             : #include <cstdio>
      40             : #include <cstring>
      41             : #include <js/CallAndConstruct.h>
      42             : #include <js/Class.h>
      43             : #include <js/ComparisonOperators.h>
      44             : #include <js/CompilationAndEvaluation.h>
      45             : #include <js/CompileOptions.h>
      46             : #include <js/EnvironmentChain.h>
      47             : #include <js/GCVector.h>
      48             : #include <js/GlobalObject.h>
      49             : #include <js/PropertyAndElement.h>
      50             : #include <js/PropertyDescriptor.h>
      51             : #include <js/Realm.h>
      52             : #include <js/RealmOptions.h>
      53             : #include <js/SourceText.h>
      54             : #include <jsapi.h>
      55             : #include <mozilla/Maybe.h>
      56             : #include <string>
      57             : #include <vector>
      58             : 
      59             : namespace JS { class Compartment; }
      60             : namespace mozilla { union Utf8Unit; }
      61             : 
      62             : #define BOOST_MULTI_INDEX_DISABLE_SERIALIZATION
      63             : #include <boost/preprocessor/punctuation/comma_if.hpp>
      64             : #include <boost/preprocessor/repetition/repeat.hpp>
      65             : #include <boost/random/linear_congruential.hpp>
      66             : #include <boost/flyweight.hpp>
      67             : #include <boost/flyweight/key_value.hpp>
      68             : #include <boost/flyweight/no_locking.hpp>
      69             : #include <boost/flyweight/no_tracking.hpp>
      70             : 
      71             : /**
      72             :  * @file
      73             :  * Abstractions of various SpiderMonkey features.
      74             :  * Engine code should be using functions of these interfaces rather than
      75             :  * directly accessing the underlying JS api.
      76             :  */
      77             : 
      78             : namespace Script
      79             : {
      80             : 
      81             : struct Interface_impl
      82             : {
      83             :     Interface_impl(const char* nativeScopeName, Context& context,
      84             :         JS::Compartment* compartment, std::function<bool(const VfsPath&)> allowModule);
      85             :     ~Interface_impl();
      86             : 
      87             :     // Take care to keep this declaration before heap rooted members. Destructors of heap rooted
      88             :     // members have to be called before the context destructor.
      89             :     Context& m_context;
      90             : 
      91             :     friend Request;
      92             :     private:
      93             :         JSContext* m_cx;
      94             :         JS::PersistentRootedObject m_glob; // global scope object
      95             : 
      96             :     public:
      97             :         boost::rand48* m_rng;
      98             :         JS::PersistentRootedObject m_nativeScope; // native function scope object
      99             :     ModuleLoader m_ModuleLoader;
     100             : };
     101             : 
     102             : /**
     103             :  * Constructor for Request - here because it needs access into Interface_impl.
     104             :  */
     105      295704 : Request::Request(const Interface& scriptInterface) :
     106      139584 :     cx(scriptInterface.m->m_cx),
     107      295704 :     glob(scriptInterface.m->m_glob),
     108      295704 :     nativeScope(scriptInterface.m->m_nativeScope),
     109      295704 :     m_ScriptInterface(scriptInterface)
     110             : {
     111      295704 :     m_FormerRealm = JS::EnterRealm(cx, scriptInterface.m->m_glob);
     112      109628 : }
     113             : 
     114      295704 : Request::~Request()
     115             : {
     116      267518 :     JS::LeaveRealm(cx, m_FormerRealm);
     117        1046 : }
     118             : 
     119      155765 : Request::Request(JSContext* cx) : Request(Interface::CmptPrivate::GetScriptInterface(cx))
     120             : {
     121      155765 : }
     122             : 
     123         370 : JS::Value Request::globalValue() const
     124             : {
     125         370 :     return JS::ObjectValue(*glob);
     126             : }
     127             : 
     128        2809 : const Interface& Request::GetScriptInterface() const
     129             : {
     130         351 :     return m_ScriptInterface;
     131             : }
     132             : 
     133             : } // namespace Script
     134             : 
     135             : namespace
     136             : {
     137             : 
     138             : JSClassOps global_classops = {
     139             :     nullptr, nullptr,
     140             :     nullptr, nullptr,
     141             :     nullptr, nullptr, nullptr,
     142             :     nullptr, nullptr,
     143             :     JS_GlobalObjectTraceHook
     144             : };
     145             : 
     146             : JSClass global_class = {
     147             :     "global", JSCLASS_GLOBAL_FLAGS, &global_classops
     148             : };
     149             : 
     150             : // Functions in the global namespace:
     151             : 
     152           0 : bool print(JSContext* cx, unsigned int argc, JS::Value* vp)
     153             : {
     154           0 :     JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
     155           0 :     Script::Request rq(cx);
     156             : 
     157           0 :     for (unsigned int i = 0; i < args.length(); ++i)
     158             :     {
     159           0 :         std::wstring str;
     160           0 :         if (!Script::FromJSVal(rq, args[i], str))
     161           0 :             return false;
     162           0 :         debug_printf("%s", utf8_from_wstring(str).c_str());
     163           0 :     }
     164           0 :     fflush(stdout);
     165           0 :     args.rval().setUndefined();
     166           0 :     return true;
     167           0 : }
     168             : 
     169          95 : bool logmsg(JSContext* cx, unsigned int argc, JS::Value* vp)
     170             : {
     171          95 :     JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
     172          95 :     if (args.length() < 1)
     173             :     {
     174           0 :         args.rval().setUndefined();
     175           0 :         return true;
     176             :     }
     177             : 
     178          95 :     Script::Request rq(cx);
     179          95 :     std::wstring str;
     180          95 :     if (!Script::FromJSVal(rq, args[0], str))
     181             :         return false;
     182         285 :     LOGMESSAGE("{}", utf8_from_wstring(str));
     183          95 :     args.rval().setUndefined();
     184          95 :     return true;
     185         190 : }
     186             : 
     187           1 : bool warn(JSContext* cx, unsigned int argc, JS::Value* vp)
     188             : {
     189           1 :     JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
     190           1 :     if (args.length() < 1)
     191             :     {
     192           0 :         args.rval().setUndefined();
     193           0 :         return true;
     194             :     }
     195             : 
     196           1 :     Script::Request rq(cx);
     197           1 :     std::wstring str;
     198           1 :     if (!Script::FromJSVal(rq, args[0], str))
     199             :         return false;
     200           3 :     LOGWARNING("{}", utf8_from_wstring(str));
     201           1 :     args.rval().setUndefined();
     202           1 :     return true;
     203           2 : }
     204             : 
     205           0 : bool error(JSContext* cx, unsigned int argc, JS::Value* vp)
     206             : {
     207           0 :     JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
     208           0 :     if (args.length() < 1)
     209             :     {
     210           0 :         args.rval().setUndefined();
     211           0 :         return true;
     212             :     }
     213             : 
     214           0 :     Script::Request rq(cx);
     215           0 :     std::wstring str;
     216           0 :     if (!Script::FromJSVal(rq, args[0], str))
     217             :         return false;
     218           0 :     LOGERROR("{}", utf8_from_wstring(str));
     219           0 :     args.rval().setUndefined();
     220           0 :     return true;
     221           0 : }
     222             : 
     223         583 : JS::Value deepcopy(const Script::Request& rq, JS::HandleValue val)
     224             : {
     225         583 :     if (val.isNullOrUndefined())
     226             :     {
     227           0 :         Script::Exception::Raise(rq, "deepcopy requires one argument.");
     228           0 :         return JS::UndefinedValue();
     229             :     }
     230             : 
     231         583 :     JS::RootedValue ret(rq.cx, Script::DeepCopy(rq, val));
     232         583 :     if (ret.isNullOrUndefined())
     233             :     {
     234           0 :         Script::Exception::Raise(rq, "deepcopy StructureClone copy failed.");
     235           0 :         return JS::UndefinedValue();
     236             :     }
     237         583 :     return ret;
     238         583 : }
     239             : 
     240         351 : JS::Value deepfreeze(const Script::Interface& scriptInterface, JS::HandleValue val)
     241             : {
     242         351 :     Script::Request rq(scriptInterface);
     243         351 :     if (!val.isObject())
     244             :     {
     245           0 :         Script::Exception::Raise(rq, "deepfreeze requires exactly one object as an argument.");
     246           0 :         return JS::UndefinedValue();
     247             :     }
     248             : 
     249         351 :     Script::DeepFreezeObject(rq, val);
     250         351 :     return val;
     251         351 : }
     252             : 
     253           8 : void ProfileStart(const std::string& regionName)
     254             : {
     255           8 :     const char* name = "(ProfileStart)";
     256             : 
     257           8 :     typedef boost::flyweight<
     258             :         std::string,
     259             :         boost::flyweights::no_tracking,
     260             :         boost::flyweights::no_locking
     261             :     > StringFlyweight;
     262             : 
     263           8 :     if (!regionName.empty())
     264           8 :         name = StringFlyweight(regionName).get().c_str();
     265             : 
     266           8 :     if (CProfileManager::IsInitialised() && Threading::IsMainThread())
     267           3 :         g_Profiler.StartScript(name);
     268             : 
     269           8 :     g_Profiler2.RecordRegionEnter(name);
     270           8 : }
     271             : 
     272           8 : void ProfileStop()
     273             : {
     274           8 :     if (CProfileManager::IsInitialised() && Threading::IsMainThread())
     275           3 :         g_Profiler.Stop();
     276             : 
     277           8 :     g_Profiler2.RecordRegionLeave();
     278           8 : }
     279             : 
     280           0 : void ProfileAttribute(const std::string& attr)
     281             : {
     282           0 :     const char* name = "(ProfileAttribute)";
     283             : 
     284           0 :     typedef boost::flyweight<
     285             :         std::string,
     286             :         boost::flyweights::no_tracking,
     287             :         boost::flyweights::no_locking
     288             :     > StringFlyweight;
     289             : 
     290           0 :     if (!attr.empty())
     291           0 :         name = StringFlyweight(attr).get().c_str();
     292             : 
     293           0 :     g_Profiler2.RecordAttribute("%s", name);
     294           0 : }
     295             : 
     296             : // Math override functions:
     297             : 
     298             : // boost::uniform_real is apparently buggy in Boost pre-1.47 - for integer generators
     299             : // it returns [min,max], not [min,max). The bug was fixed in 1.47.
     300             : // We need consistent behaviour, so manually implement the correct version:
     301             : static double generate_uniform_real(boost::rand48& rng, double min, double max)
     302             : {
     303         496 :     while (true)
     304             :     {
     305         496 :         double n = (double)(rng() - rng.min());
     306         496 :         double d = (double)(rng.max() - rng.min()) + 1.0;
     307         496 :         ENSURE(d > 0 && n >= 0 && n <= d);
     308         496 :         double r = n / d * (max - min) + min;
     309         496 :         if (r < max)
     310           2 :             return r;
     311             :     }
     312             : }
     313             : 
     314             : } // anonymous namespace
     315             : 
     316             : namespace Script
     317             : {
     318             : 
     319         496 : bool Interface::MathRandom(double& nbr) const
     320             : {
     321           2 :     if (m->m_rng == nullptr)
     322             :         return false;
     323           2 :     nbr = generate_uniform_real(*(m->m_rng), 0.0, 1.0);
     324           2 :     return true;
     325             : }
     326             : 
     327         494 : bool Interface::Math_random(JSContext* cx, unsigned int argc, JS::Value* vp)
     328             : {
     329         494 :     JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
     330         494 :     double r;
     331         988 :     if (!Interface::CmptPrivate::GetScriptInterface(cx).MathRandom(r))
     332             :     {
     333             :         // Since ESR140, returning false from a JSNative without a pending or
     334             :         // suppressed exception trips js::AssertExceptionResult in debug builds,
     335             :         // so report the failure as an uncatchable exception.
     336           0 :         Request rq(cx);
     337           0 :         Exception::ReportUncatchable(rq);
     338           0 :         return false;
     339           0 :     }
     340             : 
     341         494 :     args.rval().setNumber(r);
     342         494 :     return true;
     343             : }
     344             : 
     345         377 : Interface_impl::Interface_impl(const char* nativeScopeName, Context& context,
     346         377 :     JS::Compartment* compartment, std::function<bool(const VfsPath&)> allowModule) :
     347         377 :     m_context(context), m_cx(context.GetGeneralJSContext()), m_glob(context.GetGeneralJSContext()),
     348         377 :     m_nativeScope(context.GetGeneralJSContext()),
     349         457 :     m_ModuleLoader{std::move(allowModule)}
     350             : {
     351         377 :     JS::RealmCreationOptions creationOpt;
     352             :     // Keep JIT code during non-shrinking GCs. This brings a quite big performance improvement.
     353         377 :     creationOpt.setPreserveJitCode(true);
     354             :     // Enable uneval
     355         377 :     creationOpt.setToSourceEnabled(true);
     356             : 
     357         377 :     if (compartment)
     358           4 :         creationOpt.setExistingCompartment(compartment);
     359             :     else
     360             :         // This is the default behaviour.
     361         373 :         creationOpt.setNewCompartmentAndZone();
     362             : 
     363         377 :     JS::RealmOptions opt(creationOpt, JS::RealmBehaviors{});
     364             : 
     365         377 :     m_glob = JS_NewGlobalObject(m_cx, &global_class, nullptr, JS::OnNewGlobalHookOption::FireOnNewGlobalHook, opt);
     366             : 
     367         377 :     JSAutoRealm autoRealm(m_cx, m_glob);
     368             : 
     369         377 :     ENSURE(JS::InitRealmStandardClasses(m_cx));
     370             : 
     371         377 :     JS_DefineProperty(m_cx, m_glob, "global", m_glob, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT);
     372             : 
     373             :     // These first 4 actually use CallArgs & thus don't use Script::Function
     374         377 :     JS_DefineFunction(m_cx, m_glob, "print", ::print,        0, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT);
     375         377 :     JS_DefineFunction(m_cx, m_glob, "log",   ::logmsg,       1, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT);
     376         377 :     JS_DefineFunction(m_cx, m_glob, "warn",  ::warn,         1, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT);
     377         377 :     JS_DefineFunction(m_cx, m_glob, "error", ::error,        1, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT);
     378         377 :     Script::Function::Register<deepcopy>(m_cx, m_glob, "clone");
     379         377 :     Script::Function::Register<deepfreeze>(m_cx, m_glob, "deepfreeze");
     380             : 
     381         377 :     m_nativeScope = JS_DefineObject(m_cx, m_glob, nativeScopeName, nullptr, JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT);
     382             : 
     383         385 :     Script::Function::Register<&ProfileStart>(m_cx, m_nativeScope, "ProfileStart");
     384         385 :     Script::Function::Register<&ProfileStop>(m_cx, m_nativeScope, "ProfileStop");
     385         377 :     Script::Function::Register<&ProfileAttribute>(m_cx, m_nativeScope, "ProfileAttribute");
     386             : 
     387         377 :     m_context.RegisterRealm(JS::GetObjectRealmOrNull(m_glob));
     388         377 : }
     389             : 
     390         377 : Interface_impl::~Interface_impl()
     391             : {
     392         377 :     m_context.UnRegisterRealm(JS::GetObjectRealmOrNull(m_glob));
     393         754 : }
     394             : 
     395         373 : Interface::Interface(const char* nativeScopeName, const char* debugName, Context& context,
     396         373 :     std::function<bool(const VfsPath&)> allowModule) :
     397         373 :     m{std::make_unique<Interface_impl>(nativeScopeName, context, nullptr,
     398         373 :         std::move(allowModule))}
     399             : {
     400             :     // Profiler stats table isn't thread-safe, so only enable this on the main thread
     401         373 :     if (Threading::IsMainThread())
     402             :     {
     403         373 :         if (g_ScriptStatsTable)
     404           0 :             g_ScriptStatsTable->Add(this, debugName);
     405             :     }
     406             : 
     407         373 :     Request rq(this);
     408         373 :     m_CmptPrivate.pScriptInterface = this;
     409         373 :     JS::SetRealmPrivate(JS::GetObjectRealmOrNull(rq.glob), (void*)&m_CmptPrivate);
     410         373 : }
     411             : 
     412           4 : Interface::Interface(const char* nativeScopeName, const char* debugName,
     413           4 :     const Interface& neighbor, std::function<bool(const VfsPath& path)> allowModule)
     414             : {
     415           4 :     Request nrq(neighbor);
     416           4 :     JS::Compartment* comp = JS::GetCompartmentForRealm(JS::GetCurrentRealmOrNull(nrq.cx));
     417          12 :     m = std::make_unique<Interface_impl>(nativeScopeName, neighbor.GetContext(), comp,
     418           4 :         std::move(allowModule));
     419             : 
     420             :     // Profiler stats table isn't thread-safe, so only enable this on the main thread
     421           4 :     if (Threading::IsMainThread())
     422             :     {
     423           4 :         if (g_ScriptStatsTable)
     424           0 :             g_ScriptStatsTable->Add(this, debugName);
     425             :     }
     426             : 
     427           4 :     Request rq(this);
     428           4 :     m_CmptPrivate.pScriptInterface = this;
     429           4 :     JS::SetRealmPrivate(JS::GetObjectRealmOrNull(rq.glob), (void*)&m_CmptPrivate);
     430           4 : }
     431             : 
     432         377 : Interface::~Interface()
     433             : {
     434         377 :     m->m_context.RunJobs();
     435         377 :     if (Threading::IsMainThread())
     436             :     {
     437         377 :         if (g_ScriptStatsTable)
     438           0 :             g_ScriptStatsTable->Remove(this);
     439             :     }
     440         377 : }
     441             : 
     442      156259 : const Interface& Interface::CmptPrivate::GetScriptInterface(JSContext *cx)
     443             : {
     444      156259 :     CmptPrivate* pCmptPrivate = (CmptPrivate*)JS::GetRealmPrivate(JS::GetCurrentRealmOrNull(cx));
     445      156259 :     ENSURE(pCmptPrivate);
     446      156259 :     return *pCmptPrivate->pScriptInterface;
     447             : }
     448             : 
     449      115030 : void* Interface::CmptPrivate::GetCBData(JSContext *cx)
     450             : {
     451      115030 :     CmptPrivate* pCmptPrivate = (CmptPrivate*)JS::GetRealmPrivate(JS::GetCurrentRealmOrNull(cx));
     452      115030 :     return pCmptPrivate ? pCmptPrivate->pCBData : nullptr;
     453             : }
     454             : 
     455         208 : void Interface::SetCallbackData(void* pCBData)
     456             : {
     457         208 :     m_CmptPrivate.pCBData = pCBData;
     458         208 : }
     459             : 
     460             : template <>
     461      115030 : void* Interface::ObjectFromCBData<void>(const Request& rq)
     462             : {
     463      115030 :     return Interface::CmptPrivate::GetCBData(rq.cx);
     464             : }
     465             : 
     466         248 : bool Interface::LoadGlobalScripts()
     467             : {
     468             :     // Ignore this failure in tests
     469         248 :     if (!g_VFS)
     470             :         return false;
     471             : 
     472             :     // Load and execute *.js in the global scripts directory
     473         218 :     VfsPaths pathnames;
     474         218 :     vfs::GetPathnames(g_VFS, L"globalscripts/", L"*.js", pathnames);
     475        2073 :     for (const VfsPath& path : pathnames)
     476        1855 :         if (!LoadGlobalScriptFile(path))
     477             :         {
     478           0 :             LOGERROR("LoadGlobalScripts: Failed to load script {}", path.string8());
     479           0 :             return false;
     480             :         }
     481             : 
     482             :     return true;
     483         218 : }
     484             : 
     485         163 : bool Interface::ReplaceNondeterministicRNG(boost::rand48& rng)
     486             : {
     487         163 :     Request rq(this);
     488         163 :     JS::RootedValue math(rq.cx);
     489         163 :     JS::RootedObject global(rq.cx, rq.glob);
     490         163 :     if (JS_GetProperty(rq.cx, global, "Math", &math) && math.isObject())
     491             :     {
     492         163 :         JS::RootedObject mathObj(rq.cx, &math.toObject());
     493         163 :         JS::RootedFunction random(rq.cx, JS_DefineFunction(rq.cx, mathObj, "random", Math_random, 0,
     494         163 :             JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT));
     495         163 :         if (random)
     496             :         {
     497         163 :             m->m_rng = &rng;
     498         163 :             return true;
     499             :         }
     500         163 :     }
     501             : 
     502           0 :     Exception::CatchPending(rq);
     503           0 :     LOGERROR("ReplaceNondeterministicRNG: failed to replace Math.random");
     504           0 :     return false;
     505         163 : }
     506             : 
     507         350 : JSContext* Interface::GetGeneralJSContext() const
     508             : {
     509         350 :     return m->m_context.GetGeneralJSContext();
     510             : }
     511             : 
     512         383 : Context& Interface::GetContext() const
     513             : {
     514           4 :     return m->m_context;
     515             : }
     516             : 
     517         499 : ModuleLoader& Interface::GetModuleLoader() const
     518             : {
     519         499 :     return m->m_ModuleLoader;
     520             : }
     521             : 
     522        3962 : void Interface::CallConstructor(JS::HandleValue ctor, JS::HandleValueArray argv, JS::MutableHandleValue out) const
     523             : {
     524        3962 :     Request rq(this);
     525        3962 :     if (!ctor.isObject())
     526             :     {
     527           0 :         LOGERROR("CallConstructor: ctor is not an object");
     528           0 :         out.setNull();
     529           0 :         return;
     530             :     }
     531             : 
     532        3962 :     JS::RootedObject objOut(rq.cx);
     533        3962 :     if (!JS::Construct(rq.cx, ctor, argv, &objOut))
     534           0 :         out.setNull();
     535             :     else
     536        7924 :         out.setObjectOrNull(objOut);
     537        3962 : }
     538             : 
     539        6765 : void Interface::DefineCustomObjectType(JSClass *clasp, JSNative constructor, unsigned int minArgs,
     540             :     JSPropertySpec *ps, JSFunctionSpec *fs, JSPropertySpec *static_ps, JSFunctionSpec *static_fs)
     541             : {
     542        6765 :     Request rq(this);
     543        6765 :     std::string typeName = clasp->name;
     544             : 
     545        6765 :     if (m_CustomObjectTypes.find(typeName) != m_CustomObjectTypes.end())
     546             :     {
     547             :         // This type already exists
     548           0 :         throw PSERROR_Scripting_DefineType_AlreadyExists();
     549             :     }
     550             : 
     551        6765 :     JS::RootedObject global(rq.cx, rq.glob);
     552        6765 :     JS::RootedObject obj(rq.cx, JS_InitClass(rq.cx, global,
     553             :                                                clasp, nullptr, clasp->name,
     554             :                                                constructor, minArgs,     // Constructor, min args
     555             :                                                ps, fs,                   // Properties, methods
     556        6765 :                                                static_ps, static_fs));   // Constructor properties, methods
     557             : 
     558        6765 :     if (obj == nullptr)
     559             :     {
     560           0 :         Exception::CatchPending(rq);
     561           0 :         throw PSERROR_Scripting_DefineType_CreationFailed();
     562             :     }
     563             : 
     564        6765 :     CustomType& type = m_CustomObjectTypes[typeName];
     565             : 
     566        6765 :     type.m_Prototype.init(rq.cx, obj);
     567        6765 :     type.m_Class = clasp;
     568        6765 :     type.m_Constructor = constructor;
     569        9916 : }
     570             : 
     571        1177 : JSObject* Interface::CreateCustomObject(const std::string& typeName) const
     572             : {
     573        1177 :     std::unordered_map<std::string, CustomType>::const_iterator it = m_CustomObjectTypes.find(typeName);
     574             : 
     575        1177 :     if (it == m_CustomObjectTypes.end())
     576           0 :         throw PSERROR_Scripting_TypeDoesNotExist();
     577             : 
     578        1177 :     Request rq(this);
     579        1177 :     JS::RootedObject prototype(rq.cx, it->second.m_Prototype.get());
     580        1177 :     return JS_NewObjectWithGivenProto(rq.cx, it->second.m_Class, prototype);
     581        1177 : }
     582             : 
     583       13818 : bool Interface::SetGlobal_(const char* name, JS::HandleValue value, bool replace, bool constant, bool enumerate)
     584             : {
     585       13818 :     Request rq(this);
     586       13818 :     JS::RootedObject global(rq.cx, rq.glob);
     587             : 
     588       13818 :     bool found;
     589       13818 :     if (!JS_HasProperty(rq.cx, global, name, &found))
     590             :         return false;
     591       13818 :     if (found)
     592             :     {
     593           9 :         JS::Rooted<mozilla::Maybe<JS::PropertyDescriptor>> desc(rq.cx);
     594           9 :         if (!JS_GetOwnPropertyDescriptor(rq.cx, global, name, &desc) || !desc.isSome())
     595           0 :             return false;
     596             : 
     597           9 :         if (!desc->writable())
     598             :         {
     599           9 :             if (!replace)
     600             :             {
     601           0 :                 Exception::Raise(rq, "SetGlobal \"%s\" called multiple times", name);
     602             :                 return false;
     603             :             }
     604             : 
     605             :             // This is not supposed to happen, unless the user has called SetProperty with constant = true on the global object
     606             :             // instead of using SetGlobal.
     607           9 :             if (!desc->configurable())
     608             :             {
     609           0 :                 Exception::Raise(rq, "The global \"%s\" is permanent and cannot be hotloaded", name);
     610             :                 return false;
     611             :             }
     612             : 
     613           9 :             LOGMESSAGE("Hotloading new value for global \"{}\".", name);
     614           9 :             ENSURE(JS_DeleteProperty(rq.cx, global, name));
     615             :         }
     616           9 :     }
     617             : 
     618       13818 :     unsigned int attrs = 0;
     619       13818 :     if (constant)
     620       13818 :         attrs |= JSPROP_READONLY;
     621       13818 :     if (enumerate)
     622       13818 :         attrs |= JSPROP_ENUMERATE;
     623             : 
     624       13818 :     return JS_DefineProperty(rq.cx, global, name, value, attrs);
     625       13818 : }
     626             : 
     627        2770 : bool Interface::GetGlobalProperty(const Request& rq, const std::string& name, JS::MutableHandleValue out)
     628             : {
     629             :     // Try to get the object as a property of the global object.
     630        2770 :     JS::RootedObject global(rq.cx, rq.glob);
     631        2770 :     if (!JS_GetProperty(rq.cx, global, name.c_str(), out))
     632             :     {
     633           0 :         out.set(JS::NullHandleValue);
     634           0 :         return false;
     635             :     }
     636             : 
     637        2770 :     if (!out.isNullOrUndefined())
     638             :         return true;
     639             : 
     640             :     // Some objects, such as const definitions, or Class definitions, are hidden inside closures.
     641             :     // We must fetch those from the correct lexical scope.
     642             :     //JS::RootedValue glob(cx);
     643           8 :     JS::RootedObject lexical_environment(rq.cx, JS_GlobalLexicalEnvironment(rq.glob));
     644           8 :     if (!JS_GetProperty(rq.cx, lexical_environment, name.c_str(), out))
     645             :     {
     646           0 :         out.set(JS::NullHandleValue);
     647           0 :         return false;
     648             :     }
     649             : 
     650          16 :     if (!out.isNullOrUndefined())
     651             :         return true;
     652             : 
     653           0 :     out.set(JS::NullHandleValue);
     654           0 :     return false;
     655        2770 : }
     656             : 
     657           5 : bool Interface::SetPrototype(JS::HandleValue objVal, JS::HandleValue protoVal)
     658             : {
     659           5 :     Request rq(this);
     660           5 :     if (!objVal.isObject() || !protoVal.isObject())
     661             :         return false;
     662           5 :     JS::RootedObject obj(rq.cx, &objVal.toObject());
     663           5 :     JS::RootedObject proto(rq.cx, &protoVal.toObject());
     664           5 :     return JS_SetPrototype(rq.cx, obj, proto);
     665           5 : }
     666             : 
     667        1491 : bool Interface::LoadScript(const VfsPath& filename, const std::string& code) const
     668             : {
     669        1491 :     Request rq(this);
     670        1491 :     JS::RootedObject global(rq.cx, rq.glob);
     671             : 
     672             :     // CompileOptions does not copy the contents of the filename string pointer.
     673             :     // Passing a temporary string there will cause undefined behaviour, so we create a separate string to avoid the temporary.
     674        1491 :     std::string filenameStr = filename.string8();
     675             : 
     676        1491 :     JS::CompileOptions options(rq.cx);
     677             :     // Set the line to 0 because CompileFunction silently adds a `(function() {` as the first line,
     678             :     // and errors get misreported.
     679             :     // TODO: it would probably be better to not implicitly introduce JS scopes.
     680        1491 :     options.setFileAndLine(filenameStr.c_str(), 0);
     681        1491 :     options.setIsRunOnce(false);
     682        1491 :     options.setForceStrictMode();
     683             : 
     684        1491 :     JS::SourceText<mozilla::Utf8Unit> src;
     685        1491 :     ENSURE(src.init(rq.cx, code.c_str(), code.length(), JS::SourceOwnership::Borrowed));
     686        2982 :     JS::EnvironmentChain emptyScopeChain{ rq.cx, JS::SupportUnscopables::No };
     687        2982 :     JS::RootedFunction func(rq.cx, JS::CompileFunction(rq.cx, emptyScopeChain, options, NULL, 0, NULL, src));
     688        1491 :     if (func == nullptr)
     689             :     {
     690           2 :         Exception::CatchPending(rq);
     691             :         return false;
     692             :     }
     693             : 
     694        2980 :     JS::RootedValue rval(rq.cx);
     695        1489 :     if (JS_CallFunction(rq.cx, nullptr, func, JS::HandleValueArray::empty(), &rval))
     696             :         return true;
     697             : 
     698           4 :     Exception::CatchPending(rq);
     699             :     return false;
     700        2890 : }
     701             : 
     702        2130 : bool Interface::LoadGlobalScript(const VfsPath& filename, const std::string& code) const
     703             : {
     704        2130 :     Request rq(this);
     705             :     // CompileOptions does not copy the contents of the filename string pointer.
     706             :     // Passing a temporary string there will cause undefined behaviour, so we create a separate string to avoid the temporary.
     707        2130 :     std::string filenameStr = filename.string8();
     708             : 
     709        2130 :     JS::RootedValue rval(rq.cx);
     710        2130 :     JS::CompileOptions opts(rq.cx);
     711        2130 :     opts.setFileAndLine(filenameStr.c_str(), 1);
     712        2130 :     opts.setForceStrictMode();
     713             : 
     714        2130 :     JS::SourceText<mozilla::Utf8Unit> src;
     715        2130 :     ENSURE(src.init(rq.cx, code.c_str(), code.length(), JS::SourceOwnership::Borrowed));
     716        2130 :     if (JS::Evaluate(rq.cx, opts, src, &rval))
     717             :         return true;
     718             : 
     719           0 :     Exception::CatchPending(rq);
     720             :     return false;
     721        4260 : }
     722             : 
     723        2130 : bool Interface::LoadGlobalScriptFile(const VfsPath& path) const
     724             : {
     725        2130 :     if (!VfsFileExists(path))
     726             :     {
     727           0 :         LOGERROR("File '{}' does not exist", path.string8());
     728           0 :         return false;
     729             :     }
     730             : 
     731        2130 :     CVFSFile file;
     732             : 
     733        2130 :     PSRETURN ret = file.Load(g_VFS, path);
     734             : 
     735        2130 :     if (ret != PSRETURN_OK)
     736             :     {
     737           0 :         LOGERROR("Failed to load file '{}': {}", path.string8(), GetErrorString(ret));
     738           0 :         return false;
     739             :     }
     740             : 
     741        2130 :     CStr code = file.DecodeUTF8(); // assume it's UTF-8
     742             : 
     743        2130 :     return LoadGlobalScript(path, code);
     744        2130 : }
     745             : 
     746           2 : bool Interface::Eval(const std::string_view code) const
     747             : {
     748           2 :     Request rq(this);
     749           2 :     JS::RootedValue rval(rq.cx);
     750             : 
     751           2 :     JS::CompileOptions opts(rq.cx);
     752           2 :     opts.setFileAndLine("(eval)", 1);
     753           2 :     opts.setForceStrictMode();
     754           2 :     JS::SourceText<mozilla::Utf8Unit> src;
     755           2 :     ENSURE(src.init(rq.cx, code.data(), code.size(), JS::SourceOwnership::Borrowed));
     756           2 :     if (JS::Evaluate(rq.cx, opts, src, &rval))
     757             :         return true;
     758             : 
     759           0 :     Exception::CatchPending(rq);
     760             :     return false;
     761           2 : }
     762             : 
     763          66 : bool Interface::Eval(const std::string_view code, JS::MutableHandleValue rval) const
     764             : {
     765          66 :     Request rq(this);
     766             : 
     767          66 :     JS::CompileOptions opts(rq.cx);
     768          66 :     opts.setFileAndLine("(eval)", 1);
     769          66 :     opts.setForceStrictMode();
     770          66 :     JS::SourceText<mozilla::Utf8Unit> src;
     771          66 :     ENSURE(src.init(rq.cx, code.data(), code.size(), JS::SourceOwnership::Borrowed));
     772          66 :     if (JS::Evaluate(rq.cx, opts, src, rval))
     773             :         return true;
     774             : 
     775           0 :     Exception::CatchPending(rq);
     776             :     return false;
     777          66 : }
     778             : 
     779             : } // namespace Script

Generated by: LCOV version 1.16