LCOV - code coverage report
Current view: top level - source/simulation2/serialization - BinarySerializer.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 211 259 81.5 %
Date: 2026-12-03 01:19:39 Functions: 7 8 87.5 %

          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 "BinarySerializer.h"
      21             : 
      22             : #include "lib/utf8.h"
      23             : #include "ps/CLogger.h"
      24             : #include "scriptinterface/FunctionWrapper.h"
      25             : #include "scriptinterface/JSON.h"
      26             : #include "scriptinterface/Request.h"
      27             : #include "simulation2/serialization/SerializedScriptTypes.h"
      28             : 
      29             : #include <cmath>
      30             : #include <js/Array.h>
      31             : #include <js/ArrayBuffer.h>
      32             : #include <js/Class.h>
      33             : #include <js/ComparisonOperators.h>
      34             : #include <js/Conversions.h>
      35             : #include <js/ForOfIterator.h>
      36             : #include <js/GCAPI.h>
      37             : #include <js/MapAndSet.h>
      38             : #include <js/Object.h>
      39             : #include <js/PropertyAndElement.h>
      40             : #include <js/PropertyDescriptor.h>
      41             : #include <js/ScalarType.h>
      42             : #include <js/String.h>
      43             : #include <js/Value.h>
      44             : #include <js/experimental/TypedData.h>
      45             : #include <jsapi.h>
      46             : #include <jspubtd.h>
      47             : #include <mozilla/HashTable.h>
      48             : #include <mozilla/Maybe.h>
      49             : 
      50             : class JSObject;
      51             : 
      52          32 : static std::uint8_t GetArrayType(js::Scalar::Type arrayType)
      53             : {
      54          32 :     switch(arrayType)
      55             :     {
      56             :     case js::Scalar::Int8:
      57             :         return SCRIPT_TYPED_ARRAY_INT8;
      58             :     case js::Scalar::Uint8:
      59             :         return SCRIPT_TYPED_ARRAY_UINT8;
      60             :     case js::Scalar::Int16:
      61             :         return SCRIPT_TYPED_ARRAY_INT16;
      62             :     case js::Scalar::Uint16:
      63             :         return SCRIPT_TYPED_ARRAY_UINT16;
      64             :     case js::Scalar::Int32:
      65             :         return SCRIPT_TYPED_ARRAY_INT32;
      66             :     case js::Scalar::Uint32:
      67             :         return SCRIPT_TYPED_ARRAY_UINT32;
      68             :     case js::Scalar::Float32:
      69             :         return SCRIPT_TYPED_ARRAY_FLOAT32;
      70             :     case js::Scalar::Float64:
      71             :         return SCRIPT_TYPED_ARRAY_FLOAT64;
      72             :     case js::Scalar::Uint8Clamped:
      73             :         return SCRIPT_TYPED_ARRAY_UINT8_CLAMPED;
      74           0 :     default:
      75           0 :         LOGERROR("Cannot serialize unrecognized typed array view: {}", static_cast<int>(arrayType));
      76           0 :         throw PSERROR_Serialize_InvalidScriptValue();
      77             :     }
      78             : }
      79             : 
      80         156 : CBinarySerializerScriptImpl::CBinarySerializerScriptImpl(const Script::Interface& scriptInterface, ISerializer& serializer) :
      81         156 :     m_ScriptInterface(scriptInterface), m_Serializer(serializer), m_ScriptBackrefsNext(0)
      82             : {
      83         156 :     Script::Request rq(m_ScriptInterface);
      84         156 :     JS_AddExtraGCRootsTracer(rq.cx, Trace, this);
      85         156 :     m_SerializePropId = JS::PropertyKey::fromPinnedString(JS_AtomizeAndPinString(rq.cx, "Serialize"));
      86         156 :     m_DeserializePropId = JS::PropertyKey::fromPinnedString(JS_AtomizeAndPinString(rq.cx, "Deserialize"));
      87         156 : }
      88             : 
      89         156 : CBinarySerializerScriptImpl::~CBinarySerializerScriptImpl()
      90             : {
      91         156 :     Script::Request rq(m_ScriptInterface);
      92         156 :     JS_RemoveExtraGCRootsTracer(rq.cx, Trace, this);
      93         156 : }
      94             : 
      95       25201 : void CBinarySerializerScriptImpl::PutScriptVal(JS::HandleValue val)
      96             : {
      97       25201 :     HandleScriptVal(Script::Request(m_ScriptInterface), val);
      98       25198 : }
      99             : 
     100      137177 : void CBinarySerializerScriptImpl::HandleScriptVal(const Script::Request& rq, JS::HandleValue val)
     101             : {
     102      137177 :     switch (JS_TypeOfValue(rq.cx, val))
     103             :     {
     104        7862 :     case JSTYPE_UNDEFINED:
     105        7862 :     {
     106        7862 :         m_Serializer.NumberU8_Unbounded("type", SCRIPT_TYPE_VOID);
     107             :         break;
     108             :     }
     109       59731 :     case JSTYPE_OBJECT:
     110       59731 :     {
     111       59731 :         if (val.isNull())
     112             :         {
     113         218 :             m_Serializer.NumberU8_Unbounded("type", SCRIPT_TYPE_NULL);
     114             :             break;
     115             :         }
     116             : 
     117       59513 :         JS::RootedObject obj(rq.cx, &val.toObject());
     118             : 
     119             :         // If we've already serialized this object, just output a reference to it
     120       59513 :         std::uint32_t tag = GetScriptBackrefTag(rq, obj);
     121       59513 :         if (tag != 0)
     122             :         {
     123        2021 :             m_Serializer.NumberU8_Unbounded("type", SCRIPT_TYPE_BACKREF);
     124        2021 :             m_Serializer.NumberU32("tag", tag, 0, JSVAL_INT_MAX);
     125             :             break;
     126             :         }
     127             : 
     128             :         // Arrays, Maps and Sets are special cases of Objects
     129       57492 :         bool isArray;
     130       57492 :         bool isMap;
     131       57492 :         bool isSet;
     132             : 
     133       57492 :         if (JS::IsArrayObject(rq.cx, obj, &isArray) && isArray)
     134             :         {
     135       15962 :             m_Serializer.NumberU8_Unbounded("type", SCRIPT_TYPE_ARRAY);
     136             :             // TODO: probably should have a more efficient storage format
     137             : 
     138             :             // Arrays like [1, 2, ] have an 'undefined' at the end which is part of the
     139             :             // length but seemingly isn't enumerated, so store the length explicitly
     140       15962 :             unsigned int length = 0;
     141       15962 :             if (!JS::GetArrayLength(rq.cx, obj, &length))
     142           0 :                 throw PSERROR_Serialize_ScriptError("JS::GetArrayLength failed");
     143       31924 :             m_Serializer.NumberU32_Unbounded("array length", length);
     144             :         }
     145       41530 :         else if (JS_IsTypedArrayObject(obj))
     146             :         {
     147          32 :             m_Serializer.NumberU8_Unbounded("type", SCRIPT_TYPE_TYPED_ARRAY);
     148             : 
     149          32 :             m_Serializer.NumberU8_Unbounded("array type", GetArrayType(JS_GetArrayBufferViewType(obj)));
     150          32 :             m_Serializer.NumberU32_Unbounded("byte offset", JS_GetTypedArrayByteOffset(obj));
     151          32 :             m_Serializer.NumberU32_Unbounded("length", JS_GetTypedArrayLength(obj));
     152             : 
     153          32 :             bool sharedMemory;
     154             :             // Now handle its array buffer
     155             :             // this may be a backref, since ArrayBuffers can be shared by multiple views
     156          32 :             JS::RootedValue bufferVal(rq.cx, JS::ObjectValue(*JS_GetArrayBufferViewBuffer(rq.cx, obj, &sharedMemory)));
     157          32 :             HandleScriptVal(rq, bufferVal);
     158          32 :             break;
     159          32 :         }
     160       41498 :         else if (JS::IsArrayBufferObject(obj))
     161             :         {
     162          24 :             m_Serializer.NumberU8_Unbounded("type", SCRIPT_TYPE_ARRAY_BUFFER);
     163             : 
     164             : #if BYTE_ORDER != LITTLE_ENDIAN
     165             : #error TODO: need to convert JS ArrayBuffer data to little-endian
     166             : #endif
     167             : 
     168          24 :             std::uint32_t length = JS::GetArrayBufferByteLength(obj);
     169          24 :             m_Serializer.NumberU32_Unbounded("buffer length", length);
     170          24 :             JS::AutoCheckCannotGC nogc;
     171          24 :             bool sharedMemory;
     172          24 :             m_Serializer.RawBytes("buffer data", static_cast<const std::uint8_t*>(
     173          24 :                 JS::GetArrayBufferData(obj, &sharedMemory, nogc)), length);
     174          24 :             break;
     175             :         }
     176             : 
     177       41474 :         else if (JS::IsMapObject(rq.cx, obj, &isMap) && isMap)
     178             :         {
     179        1098 :             m_Serializer.NumberU8_Unbounded("type", SCRIPT_TYPE_OBJECT_MAP);
     180        1098 :             m_Serializer.NumberU32_Unbounded("map size", JS::MapSize(rq.cx, obj));
     181             : 
     182        1098 :             JS::RootedValue keyValueIterator(rq.cx);
     183        1098 :             if (!JS::MapEntries(rq.cx, obj, &keyValueIterator))
     184           0 :                 throw PSERROR_Serialize_ScriptError("JS::MapEntries failed");
     185             : 
     186        1098 :             JS::ForOfIterator it(rq.cx);
     187        1098 :             if (!it.init(keyValueIterator))
     188           0 :                 throw PSERROR_Serialize_ScriptError("JS::ForOfIterator::init failed");
     189             : 
     190        1098 :             JS::RootedValue keyValuePair(rq.cx);
     191        2124 :             bool done;
     192        3150 :             while (true)
     193             :             {
     194        2124 :                 if (!it.next(&keyValuePair, &done))
     195           0 :                     throw PSERROR_Serialize_ScriptError("JS::ForOfIterator::next failed");
     196             : 
     197        2124 :                 if (done)
     198             :                     break;
     199             : 
     200        1026 :                 JS::RootedObject keyValuePairObj(rq.cx, &keyValuePair.toObject());
     201        1026 :                 JS::RootedValue key(rq.cx);
     202        1026 :                 JS::RootedValue value(rq.cx);
     203        1026 :                 ENSURE(JS_GetElement(rq.cx, keyValuePairObj, 0, &key));
     204        1026 :                 ENSURE(JS_GetElement(rq.cx, keyValuePairObj, 1, &value));
     205             : 
     206        1026 :                 HandleScriptVal(rq, key);
     207        1026 :                 HandleScriptVal(rq, value);
     208        1026 :             }
     209        1098 :             break;
     210        1098 :         }
     211             : 
     212       40376 :         else if (JS::IsSetObject(rq.cx, obj, &isSet) && isSet)
     213             :         {
     214        1118 :             m_Serializer.NumberU8_Unbounded("type", SCRIPT_TYPE_OBJECT_SET);
     215        1118 :             m_Serializer.NumberU32_Unbounded("set size", JS::SetSize(rq.cx, obj));
     216             : 
     217        1118 :             JS::RootedValue valueIterator(rq.cx);
     218        1118 :             if (!JS::SetValues(rq.cx, obj, &valueIterator))
     219           0 :                 throw PSERROR_Serialize_ScriptError("JS::SetValues failed");
     220             : 
     221        1118 :             JS::ForOfIterator it(rq.cx);
     222        1118 :             if (!it.init(valueIterator))
     223           0 :                 throw PSERROR_Serialize_ScriptError("JS::ForOfIterator::init failed");
     224             : 
     225        1118 :             JS::RootedValue value(rq.cx);
     226        2314 :             bool done;
     227        3510 :             while (true)
     228             :             {
     229        2314 :                 if (!it.next(&value, &done))
     230           0 :                     throw PSERROR_Serialize_ScriptError("JS::ForOfIterator::next failed");
     231             : 
     232        2314 :                 if (done)
     233             :                     break;
     234             : 
     235        1196 :                 HandleScriptVal(rq, value);
     236             :             }
     237        1118 :             break;
     238        1118 :         }
     239             : 
     240             :         else
     241             :         {
     242             :             // Find type of object
     243       39258 :             const JSClass* jsclass = JS::GetClass(obj);
     244       39258 :             if (!jsclass)
     245           0 :                 throw PSERROR_Serialize_ScriptError("JS::GetClass failed");
     246             : 
     247       39258 :             JSProtoKey protokey = JSCLASS_CACHED_PROTO_KEY(jsclass);
     248             : 
     249       39258 :             if (protokey == JSProto_Object)
     250             :             {
     251             :                 // Object class - check for user-defined prototype
     252       39246 :                 JS::RootedObject proto(rq.cx);
     253       39246 :                 if (!JS_GetPrototype(rq.cx, obj, &proto))
     254           0 :                     throw PSERROR_Serialize_ScriptError("JS_GetPrototype failed");
     255             : 
     256       39246 :                 SPrototypeSerialization protoInfo = GetPrototypeInfo(rq, proto, m_SerializePropId, m_DeserializePropId);
     257             : 
     258       39246 :                 if (protoInfo.name == L"Object")
     259       47537 :                     m_Serializer.NumberU8_Unbounded("type", SCRIPT_TYPE_OBJECT);
     260             :                 else
     261             :                 {
     262       22589 :                     m_Serializer.NumberU8_Unbounded("type", SCRIPT_TYPE_OBJECT_PROTOTYPE);
     263       22589 :                     m_Serializer.String("proto", protoInfo.name, 0, 256);
     264             : 
     265             :                     // Does it have custom Serialize function?
     266             :                     // if so, we serialize the data it returns, rather than the object's properties directly
     267       22589 :                     if (protoInfo.hasCustomSerialize)
     268             :                     {
     269             :                         // If serialize is null, don't serialize anything more
     270        8366 :                         if (!protoInfo.hasNullSerialize)
     271             :                         {
     272        3173 :                             JS::RootedValue data(rq.cx);
     273        3173 :                             if (!Script::Function::Call(rq, val, "Serialize", &data))
     274           0 :                                 throw PSERROR_Serialize_ScriptError("Prototype Serialize function failed");
     275        3173 :                             m_Serializer.ScriptVal("data", &data);
     276        3173 :                         }
     277             :                         // Break here to skip the custom object property serialization logic below.
     278        8366 :                         break;
     279             :                     }
     280             :                 }
     281       39246 :             }
     282          12 :             else if (protokey == JSProto_Number)
     283             :             {
     284             :                 // Get primitive value
     285           4 :                 double d;
     286           8 :                 if (!JS::ToNumber(rq.cx, val, &d))
     287           0 :                     throw PSERROR_Serialize_ScriptError("JS::ToNumber failed");
     288             : 
     289             :                 // Refuse to serialize NaN values: their representation can differ, leading to OOS
     290             :                 // and in general this is indicative of an underlying bug rather than desirable behaviour.
     291           4 :                 if (std::isnan(d))
     292             :                 {
     293           0 :                     LOGERROR("Cannot serialize NaN values.");
     294           0 :                     throw PSERROR_Serialize_InvalidScriptValue();
     295             :                 }
     296             : 
     297             :                 // Standard Number object
     298           4 :                 m_Serializer.NumberU8_Unbounded("type", SCRIPT_TYPE_OBJECT_NUMBER);
     299           4 :                 m_Serializer.NumberDouble_Unbounded("value", d);
     300           4 :                 break;
     301             :             }
     302           8 :             else if (protokey == JSProto_String)
     303             :             {
     304             :                 // Standard String object
     305           4 :                 m_Serializer.NumberU8_Unbounded("type", SCRIPT_TYPE_OBJECT_STRING);
     306             :                 // Get primitive value
     307           8 :                 JS::RootedString str(rq.cx, JS::ToString(rq.cx, val));
     308           4 :                 if (!str)
     309           0 :                     throw PSERROR_Serialize_ScriptError("JS_ValueToString failed");
     310           4 :                 ScriptString(rq, "value", str);
     311           4 :                 break;
     312           4 :             }
     313           4 :             else if (protokey == JSProto_Boolean)
     314             :             {
     315             :                 // Standard Boolean object
     316           4 :                 m_Serializer.NumberU8_Unbounded("type", SCRIPT_TYPE_OBJECT_BOOLEAN);
     317             :                 // Get primitive value
     318           4 :                 bool b = JS::ToBoolean(val);
     319           4 :                 m_Serializer.Bool("value", b);
     320             :                 break;
     321             :             }
     322             :             else
     323             :             {
     324             :                 // Unrecognized class
     325           3 :                 LOGERROR("Cannot serialize JS objects with unrecognized class '{}'",
     326             :                     jsclass->name);
     327           0 :                 throw PSERROR_Serialize_InvalidScriptValue();
     328             :             }
     329             :         }
     330             : 
     331             :         // Find all properties (ordered by insertion time)
     332      106355 :         JS::Rooted<JS::IdVector> ida(rq.cx, JS::IdVector(rq.cx));
     333       46845 :         if (!JS_Enumerate(rq.cx, obj, &ida))
     334           0 :             throw PSERROR_Serialize_ScriptError("JS_Enumerate failed");
     335             : 
     336       46842 :         m_Serializer.NumberU32_Unbounded("num props", static_cast<std::uint32_t>(ida.length()));
     337             : 
     338      155536 :         for (size_t i = 0; i < ida.length(); ++i)
     339             :         {
     340      108697 :             JS::RootedId id(rq.cx, ida[i]);
     341             : 
     342      108697 :             JS::RootedValue idval(rq.cx);
     343      108697 :             JS::RootedValue propval(rq.cx);
     344             : 
     345             :             // Forbid getters, which might delete values and mess things up.
     346      108697 :             JS::Rooted<mozilla::Maybe<JS::PropertyDescriptor>> desc(rq.cx);
     347      108697 :             JS::RootedObject holder(rq.cx);
     348      108697 :             if (!JS_GetPropertyDescriptorById(rq.cx, obj, id, &desc, &holder))
     349           0 :                 throw PSERROR_Serialize_ScriptError("JS_GetPropertyDescriptorById failed");
     350      108697 :             if (desc.isSome() && desc->hasGetter())
     351           1 :                 throw PSERROR_Serialize_ScriptError("Cannot serialize property getters");
     352             : 
     353             :             // Get the property name as a string
     354      108699 :             if (!JS_IdToValue(rq.cx, id, &idval))
     355           0 :                 throw PSERROR_Serialize_ScriptError("JS_IdToValue failed");
     356      217392 :             JS::RootedString idstr(rq.cx, JS::ToString(rq.cx, idval));
     357      108696 :             if (!idstr)
     358           0 :                 throw PSERROR_Serialize_ScriptError("JS_ValueToString failed");
     359             : 
     360      108696 :             ScriptString(rq, "prop name", idstr);
     361             : 
     362      108696 :             if (!JS_GetPropertyById(rq.cx, obj, id, &propval))
     363           0 :                 throw PSERROR_Serialize_ScriptError("JS_GetPropertyById failed");
     364             : 
     365      108696 :             HandleScriptVal(rq, propval);
     366      108697 :         }
     367             : 
     368       46839 :         break;
     369       59731 :     }
     370           1 :     case JSTYPE_FUNCTION:
     371           1 :     {
     372             :         // We can't serialise functions, but we can at least name the offender (hopefully)
     373           1 :         std::wstring funcname(L"(unnamed)");
     374           1 :         JS::RootedFunction func(rq.cx, JS_ValueToFunction(rq.cx, val));
     375           1 :         if (func)
     376             :         {
     377           1 :             JS::RootedString string(rq.cx, JS_GetMaybePartialFunctionId(func));
     378           1 :             if (string)
     379             :             {
     380           0 :                 if (JS::StringHasLatin1Chars(string))
     381             :                 {
     382           0 :                     size_t length;
     383           0 :                     JS::AutoCheckCannotGC nogc;
     384           0 :                     const JS::Latin1Char* ch = JS_GetLatin1StringCharsAndLength(rq.cx, nogc, string, &length);
     385           0 :                     if (ch && length > 0)
     386           0 :                         funcname.assign(ch, ch + length);
     387             :                 }
     388             :                 else
     389             :                 {
     390           0 :                     size_t length;
     391           0 :                     JS::AutoCheckCannotGC nogc;
     392           0 :                     const char16_t* ch = JS_GetTwoByteStringCharsAndLength(rq.cx, nogc, string, &length);
     393           0 :                     if (ch && length > 0)
     394           0 :                         funcname.assign(ch, ch + length);
     395             :                 }
     396             :             }
     397           1 :         }
     398             : 
     399           4 :         LOGERROR("Cannot serialize JS objects of type 'function': {}", utf8_from_wstring(funcname));
     400           1 :         throw PSERROR_Serialize_InvalidScriptValue();
     401           2 :     }
     402       14011 :     case JSTYPE_STRING:
     403       14011 :     {
     404       14011 :         m_Serializer.NumberU8_Unbounded("type", SCRIPT_TYPE_STRING);
     405       14011 :         JS::RootedString stringVal(rq.cx, val.toString());
     406       14011 :         ScriptString(rq, "string", stringVal);
     407       14011 :         break;
     408       14011 :     }
     409       42666 :     case JSTYPE_NUMBER:
     410       42666 :     {
     411             :         // Refuse to serialize NaN values: their representation can differ, leading to OOS
     412             :         // and in general this is indicative of an underlying bug rather than desirable behaviour.
     413       42666 :         if (val == JS::NaNValue())
     414             :         {
     415           1 :             LOGERROR("Cannot serialize NaN values.");
     416           1 :             throw PSERROR_Serialize_InvalidScriptValue();
     417             :         }
     418             : 
     419             :         // To reduce the size of the serialized data, we handle integers and doubles separately.
     420             :         // We can't check for val.isInt32 and val.isDouble directly, because integer numbers are not guaranteed
     421             :         // to be represented as integers. A number like 33 could be stored as integer on the computer of one player
     422             :         // and as double on the other player's computer. That would cause out of sync errors in multiplayer games because
     423             :         // their binary representation and thus the hash would be different.
     424       42665 :         double d;
     425       42665 :         d = val.toNumber();
     426       42665 :         std::int32_t integer;
     427             : 
     428       42665 :         if (JS_DoubleIsInt32(d, &integer))
     429             :         {
     430       38733 :             m_Serializer.NumberU8_Unbounded("type", SCRIPT_TYPE_INT);
     431       38733 :             m_Serializer.NumberI32_Unbounded("value", integer);
     432             :         }
     433             :         else
     434             :         {
     435        3932 :             m_Serializer.NumberU8_Unbounded("type", SCRIPT_TYPE_DOUBLE);
     436        3932 :             m_Serializer.NumberDouble_Unbounded("value", d);
     437             :         }
     438       42665 :         break;
     439             :     }
     440       12906 :     case JSTYPE_BOOLEAN:
     441       12906 :     {
     442       12906 :         m_Serializer.NumberU8_Unbounded("type", SCRIPT_TYPE_BOOLEAN);
     443       12906 :         bool b = val.toBoolean();
     444       12906 :         m_Serializer.NumberU8_Unbounded("value", b ? 1 : 0);
     445             :         break;
     446             :     }
     447           0 :     default:
     448           0 :     {
     449           0 :         debug_warn(L"Invalid TypeOfValue");
     450           0 :         throw PSERROR_Serialize_InvalidScriptValue();
     451             :     }
     452             :     }
     453      137172 : }
     454             : 
     455      122711 : void CBinarySerializerScriptImpl::ScriptString(const Script::Request& rq, const char* name, JS::HandleString string)
     456             : {
     457             : #if BYTE_ORDER != LITTLE_ENDIAN
     458             : #error TODO: probably need to convert JS strings to little-endian
     459             : #endif
     460             : 
     461      122711 :     size_t length;
     462      122711 :     JS::AutoCheckCannotGC nogc;
     463             :     // Serialize strings directly as UTF-16 or Latin1, to avoid expensive encoding conversions
     464      122711 :     std::uint8_t isLatin1 = JS::StringHasLatin1Chars(string);
     465      122711 :     m_Serializer.NumberU8_Unbounded("isLatin1", isLatin1);
     466      122711 :     if (isLatin1)
     467             :     {
     468      122705 :         const JS::Latin1Char* chars = JS_GetLatin1StringCharsAndLength(rq.cx, nogc, string, &length);
     469      122705 :         if (!chars)
     470           0 :             throw PSERROR_Serialize_ScriptError("JS_GetLatin1StringCharsAndLength failed");
     471      122705 :         m_Serializer.NumberU32_Unbounded("string length", static_cast<std::uint32_t>(length));
     472      122705 :         m_Serializer.RawBytes(name, static_cast<const std::uint8_t*>(chars), length);
     473             :     }
     474             :     else
     475             :     {
     476           6 :         const char16_t* chars = JS_GetTwoByteStringCharsAndLength(rq.cx, nogc, string, &length);
     477             : 
     478           6 :         if (!chars)
     479           0 :             throw PSERROR_Serialize_ScriptError("JS_GetTwoByteStringCharsAndLength failed");
     480           6 :         m_Serializer.NumberU32_Unbounded("string length", static_cast<std::uint32_t>(length));
     481           6 :         m_Serializer.RawBytes(name, reinterpret_cast<const std::uint8_t*>(chars), length*2);
     482             :     }
     483      122711 : }
     484             : 
     485           0 : void CBinarySerializerScriptImpl::Trace(JSTracer *trc, void *data)
     486             : {
     487           0 :     CBinarySerializerScriptImpl* serializer = static_cast<CBinarySerializerScriptImpl*>(data);
     488           0 :     serializer->m_ScriptBackrefTags.trace(trc);
     489           0 : }
     490             : 
     491       59513 : std::uint32_t CBinarySerializerScriptImpl::GetScriptBackrefTag(const Script::Request& rq, JS::HandleObject obj)
     492             : {
     493             :     // To support non-tree structures (e.g. "var x = []; var y = [x, x];"), we need a way
     494             :     // to indicate multiple references to one object(/array). So every time we serialize a
     495             :     // new object, we give it a new tag; when we serialize it a second time we just refer
     496             :     // to that tag.
     497             : 
     498      119026 :     ObjectTagMap::Ptr ptr = m_ScriptBackrefTags.lookup(JS::Heap<JSObject*>(obj.get()));
     499       59513 :     if (!ptr.found())
     500             :     {
     501      172476 :         if (!m_ScriptBackrefTags.put(JS::Heap<JSObject*>(obj.get()), ++m_ScriptBackrefsNext))
     502             :         {
     503           0 :             JS::RootedValue objval(rq.cx, JS::ObjectValue(*obj.get()));
     504           0 :             LOGERROR("BinarySerializer: error at insertion. Object was {}", Script::ToString(rq, &objval));
     505           0 :             return 0;
     506           0 :         }
     507             :         // Return 0 to mean "you have to serialize this object";
     508             :         return 0;
     509             :     }
     510             :     else
     511        2021 :         return ptr->value();
     512             : }

Generated by: LCOV version 1.16