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 "StructuredClone.h" 21 : 22 : #include "lib/debug.h" 23 : #include "ps/Profile.h" 24 : #include "scriptinterface/Exceptions.h" 25 : #include "scriptinterface/Request.h" 26 : 27 : #include <js/CallArgs.h> 28 : #include <js/RootingAPI.h> 29 : #include <js/StructuredClone.h> 30 : 31 : namespace Script { class Interface; } 32 : 33 624 : Script::StructuredClone Script::WriteStructuredClone(const Script::Request& rq, JS::HandleValue v) 34 : { 35 624 : Script::StructuredClone ret(new JSStructuredCloneData(JS::StructuredCloneScope::SameProcess)); 36 624 : JS::CloneDataPolicy policy; 37 624 : if (!JS_WriteStructuredClone(rq.cx, v, ret.get(), JS::StructuredCloneScope::SameProcess, policy, nullptr, nullptr, JS::UndefinedHandleValue)) 38 : { 39 0 : debug_warn(L"Writing a structured clone with JS_WriteStructuredClone failed!"); 40 0 : Script::Exception::CatchPending(rq); 41 0 : return StructuredClone(); 42 : } 43 : 44 624 : return ret; 45 624 : } 46 : 47 612 : void Script::ReadStructuredClone(const Script::Request& rq, const Script::StructuredClone& ptr, JS::MutableHandleValue ret) 48 : { 49 612 : JS::CloneDataPolicy policy; 50 612 : if (!JS_ReadStructuredClone(rq.cx, *ptr, JS_STRUCTURED_CLONE_VERSION, ptr->scope(), ret, policy, nullptr, nullptr)) 51 0 : Script::Exception::CatchPending(rq); 52 612 : } 53 : 54 3 : JS::Value Script::CloneValueFromOtherCompartment(const Script::Interface& to, const Script::Interface& from, JS::HandleValue val) 55 : { 56 3 : PROFILE("CloneValueFromOtherCompartment"); 57 3 : Script::StructuredClone structuredClone; 58 3 : { 59 3 : Script::Request fromRq(from); 60 3 : structuredClone = WriteStructuredClone(fromRq, val); 61 3 : } 62 3 : Script::Request toRq(to); 63 3 : JS::RootedValue out(toRq.cx); 64 3 : ReadStructuredClone(toRq, structuredClone, &out); 65 6 : return out.get(); 66 6 : } 67 : 68 583 : JS::Value Script::DeepCopy(const Script::Request& rq, JS::HandleValue val) 69 : { 70 583 : JS::RootedValue out(rq.cx); 71 583 : ReadStructuredClone(rq, WriteStructuredClone(rq, val), &out); 72 583 : return out.get(); 73 583 : }