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 : #ifndef INCLUDED_ISERIALIZER
19 : #define INCLUDED_ISERIALIZER
20 :
21 : #include "maths/Fixed.h"
22 : #include "ps/Errors.h"
23 :
24 : #include <cstddef>
25 : #include <cstdint>
26 : #include <iosfwd>
27 : #include <js/TypeDecls.h>
28 : #include <string>
29 :
30 : ERROR_GROUP(Serialize);
31 : ERROR_TYPE(Serialize, OutOfBounds);
32 : ERROR_TYPE(Serialize, InvalidCharInString);
33 : ERROR_TYPE(Serialize, ScriptError);
34 : ERROR_TYPE(Serialize, InvalidScriptValue);
35 :
36 : /**
37 : * @page serialization Component serialization
38 : *
39 : * This page gives a high-level description of ISerializer and IDeserializer.
40 : *
41 : * @section design Rough design notes
42 : *
43 : * We want to handle the following serialization-related features:
44 : * - Out-of-sync detection: Based on hash of simulation state.
45 : * Must be fast.
46 : * - Debugging OOS failures: Human-readable output of simulation state,
47 : * that can be diffed against other states.
48 : * - Saving and loading games to disk: Machine-readable output of state.
49 : * Should remain usable after patches to the game.
50 : * - Joining in-progress network games: Machine-readable output of state.
51 : * Must be compact (minimise network traffic).
52 : * Must be secure (no remote code execution from invalid network data).
53 : *
54 : * All cases must be portable across OSes, CPU architectures (endianness, bitness),
55 : * compilers, compiler settings, etc.
56 : *
57 : * This is designed for serializing components, which we consider to have three main kinds of state:
58 : * - Basic deterministic state: Stuff that's critical to the simulation state,
59 : * and is identical between all players in a network game.
60 : * Always needs to be saved and loaded and hashed and dumped etc.
61 : * - Derived deterministic state: Stuff that can be identically recomputed from
62 : * the basic deterministic state,
63 : * but typically is stored in memory as an optimisation (e.g. caches).
64 : * Shouldn't be saved to disk/network (to save space), and should be recomputed on loading.
65 : * Should be included in hashes and debug dumps, to detect errors sooner.
66 : * - Non-deterministic state: Stuff that's not part of the simulation state,
67 : * and may vary between players in a network game,
68 : * but is kept for graphics or for optimisations etc.
69 : * Shouldn't be saved or hashed or dumped or anything.
70 : *
71 : * (TODO: Versioning (for saved games to survive patches) is not yet implemented.)
72 : *
73 : * We have separate serialization and deserialization APIs (thus requiring components
74 : * to implement separate serialize/deserialize functions), rather than a single unified
75 : * API (that can either serialize or deserialize depending on the particular instance).
76 : * This means more work for simple components, but it simplifies complex components (those
77 : * which have versioning, or recompute derived state) since they don't need lots of
78 : * "if (IsDeserializing()) ..." checks.
79 : *
80 : * Callers must use the same sequence of IDeserializer calls as they used
81 : * ISerializer calls. For efficiency, serializations typically don't encode
82 : * the data type, and so mismatches will make them read bogus values and
83 : * hopefully hit an out-of-bounds exception.
84 : *
85 : * The ISerializable interface used by some code in the engine is irrelevant here. Serialization
86 : * of interesting classes is implemented in this module, not in the classes themselves, so that
87 : * the serialization system has greater control (e.g. the human-readable debug output can handle
88 : * classes very differently to binary output).
89 : *
90 : * To encourage portability, only fixed-size types are exposed in the API (e.g. int32_t,
91 : * not int). Components should use fixed-size types internally, to ensure deterministic
92 : * simulation across 32-bit and 64-bit architectures.
93 : *
94 : * TODO: At least some compound types like lists ought to be supported somehow.
95 : *
96 : * To encourage security, the API accepts bounds on numbers and string lengths etc,
97 : * and will fail if the data exceeds the bounds. Callers should provide sensible bounds
98 : * (they must never be exceeded, but the caller should be able to safely cope with any values
99 : * within the bounds and not crash or run out of memory etc).
100 : *
101 : * For the OOS debugging output, the API requires field names for all values. These are
102 : * only used for human-readable output, so they should be readable but don't have to
103 : * be unique or follow any particular pattern.
104 : *
105 : * The APIs throw exceptions whenever something fails (all errors are fatal).
106 : * Component (de)serialization functions must be exception-safe.
107 : */
108 :
109 : /*
110 : * Implementation details:
111 : *
112 : * The current implementation has lots of nested virtual function calls,
113 : * to maximise flexibility. If this turns out to be too inefficient,
114 : * it'll need to be rewritten somehow with less virtuals (probably using
115 : * templates instead). (This is a more generic design than will be needed
116 : * in practice.)
117 : *
118 : * The public API functions do bounds checking, then pass the data
119 : * to the Put* methods, which subclasses must handle.
120 : */
121 :
122 : /**
123 : * Serialization interface; see @ref serialization "serialization overview".
124 : */
125 177 : class ISerializer
126 : {
127 : public:
128 : virtual ~ISerializer();
129 :
130 : /**
131 : * Serialize a number, which must be lower <= value <= upper.
132 : * The same bounds must be used when deserializing the number.
133 : * This should be used in preference to the Unbounded functions, to
134 : * detect erroneous or malicious values that might cause problems when used.
135 : * @throw PSERROR_Serialize_OutOfBounds if value is out of bounds
136 : * @throw PSERROR_Serialize for any other errors
137 : * @param name informative name for debug output
138 : * @param value value to serialize
139 : * @param lower inclusive lower bound
140 : * @param upper inclusive upper bound
141 : */
142 : void NumberU8(const char* name, uint8_t value, uint8_t lower, uint8_t upper);
143 : void NumberI8(const char* name, int8_t value, int8_t lower, int8_t upper);
144 : void NumberU16(const char* name, uint16_t value, uint16_t lower, uint16_t upper); ///< @copydoc NumberU8
145 : void NumberI16(const char* name, int16_t value, int16_t lower, int16_t upper); ///< @copydoc NumberU8
146 : void NumberU32(const char* name, uint32_t value, uint32_t lower, uint32_t upper); ///< @copydoc NumberU8
147 : void NumberI32(const char* name, int32_t value, int32_t lower, int32_t upper); ///< @copydoc NumberU8
148 :
149 : /**
150 : * Serialize a number.
151 : * @throw PSERROR_Serialize for any errors
152 : * @param name informative name for debug output
153 : * @param value value to serialize
154 : */
155 278874 : void NumberU8_Unbounded(const char* name, uint8_t value)
156 : {
157 : // (These functions are defined inline for efficiency)
158 278874 : PutNumber(name, value);
159 80531 : }
160 :
161 1034 : void NumberI8_Unbounded(const char* name, int8_t value) ///@copydoc NumberU8_Unbounded()
162 : {
163 1034 : PutNumber(name, value);
164 : }
165 :
166 2668 : void NumberU16_Unbounded(const char* name, uint16_t value) ///@copydoc NumberU8_Unbounded()
167 : {
168 2631 : PutNumber(name, value);
169 0 : }
170 :
171 2 : void NumberI16_Unbounded(const char* name, int16_t value) ///@copydoc NumberU8_Unbounded()
172 : {
173 2 : PutNumber(name, value);
174 : }
175 :
176 287782 : void NumberU32_Unbounded(const char* name, uint32_t value) ///@copydoc NumberU8_Unbounded()
177 : {
178 276754 : PutNumber(name, value);
179 99914 : }
180 :
181 41413 : void NumberI32_Unbounded(const char* name, int32_t value) ///@copydoc NumberU8_Unbounded()
182 : {
183 41410 : PutNumber(name, value);
184 39433 : }
185 :
186 10 : void NumberFloat_Unbounded(const char* name, float value) ///@copydoc NumberU8_Unbounded()
187 : {
188 10 : PutNumber(name, value);
189 8 : }
190 :
191 3948 : void NumberDouble_Unbounded(const char* name, double value) ///@copydoc NumberU8_Unbounded()
192 : {
193 3948 : PutNumber(name, value);
194 3946 : }
195 :
196 44499 : void NumberFixed_Unbounded(const char* name, fixed value) ///@copydoc NumberU8_Unbounded()
197 : {
198 14265 : PutNumber(name, value);
199 1 : }
200 :
201 : /**
202 : * Serialize a boolean.
203 : */
204 13766 : void Bool(const char* name, bool value)
205 : {
206 7908 : PutBool(name, value);
207 4 : }
208 :
209 : /**
210 : * Serialize an ASCII string.
211 : * Characters must be in the range U+0001 .. U+00FF (inclusive).
212 : * The string must be between minlength .. maxlength (inclusive) characters.
213 : */
214 : void StringASCII(const char* name, const std::string& value, uint32_t minlength, uint32_t maxlength);
215 :
216 : /**
217 : * Serialize a Unicode string.
218 : * Characters must be in the range U+0000..U+D7FF, U+E000..U+FDCF, U+FDF0..U+FFFD (inclusive).
219 : * The string must be between minlength .. maxlength (inclusive) characters.
220 : */
221 : void String(const char* name, const std::wstring& value, uint32_t minlength, uint32_t maxlength);
222 :
223 : /**
224 : * Serialize a JS::MutableHandleValue.
225 : * The value must not contain any unserializable values (like functions).
226 : * NOTE: We have to use a mutable handle because JS_Stringify requires that for unknown reasons.
227 : */
228 : void ScriptVal(const char* name, JS::MutableHandleValue value);
229 :
230 : /**
231 : * Serialize a stream of bytes.
232 : * It is the caller's responsibility to deal with portability (padding, endianness, etc);
233 : * the typed serialize methods should usually be used instead of this.
234 : */
235 : void RawBytes(const char* name, const std::uint8_t* data, size_t len);
236 :
237 : /**
238 : * Returns true if the serializer is being used in debug mode.
239 : * Components should serialize non-critical data (e.g. data that is unchanged
240 : * from the template) only if this is true. (It must still only be used
241 : * for synchronised, deterministic data.)
242 : */
243 : virtual bool IsDebug() const;
244 :
245 : /**
246 : * Returns a stream which can be used to serialize data directly.
247 : * (This is particularly useful for chaining multiple serializers
248 : * together.)
249 : */
250 : virtual std::ostream& GetStream() = 0;
251 :
252 : protected:
253 : virtual void PutNumber(const char* name, uint8_t value) = 0;
254 : virtual void PutNumber(const char* name, int8_t value) = 0;
255 : virtual void PutNumber(const char* name, uint16_t value) = 0;
256 : virtual void PutNumber(const char* name, int16_t value) = 0;
257 : virtual void PutNumber(const char* name, uint32_t value) = 0;
258 : virtual void PutNumber(const char* name, int32_t value) = 0;
259 : virtual void PutNumber(const char* name, float value) = 0;
260 : virtual void PutNumber(const char* name, double value) = 0;
261 : virtual void PutNumber(const char* name, fixed value) = 0;
262 : virtual void PutBool(const char* name, bool value) = 0;
263 : virtual void PutString(const char* name, const std::string& value) = 0;
264 : // We have to use a mutable handle because JS_Stringify requires that for unknown reasons.
265 : virtual void PutScriptVal(const char* name, JS::MutableHandleValue value) = 0;
266 : virtual void PutRaw(const char* name, const std::uint8_t* data, size_t len) = 0;
267 : };
268 :
269 : #endif // INCLUDED_ISERIALIZER
|