LCOV - code coverage report
Current view: top level - source/scriptinterface - Context.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 80 93 86.0 %
Date: 2026-12-03 01:19:39 Functions: 8 9 88.9 %

          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 "Context.h"
      21             : 
      22             : #include "js/Modules.h"
      23             : #include "lib/alignment.h"
      24             : #include "lib/debug.h"
      25             : #include "ps/Profile.h"
      26             : #include "ps/Profiler2.h"
      27             : #include "ps/ThreadUtil.h"
      28             : #include "scriptinterface/ModuleLoader.h"
      29             : #include "scriptinterface/Promises.h"
      30             : #include "scriptinterface/Engine.h"
      31             : 
      32             : #include <js/Context.h>
      33             : #include <js/GCAPI.h>
      34             : #include <js/Initialization.h>
      35             : #include <js/Promise.h>
      36             : #include <js/SliceBudget.h>
      37             : #include <js/Stack.h>
      38             : #include <jsapi.h>
      39             : #include <jsfriendapi.h>
      40             : 
      41             : namespace JS { class Realm; }
      42             : struct JSContext;
      43             : struct JSRuntime;
      44             : 
      45        2220 : void GCSliceCallbackHook(JSContext*, JS::GCProgress progress, const JS::GCDescription&)
      46             : {
      47             :     /**
      48             :      * From the GCAPI.h file:
      49             :      * > During GC, the GC is bracketed by GC_CYCLE_BEGIN/END callbacks. Each
      50             :      * > slice between those (whether an incremental or the sole non-incremental
      51             :      * > slice) is bracketed by GC_SLICE_BEGIN/GC_SLICE_END.
      52             :      * Thus, to safely monitor GCs, we need to profile SLICE_X calls.
      53             :      */
      54             : 
      55             : 
      56        2220 :     if (progress == JS::GC_SLICE_BEGIN)
      57             :     {
      58         555 :         if (CProfileManager::IsInitialised() && Threading::IsMainThread())
      59           3 :             g_Profiler.Start("GCSlice");
      60         555 :         g_Profiler2.RecordRegionEnter("GCSlice");
      61             :     }
      62        1665 :     else if (progress == JS::GC_SLICE_END)
      63             :     {
      64         555 :         if (CProfileManager::IsInitialised() && Threading::IsMainThread())
      65           3 :             g_Profiler.Stop();
      66         555 :         g_Profiler2.RecordRegionLeave();
      67             :     }
      68             : 
      69             :     // The following code can be used to print some information aobut garbage collection
      70             :     // Search for "Nonincremental reason" if there are problems running GC incrementally.
      71             :     #if 0
      72             :     if (progress == JS::GCProgress::GC_CYCLE_BEGIN)
      73             :         printf("starting cycle ===========================================\n");
      74             : 
      75             :     //const char16_t* str = desc.formatMessage(cx);
      76             :     const char16_t* str = desc.formatSliceMessage(cx);
      77             :     int len = 0;
      78             : 
      79             :     for(int i = 0; i < 10000; i++)
      80             :     {
      81             :         len++;
      82             :         if(!str[i])
      83             :             break;
      84             :     }
      85             : 
      86             :     wchar_t outstring[len];
      87             : 
      88             :     for(int i = 0; i < len; i++)
      89             :     {
      90             :         outstring[i] = (wchar_t)str[i];
      91             :     }
      92             : 
      93             :     printf("---------------------------------------\n: %ls \n---------------------------------------\n", outstring);
      94             : 
      95             :     const uint32_t gcBytes = JS_GetGCParameter(cx, JSGC_BYTES);
      96             : 
      97             :     printf("gcBytes: %i KB\n", gcBytes / 1024);
      98             : 
      99             :     if (progress == JS::GCProgress::GC_SLICE_END)
     100             :         printf("ending cycle ===========================================\n");
     101             :     #endif
     102        2220 : }
     103             : 
     104             : namespace Script
     105             : {
     106             : 
     107           1 : Context::Context(int contextSize, uint32_t heapGrowthBytesGCTrigger):
     108           1 :     m_JobQueue{std::make_unique<JobQueue>()},
     109           1 :     m_ContextSize{contextSize},
     110           1 :     m_HeapGrowthBytesGCTrigger{heapGrowthBytesGCTrigger}
     111             : {
     112           1 :     ENSURE(Engine::IsInitialised() && "The Script::Engine must be initialized before constructing any ScriptContexts!");
     113             : 
     114           1 :     m_cx = JS_NewContext(contextSize);
     115           1 :     ENSURE(m_cx); // TODO: error handling
     116             : 
     117             :     // Set stack quota limits - JS scripts will stop with a "too much recursion" exception.
     118             :     // This seems to refer to the program's actual stack size, so it should be lower than the lowest common denominator
     119             :     // of the various stack sizes of supported OS.
     120             :     // From SM78's jsapi.h:
     121             :     // - "The stack quotas for each kind of code should be monotonically descending"
     122             :     // - "This function may only be called immediately after the runtime is initialized
     123             :     //   and before any code is executed and/or interrupts requested"
     124           1 :     JS_SetNativeStackQuota(m_cx, 950 * KiB, 900 * KiB, 850 * KiB);
     125             : 
     126           1 :     ENSURE(JS::InitSelfHostedCode(m_cx));
     127             : 
     128           1 :     JS::SetGCSliceCallback(m_cx, GCSliceCallbackHook);
     129             : 
     130           1 :     JS_SetGCParameter(m_cx, JSGC_MAX_BYTES, m_ContextSize);
     131           1 :     JS_SetGCParameter(m_cx, JSGC_INCREMENTAL_GC_ENABLED, true);
     132           1 :     JS_SetGCParameter(m_cx, JSGC_PER_ZONE_GC_ENABLED, false);
     133             : 
     134             :     // Set a low time budget to avoid lag spikes, but allow any number of last ditch GCs
     135             :     // to avoid OOM errors.
     136           1 :     JS_SetGCParameter(m_cx, JSGC_SLICE_TIME_BUDGET_MS, 6);
     137           1 :     JS_SetGCParameter(m_cx, JSGC_MIN_LAST_DITCH_GC_PERIOD, 0);
     138             : 
     139             :     // Turn off nursery size heuristic.
     140             :     // See https://gitea.wildfiregames.com/0ad/0ad/issues/7714 for details.
     141           1 :     JS_SetGCParameter(m_cx, JSGC_NURSERY_MAX_TIME_GOAL_MS, 0);
     142             : 
     143           1 :     JS_SetOffthreadIonCompilationEnabled(m_cx, true);
     144             : 
     145             :     // For GC debugging:
     146             :     // JS_SetGCZeal(m_cx, 2, JS_DEFAULT_ZEAL_FREQ);
     147             : 
     148           1 :     JS_SetContextPrivate(m_cx, nullptr);
     149             : 
     150           1 :     JS_SetGlobalJitCompilerOption(m_cx, JSJITCOMPILER_ION_ENABLE, 1);
     151           1 :     JS_SetGlobalJitCompilerOption(m_cx, JSJITCOMPILER_BASELINE_ENABLE, 1);
     152             : 
     153             :     // Turn off Spectre mitigations - this is a huge speedup on JS code, particularly JS -> C++ calls.
     154           1 :     JS_SetGlobalJitCompilerOption(m_cx, JSJITCOMPILER_SPECTRE_JIT_TO_CXX_CALLS, 0);
     155           1 :     JS_SetGlobalJitCompilerOption(m_cx, JSJITCOMPILER_SPECTRE_INDEX_MASKING, 0);
     156           1 :     JS_SetGlobalJitCompilerOption(m_cx, JSJITCOMPILER_SPECTRE_VALUE_MASKING, 0);
     157           1 :     JS_SetGlobalJitCompilerOption(m_cx, JSJITCOMPILER_SPECTRE_STRING_MITIGATIONS, 0);
     158           1 :     JS_SetGlobalJitCompilerOption(m_cx, JSJITCOMPILER_SPECTRE_OBJECT_MITIGATIONS, 0);
     159             : 
     160           1 :     Engine::GetSingleton().RegisterContext(m_cx);
     161             : 
     162           1 :     JS::SetJobQueue(m_cx, m_JobQueue.get());
     163           1 :     JS::SetPromiseRejectionTrackerCallback(m_cx, &UnhandledRejectedPromise);
     164             : 
     165           1 :     JSRuntime* runtime{JS_GetRuntime(m_cx)};
     166           1 :     JS::SetModuleMetadataHook(runtime, &ModuleLoader::MetadataHook);
     167           1 :     JS::SetModuleResolveHook(runtime, &ModuleLoader::ResolveHook);
     168           1 :     JS::SetModuleDynamicImportHook(runtime, &ModuleLoader::DynamicImportHook);
     169           1 : }
     170             : 
     171           2 : Context::~Context()
     172             : {
     173           1 :     ENSURE(Engine::IsInitialised() && "The Script::Engine must be active (initialized and not yet shut down) when destroying a Script::Context!");
     174             : 
     175           1 :     JSRuntime* runtime{JS_GetRuntime(m_cx)};
     176           1 :     JS::SetModuleDynamicImportHook(runtime, nullptr);
     177           1 :     JS::SetModuleResolveHook(runtime, nullptr);
     178           1 :     JS::SetModuleMetadataHook(runtime, nullptr);
     179             : 
     180           1 :     JS_DestroyContext(m_cx);
     181           1 :     Engine::GetSingleton().UnRegisterContext(m_cx);
     182           2 : }
     183             : 
     184         377 : void Context::RegisterRealm(JS::Realm* realm)
     185             : {
     186         377 :     ENSURE(realm);
     187         377 :     m_Realms.push_back(realm);
     188         377 : }
     189             : 
     190         377 : void Context::UnRegisterRealm(JS::Realm* realm)
     191             : {
     192             :     // Schedule the zone for GC, which will destroy the realm.
     193         377 :     if (JS::IsIncrementalGCInProgress(m_cx))
     194           0 :         JS::FinishIncrementalGC(m_cx, JS::GCReason::API);
     195         377 :     JS::PrepareZoneForGC(m_cx, js::GetRealmZone(realm));
     196         377 :     m_Realms.remove(realm);
     197         377 : }
     198             : 
     199             : #define GC_DEBUG_PRINT 0
     200         191 : void Context::MaybeIncrementalGC()
     201             : {
     202         191 :     PROFILE2("MaybeIncrementalGC");
     203             : 
     204         191 :     if (!JS::IsIncrementalGCEnabled(m_cx))
     205           0 :         return;
     206             : 
     207             :     // The idea is to get the heap size after a completed GC and trigger the next GC
     208             :     // when the heap size has reached m_LastGCBytes + X.
     209             :     // Spidermonkey allocates memory arenas of 4KB for JS heap data.
     210             :     // At the end of a GC, any such arena that became empty is freed.
     211             :     // On shrinking GCs, spidermonkey further defragments the arenas, which effectively frees more memory but costs time.
     212             :     // In practice, shrinking GCs also dump JITted code and the defragmentation is not worth it for 0 A.D.
     213             :     // The regular GCs also free quite a bit of memory anyways, and non-full arenas get used for new objects.
     214             : 
     215         191 :     const uint32_t gcBytes = JS_GetGCParameter(m_cx, JSGC_BYTES);
     216             : 
     217             : #if GC_DEBUG_PRINT
     218             :     printf("gcBytes: %i KB, last of %i KB\n", gcBytes / 1024, m_LastGCBytes / 1024);
     219             : #endif
     220             : 
     221             :     // The memory freeing happens mostly in the background, so we can't rely on the value on the last incremental slice.
     222             :     // To fix that, just remember a 'minimum' value.
     223         191 :     if (m_LastGCBytes > gcBytes || m_LastGCBytes == 0)
     224             :     {
     225             : #if GC_DEBUG_PRINT
     226             :         printf("Setting m_LastGCBytes: %d KB \n", gcBytes / 1024);
     227             : #endif
     228           3 :         m_LastGCBytes = gcBytes;
     229             :     }
     230             : 
     231             :     // Run an additional incremental GC slice if the currently running incremental GC isn't over yet
     232             :     // ... or
     233             :     // start a new incremental GC if the JS heap size has grown enough for a GC to make sense
     234         191 :     if (JS::IsIncrementalGCInProgress(m_cx) || (gcBytes - m_LastGCBytes > m_HeapGrowthBytesGCTrigger))
     235             :     {
     236             : #if GC_DEBUG_PRINT
     237             :         if (JS::IsIncrementalGCInProgress(m_cx))
     238             :             printf("An incremental GC cycle is in progress. \n");
     239             :         else
     240             :             printf("GC needed because JSGC_BYTES - m_LastGCBytes > m_HeapGrowthBytesGCTrigger \n"
     241             :                 "    JSGC_BYTES: %d KB \n    m_LastGCBytes: %d KB \n    m_HeapGrowthBytesGCTrigger: %d KB \n",
     242             :                 gcBytes / 1024,
     243             :                 m_LastGCBytes / 1024,
     244             :                 m_HeapGrowthBytesGCTrigger / 1024);
     245             : #endif
     246             : 
     247             : #if GC_DEBUG_PRINT
     248             :         if (!JS::IsIncrementalGCInProgress(m_cx))
     249             :             printf("Starting incremental GC \n");
     250             :         else
     251             :             printf("Running incremental GC slice \n");
     252             : #endif
     253             : 
     254             :         // There is a tradeoff between this time and the number of frames we must run GCs on, but overall we should prioritize smooth framerates.
     255           0 :         const JS::SliceBudget GCSliceTimeBudget = JS::SliceBudget(JS::TimeBudget(6)); // Milliseconds an incremental slice is allowed to run. SM respects this fairly well.
     256             : 
     257           0 :         PrepareZonesForIncrementalGC();
     258           0 :         if (!JS::IsIncrementalGCInProgress(m_cx))
     259           0 :             JS::StartIncrementalGC(m_cx, JS::GCOptions::Normal, JS::GCReason::API, GCSliceTimeBudget);
     260             :         else
     261           0 :             JS::IncrementalGCSlice(m_cx, JS::GCReason::API, GCSliceTimeBudget);
     262             : 
     263             :         // Reset this here so that the minimum gets cleared.
     264           0 :         m_LastGCBytes = gcBytes;
     265           0 :     }
     266         191 : }
     267             : 
     268         554 : void Context::ShrinkingGC()
     269             : {
     270         554 :     JS_SetGCParameter(m_cx, JSGC_INCREMENTAL_GC_ENABLED, false);
     271         554 :     JS_SetGCParameter(m_cx, JSGC_PER_ZONE_GC_ENABLED, true);
     272         554 :     JS::PrepareForFullGC(m_cx);
     273         554 :     JS::NonIncrementalGC(m_cx, JS::GCOptions::Shrink, JS::GCReason::API);
     274         554 :     JS_SetGCParameter(m_cx, JSGC_INCREMENTAL_GC_ENABLED, true);
     275         554 :     JS_SetGCParameter(m_cx, JSGC_PER_ZONE_GC_ENABLED, false);
     276         554 : }
     277             : 
     278         644 : void Context::RunJobs()
     279             : {
     280         644 :     m_JobQueue->runJobs(m_cx);
     281         644 : }
     282             : 
     283           0 : void Context::PrepareZonesForIncrementalGC() const
     284             : {
     285           0 :     for (JS::Realm* const& realm : m_Realms)
     286           0 :         JS::PrepareZoneForGC(m_cx, js::GetRealmZone(realm));
     287           0 : }
     288             : 
     289             : } // namespace Script

Generated by: LCOV version 1.16