소스 검색

fix(scripting): release OpaqueScriptableObjectAdapter when the JS object is finalized (#619)

ScriptableObjectAdapter::instantiate allocates an OpaqueScriptableObjectAdapter
on the heap and stores it via JS_SetOpaque, but the JSClassDef passed to
JS_NewClass has no finalizer. QuickJS releases the JSValue when the object
is unreachable, leaving the heap struct leaked for the lifetime of the
runtime.

JS_DUMP_LEAKS is enabled on the runtime (ScriptEngine.cpp:199) so this is
observable: every ScriptableObject (the 'ILayer' root object exposed to
scene scripts) reports a leak on shutdown.

Match the pattern used by VectorAdapter::vector_finalizer
(src/WallpaperEngine/Scripting/Adapters/VectorAdapter.cpp:398): a free
function with the standard (JSRuntime*, JSValueConst) signature that
fetches the opaque via JS_GetAnyOpaque, validates the magic, and deletes
the container. Wire it into the JSClassDef in the adapter constructor.
David Mireles 1 개월 전
부모
커밋
5da5073466
1개의 변경된 파일과 15개의 추가작업 그리고 0개의 파일을 삭제
  1. 15 0
      src/WallpaperEngine/Scripting/Adapters/ScriptableObjectAdapter.cpp

+ 15 - 0
src/WallpaperEngine/Scripting/Adapters/ScriptableObjectAdapter.cpp

@@ -18,6 +18,8 @@ struct OpaqueScriptableObjectAdapter {
     WallpaperEngine::Scripting::ScriptableObject& object;
 };
 
+void scriptableobject_finalizer (JSRuntime* rt, JSValueConst val);
+
 JSValue scriptableobject_property_get (JSContext* ctx, JSValueConst obj_val, JSAtom atom, JSValueConst receiver) {
     JSClassID classId = 0;
 
@@ -70,6 +72,7 @@ ScriptableObjectAdapter::ScriptableObjectAdapter (ScriptEngine& engine, std::str
     this->registerType (
 	{
 	    .class_name = m_name.c_str (),
+	    .finalizer = scriptableobject_finalizer,
 	    .exotic = &m_exoticMethods,
 	}
     );
@@ -85,6 +88,18 @@ JSValue ScriptableObjectAdapter::instantiate (ScriptableObject& object) {
     return result;
 }
 
+void scriptableobject_finalizer (JSRuntime* rt, JSValueConst val) {
+    JSClassID classId = 0;
+
+    const auto* container = static_cast<OpaqueScriptableObjectAdapter*> (JS_GetAnyOpaque (val, &classId));
+
+    if (container == nullptr || container->magic != SCRIPTABLE_OPAQUE_MAGIC) {
+	return;
+    }
+
+    delete container;
+}
+
 JSValue ScriptableObjectAdapter::instantiate (DynamicValue& value) {
     throw std::runtime_error ("Cannot create a ScriptableObject instance from a DynamicValue");
 }