From 9521e6cdf91228f95c0770245d0b2aaaf961be48 Mon Sep 17 00:00:00 2001 From: itu-itis24-iyigun24 Date: Mon, 26 Oct 2026 03:00:41 +0300 Subject: [PATCH] Fix use-after-free when unregistering script classes twice (#27143) ScBase::Unregister() freed the class prototype but kept proto and protoCtx. The script classes are globals and the JS runtime is freed when a context is destroyed, so these values become dangling pointers. The script classes are registered only by ScriptEngine::Initialise(), but ~ScriptEngine() always unregisters them. Destroying a context whose script engine was never initialised, after an initialised one had been destroyed, therefore freed the stale prototype again through the freed JSContext. On Windows this crashed WaterObjectTest when it ran after TileElementsViewTests in the same test process. Reset proto and protoCtx after freeing them, and add a test that destroys an uninitialised context after an initialised one. Co-authored-by: Claude Opus 5 (1M context) --- src/openrct2/scripting/ScriptEngine.h | 2 ++ test/tests/ScriptingTests.cpp | 17 +++++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/src/openrct2/scripting/ScriptEngine.h b/src/openrct2/scripting/ScriptEngine.h index 8f1c2b6818..cc52747324 100644 --- a/src/openrct2/scripting/ScriptEngine.h +++ b/src/openrct2/scripting/ScriptEngine.h @@ -333,6 +333,8 @@ namespace OpenRCT2::Scripting classId = JS_INVALID_CLASS_ID; if (protoCtx != nullptr) JS_FreeValue(protoCtx, proto); + proto = JS_NULL; + protoCtx = nullptr; } [[nodiscard]] JSValue GetProto() const diff --git a/test/tests/ScriptingTests.cpp b/test/tests/ScriptingTests.cpp index 712a7914fb..f5b0b2527d 100644 --- a/test/tests/ScriptingTests.cpp +++ b/test/tests/ScriptingTests.cpp @@ -73,4 +73,21 @@ TEST_F(ScriptingTests, MultipleSubscribersToSameEventShouldNotCrash) hookEngine.Call(HookType::intervalTick, arg, false); } +TEST(ScriptEngineLifetimeTests, UninitialisedContextCanBeDestroyedAfterInitialisedOne) +{ + gOpenRCT2Headless = true; + gOpenRCT2NoGraphics = true; + + // Registers the global script classes and then frees the JS runtime they belong to. + { + auto context = CreateContext(); + context->GetScriptEngine().Initialise(); + } + + // Unregisters the global script classes again without registering them first. + { + auto context = CreateContext(); + } +} + #endif