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 "XMBStorage.h"
21 :
22 : #include "lib/debug.h"
23 : #include "lib/file/io/write_buffer.h"
24 : #include "lib/file/vfs/vfs.h"
25 : #include "ps/CLogger.h"
26 : #include "scriptinterface/Object.h"
27 : #include "scriptinterface/Conversions.h"
28 : #include "scriptinterface/Interface.h"
29 : #include "scriptinterface/Request.h"
30 :
31 : #include <algorithm>
32 : #include <js/Array.h>
33 : #include <js/RootingAPI.h>
34 : #include <js/Value.h>
35 : #include <jsapi.h>
36 : #include <jspubtd.h>
37 : #include <libxml/parser.h>
38 : #include <libxml/xmlmemory.h>
39 : #include <libxml/xmlstring.h>
40 : #include <string_view>
41 : #include <unordered_map>
42 : #include <utility>
43 : #include <vector>
44 :
45 : const char* XMBStorage::HeaderMagicStr = "XMB0";
46 : const char* XMBStorage::UnfinishedHeaderMagicStr = "XMBu";
47 : // Arbitrary version number - change this if we update the code and
48 : // need to invalidate old users' caches
49 : const std::uint32_t XMBStorage::XMBVersion = 4;
50 :
51 : namespace
52 : {
53 7807 : class XMBStorageWriter
54 : {
55 : public:
56 : template<typename ...Args>
57 : bool Load(WriteBuffer& writeBuffer, Args&&... args);
58 :
59 105308 : int GetElementName(const std::string& name) { return GetName(m_ElementSize, m_ElementIDs, name); }
60 12770 : int GetAttributeName(const std::string& name) { return GetName(m_AttributeSize, m_AttributeIDs, name); }
61 :
62 : protected:
63 118096 : int GetName(int& totalSize, std::unordered_map<std::string, int>& names, const std::string& name)
64 : {
65 118096 : int nameIdx = totalSize;
66 118096 : auto [iterator, inserted] = names.try_emplace(name, nameIdx);
67 118096 : if (inserted)
68 113336 : totalSize += name.size() + 5; // Add 1 for the null terminator & 4 for the size int.
69 118096 : return iterator->second;
70 : }
71 :
72 : void OutputNames(WriteBuffer& writeBuffer, const std::unordered_map<std::string, int>& names) const;
73 :
74 : template<typename ...Args>
75 : bool OutputElements(WriteBuffer&, Args...)
76 : {
77 : static_assert(sizeof...(Args) != sizeof...(Args), "OutputElements must be specialized.");
78 : return false;
79 : }
80 :
81 : int m_ElementSize = 0;
82 : int m_AttributeSize = 0;
83 : std::unordered_map<std::string, int> m_ElementIDs;
84 : std::unordered_map<std::string, int> m_AttributeIDs;
85 : };
86 :
87 : // Output text, prefixed by length in bytes (including null-terminator)
88 105320 : void WriteStringAndLineNumber(WriteBuffer& writeBuffer, const std::string& text, int lineNumber)
89 : {
90 105320 : if (text.empty())
91 : {
92 : // No text; don't write much
93 65970 : writeBuffer.Append("\0\0\0\0", 4);
94 : }
95 : else
96 : {
97 : // Write length and line number and null-terminated text
98 39350 : std::uint32_t nodeLen = static_cast<std::uint32_t>(4 + text.length() + 1);
99 39350 : writeBuffer.Append(&nodeLen, 4);
100 39350 : writeBuffer.Append(&lineNumber, 4);
101 39350 : writeBuffer.Append((void*)text.c_str(), nodeLen-4);
102 : }
103 105320 : }
104 :
105 : template<typename ...Args>
106 7807 : bool XMBStorageWriter::Load(WriteBuffer& writeBuffer, Args&&... args)
107 : {
108 : // Header
109 7807 : writeBuffer.Append(XMBStorage::UnfinishedHeaderMagicStr, 4);
110 : // Version
111 7807 : writeBuffer.Append(&XMBStorage::XMBVersion, 4);
112 :
113 : // Filled in below.
114 7807 : size_t elementPtr = writeBuffer.Size();
115 7807 : writeBuffer.Append("????????", 8);
116 : // Likewise with attributes.
117 7807 : size_t attributePtr = writeBuffer.Size();
118 7807 : writeBuffer.Append("????????", 8);
119 :
120 7807 : if (!OutputElements<Args&&...>(writeBuffer, std::forward<Args>(args)...))
121 : return false;
122 :
123 7807 : std::uint32_t data = writeBuffer.Size();
124 7807 : writeBuffer.Overwrite(&data, 4, elementPtr);
125 7807 : data = m_ElementIDs.size();
126 7807 : writeBuffer.Overwrite(&data, 4, elementPtr + 4);
127 7807 : OutputNames(writeBuffer, m_ElementIDs);
128 :
129 7807 : data = writeBuffer.Size();
130 7807 : writeBuffer.Overwrite(&data, 4, attributePtr);
131 7807 : data = m_AttributeIDs.size();
132 7807 : writeBuffer.Overwrite(&data, 4, attributePtr + 4);
133 7807 : OutputNames(writeBuffer, m_AttributeIDs);
134 :
135 : // File is now valid, so insert correct magic string.
136 7807 : writeBuffer.Overwrite(XMBStorage::HeaderMagicStr, 4, 0);
137 :
138 : return true;
139 : }
140 :
141 15614 : void XMBStorageWriter::OutputNames(WriteBuffer& writeBuffer, const std::unordered_map<std::string, int>& names) const
142 : {
143 15614 : std::vector<std::pair<std::string, int>> orderedElements;
144 128950 : for (const std::pair<const std::string, int>& n : names)
145 113336 : orderedElements.emplace_back(n);
146 315696 : std::sort(orderedElements.begin(), orderedElements.end(), [](const auto& a, const auto&b) { return a.second < b.second; });
147 128950 : for (const std::pair<std::string, int>& n : orderedElements)
148 : {
149 113336 : std::uint32_t textLen = static_cast<std::uint32_t>(n.first.length()) + 1;
150 113336 : writeBuffer.Append(&textLen, 4);
151 113336 : writeBuffer.Append((void*)n.first.c_str(), textLen);
152 : }
153 15614 : }
154 :
155 : class JSNodeData
156 : {
157 : public:
158 4 : JSNodeData(const Script::Interface& s) : scriptInterface(s), rq(s) {}
159 :
160 : bool Setup(XMBStorageWriter& xmb, JS::HandleValue value);
161 : bool Output(WriteBuffer& writeBuffer, JS::HandleValue value) const;
162 :
163 : std::vector<std::pair<std::uint32_t, std::string>> m_Attributes;
164 : std::vector<std::pair<std::uint32_t, JS::Heap<JS::Value>>> m_Children;
165 :
166 : const Script::Interface& scriptInterface;
167 : const Script::Request rq;
168 : };
169 :
170 : template<>
171 16 : bool XMBStorageWriter::OutputElements<JSNodeData&, const std::uint32_t&, JS::HandleValue&&>(
172 : WriteBuffer& writeBuffer, JSNodeData& data, const std::uint32_t& nodeName, JS::HandleValue&& value)
173 : {
174 : // Set up variables.
175 16 : if (!data.Setup(*this, value))
176 : return false;
177 :
178 16 : size_t posLength = writeBuffer.Size();
179 : // Filled in later with the length of the element
180 16 : writeBuffer.Append("????", 4);
181 :
182 16 : writeBuffer.Append(&nodeName, 4);
183 :
184 16 : std::uint32_t attrCount = static_cast<std::uint32_t>(data.m_Attributes.size());
185 16 : writeBuffer.Append(&attrCount, 4);
186 :
187 16 : std::uint32_t childCount = data.m_Children.size();
188 16 : writeBuffer.Append(&childCount, 4);
189 :
190 : // Filled in later with the offset to the list of child elements
191 16 : size_t posChildrenOffset = writeBuffer.Size();
192 16 : writeBuffer.Append("????", 4);
193 :
194 16 : data.Output(writeBuffer, value);
195 :
196 : // Output attributes
197 18 : for (const std::pair<const std::uint32_t, std::string> attr : data.m_Attributes)
198 : {
199 2 : writeBuffer.Append(&attr.first, 4);
200 2 : std::uint32_t attrLen = static_cast<std::uint32_t>(attr.second.size()) + 1;
201 2 : writeBuffer.Append(&attrLen, 4);
202 2 : writeBuffer.Append((void*)attr.second.c_str(), attrLen);
203 2 : }
204 :
205 : // Go back and fill in the child-element offset
206 16 : std::uint32_t childrenOffset = static_cast<std::uint32_t>(writeBuffer.Size() - (posChildrenOffset+4));
207 16 : writeBuffer.Overwrite(&childrenOffset, 4, posChildrenOffset);
208 :
209 : // Output all child elements, making a copy since data will be overwritten.
210 16 : std::vector<std::pair<std::uint32_t, JS::Heap<JS::Value>>> children = data.m_Children;
211 28 : for (const std::pair<std::uint32_t, JS::Heap<JS::Value>>& child : children)
212 : {
213 12 : JS::RootedValue val(data.rq.cx, child.second);
214 12 : if (!OutputElements<JSNodeData&, const std::uint32_t&, JS::HandleValue&&>(writeBuffer, data, child.first, val))
215 0 : return false;
216 12 : }
217 :
218 : // Go back and fill in the length
219 16 : std::uint32_t length = static_cast<std::uint32_t>(writeBuffer.Size() - posLength);
220 16 : writeBuffer.Overwrite(&length, 4, posLength);
221 :
222 : return true;
223 16 : }
224 :
225 16 : bool JSNodeData::Setup(XMBStorageWriter& xmb, JS::HandleValue value)
226 : {
227 16 : m_Attributes.clear();
228 16 : m_Children.clear();
229 16 : JSType valType = JS_TypeOfValue(rq.cx, value);
230 16 : if (valType != JSTYPE_OBJECT)
231 : return true;
232 :
233 9 : std::vector<std::string> props;
234 9 : if (!Script::EnumeratePropertyNames(rq, value, true, props))
235 : {
236 0 : LOGERROR("Failed to enumerate component properties.");
237 0 : return false;
238 : }
239 :
240 26 : for (const std::string& prop : props)
241 : {
242 : // Special 'value' key.
243 17 : if (prop == "_string")
244 5 : continue;
245 :
246 12 : bool attrib = !prop.empty() && prop.front() == '@';
247 :
248 12 : std::string_view name = prop;
249 12 : if (!attrib && !prop.empty() && prop.back() == '@')
250 : {
251 4 : const size_t idx = std::string_view{prop}.substr(0, prop.size() - 1)
252 4 : .find_last_of('@');
253 4 : if (idx == std::string::npos)
254 : {
255 0 : LOGERROR("Object key name cannot end with an '@' unless it is an index specifier.");
256 0 : return false;
257 : }
258 4 : name = std::string_view(prop.c_str(), idx);
259 : }
260 8 : else if (attrib)
261 2 : name = std::string_view(prop.c_str()+1, prop.length()-1);
262 :
263 12 : JS::RootedValue child(rq.cx);
264 12 : if (!Script::GetProperty(rq, value, prop.c_str(), &child))
265 : return false;
266 :
267 12 : if (attrib)
268 : {
269 2 : std::string attrVal;
270 2 : if (!Script::FromJSVal(rq, child, attrVal))
271 : {
272 0 : LOGERROR("Attributes must be convertible to string");
273 0 : return false;
274 : }
275 4 : m_Attributes.emplace_back(xmb.GetAttributeName(std::string(name)), attrVal);
276 2 : continue;
277 2 : }
278 :
279 10 : bool isArray = false;
280 10 : if (!JS::IsArrayObject(rq.cx, child, &isArray))
281 : return false;
282 10 : if (!isArray)
283 : {
284 16 : m_Children.emplace_back(xmb.GetElementName(std::string(name)), child);
285 8 : continue;
286 : }
287 :
288 : // Parse each array object as a child.
289 2 : JS::RootedObject obj(rq.cx);
290 2 : JS_ValueToObject(rq.cx, child, &obj);
291 2 : std::uint32_t length;
292 2 : JS::GetArrayLength(rq.cx, obj, &length);
293 6 : for (size_t i = 0; i < length; ++i)
294 : {
295 4 : JS::RootedValue arrayChild(rq.cx);
296 4 : Script::GetPropertyInt(rq, child, i, &arrayChild);
297 12 : m_Children.emplace_back(xmb.GetElementName(std::string(name)), arrayChild);
298 4 : }
299 17 : }
300 : return true;
301 9 : }
302 :
303 16 : bool JSNodeData::Output(WriteBuffer& writeBuffer, JS::HandleValue value) const
304 : {
305 16 : switch (JS_TypeOfValue(rq.cx, value))
306 : {
307 0 : case JSTYPE_UNDEFINED:
308 0 : {
309 0 : writeBuffer.Append("\0\0\0\0", 4);
310 0 : break;
311 : }
312 9 : case JSTYPE_OBJECT:
313 9 : {
314 9 : if (!Script::HasProperty(rq, value, "_string"))
315 : {
316 4 : writeBuffer.Append("\0\0\0\0", 4);
317 9 : break;
318 : }
319 5 : JS::RootedValue actualValue(rq.cx);
320 5 : if (!Script::GetProperty(rq, value, "_string", &actualValue))
321 : return false;
322 5 : std::string strVal;
323 5 : if (!Script::FromJSVal(rq, actualValue, strVal))
324 : {
325 0 : LOGERROR("'_string' value must be convertible to string");
326 0 : return false;
327 : }
328 5 : WriteStringAndLineNumber(writeBuffer, strVal, 0);
329 5 : break;
330 9 : }
331 7 : case JSTYPE_STRING:
332 7 : case JSTYPE_NUMBER:
333 7 : {
334 7 : std::string strVal;
335 7 : if (!Script::FromJSVal(rq, value, strVal))
336 0 : return false;
337 :
338 7 : WriteStringAndLineNumber(writeBuffer, strVal, 0);
339 7 : break;
340 7 : }
341 0 : default:
342 0 : {
343 0 : LOGERROR("Unsupported JS construct when parsing ParamNode");
344 0 : return false;
345 : }
346 : }
347 : return true;
348 : }
349 :
350 : template<>
351 105308 : bool XMBStorageWriter::OutputElements<xmlNodePtr&&>(WriteBuffer& writeBuffer, xmlNodePtr&& node)
352 : {
353 : // Filled in later with the length of the element
354 105308 : size_t posLength = writeBuffer.Size();
355 105308 : writeBuffer.Append("????", 4);
356 :
357 210616 : std::uint32_t name = GetElementName((const char*)node->name);
358 105308 : writeBuffer.Append(&name, 4);
359 :
360 105308 : std::uint32_t attrCount = 0;
361 118078 : for (xmlAttrPtr attr = node->properties; attr; attr = attr->next)
362 12770 : ++attrCount;
363 105308 : writeBuffer.Append(&attrCount, 4);
364 :
365 105308 : std::uint32_t childCount = 0;
366 283716 : for (xmlNodePtr child = node->children; child; child = child->next)
367 178408 : if (child->type == XML_ELEMENT_NODE)
368 97505 : ++childCount;
369 105308 : writeBuffer.Append(&childCount, 4);
370 :
371 : // Filled in later with the offset to the list of child elements
372 105308 : size_t posChildrenOffset = writeBuffer.Size();
373 105308 : writeBuffer.Append("????", 4);
374 :
375 :
376 : // Trim excess whitespace in the entity's text, while counting
377 : // the number of newlines trimmed (so that JS error reporting
378 : // can give the correct line number within the script)
379 :
380 105308 : std::string whitespace = " \t\r\n";
381 105308 : std::string text;
382 283716 : for (xmlNodePtr child = node->children; child; child = child->next)
383 : {
384 178408 : if (child->type == XML_TEXT_NODE)
385 : {
386 80801 : xmlChar* content = xmlNodeGetContent(child);
387 161602 : text += std::string((const char*)content);
388 80801 : xmlFree(content);
389 : }
390 : }
391 :
392 105308 : std::uint32_t linenum = xmlGetLineNo(node);
393 :
394 : // Find the start of the non-whitespace section
395 105308 : size_t first = text.find_first_not_of(whitespace);
396 :
397 105308 : if (first == text.npos)
398 : // Entirely whitespace - easy to handle
399 65970 : text = "";
400 :
401 : else
402 : {
403 : // Count the number of \n being cut off,
404 : // and add them to the line number
405 78676 : std::string trimmed (text.begin(), text.begin()+first);
406 39338 : linenum += std::count(trimmed.begin(), trimmed.end(), '\n');
407 :
408 : // Find the end of the non-whitespace section,
409 : // and trim off everything else
410 39338 : size_t last = text.find_last_not_of(whitespace);
411 61990 : text = text.substr(first, 1+last-first);
412 39338 : }
413 :
414 :
415 : // Output text, prefixed by length in bytes
416 105308 : WriteStringAndLineNumber(writeBuffer, text, linenum);
417 :
418 : // Output attributes
419 118078 : for (xmlAttrPtr attr = node->properties; attr; attr = attr->next)
420 : {
421 25540 : std::uint32_t attrName = GetAttributeName((const char*)attr->name);
422 12770 : writeBuffer.Append(&attrName, 4);
423 :
424 12770 : xmlChar* value = xmlNodeGetContent(attr->children);
425 12770 : std::uint32_t attrLen = static_cast<std::uint32_t>(xmlStrlen(value) + 1);
426 12770 : writeBuffer.Append(&attrLen, 4);
427 12770 : writeBuffer.Append((void*)value, attrLen);
428 12770 : xmlFree(value);
429 : }
430 :
431 : // Go back and fill in the child-element offset
432 105308 : std::uint32_t childrenOffset =
433 105308 : static_cast<std::uint32_t>(writeBuffer.Size() - (posChildrenOffset + 4));
434 105308 : writeBuffer.Overwrite(&childrenOffset, 4, posChildrenOffset);
435 :
436 : // Output all child elements
437 283716 : for (xmlNodePtr child = node->children; child; child = child->next)
438 178408 : if (child->type == XML_ELEMENT_NODE)
439 97505 : OutputElements<xmlNodePtr&&>(writeBuffer, std::move(child));
440 :
441 : // Go back and fill in the length
442 105308 : std::uint32_t length = static_cast<std::uint32_t>(writeBuffer.Size() - posLength);
443 105308 : writeBuffer.Overwrite(&length, 4, posLength);
444 :
445 105308 : return true;
446 105308 : }
447 : } // anonymous namespace
448 :
449 6829 : bool XMBStorage::ReadFromFile(const PIVFS& vfs, const VfsPath& filename)
450 : {
451 6829 : if(vfs->LoadFile(filename, m_Buffer, m_Size) < 0)
452 : return false;
453 : // if the game crashes during loading, (e.g. due to driver bugs),
454 : // it sometimes leaves empty XMB files in the cache.
455 : // reporting failure will cause our caller to re-generate the XMB.
456 6829 : if (m_Size == 0)
457 : return false;
458 6829 : ENSURE(m_Size >= 4); // make sure it's at least got the initial header
459 : return true;
460 : }
461 :
462 7803 : bool XMBStorage::LoadXMLDoc(const xmlDocPtr doc)
463 : {
464 7803 : WriteBuffer writeBuffer;
465 :
466 7803 : XMBStorageWriter writer;
467 7803 : if (!writer.Load(writeBuffer, std::move(xmlDocGetRootElement(doc))))
468 : return false;
469 :
470 7803 : m_Buffer = writeBuffer.Data(); // add a reference
471 7803 : m_Size = writeBuffer.Size();
472 7803 : return true;
473 15606 : }
474 :
475 4 : bool XMBStorage::LoadJSValue(const Script::Interface& scriptInterface, JS::HandleValue value, const std::string& rootName)
476 : {
477 4 : WriteBuffer writeBuffer;
478 :
479 4 : XMBStorageWriter writer;
480 4 : const std::uint32_t name = writer.GetElementName(rootName);
481 4 : JSNodeData data(scriptInterface);
482 4 : if (!writer.Load(writeBuffer, data, name, std::move(value)))
483 : return false;
484 :
485 4 : m_Buffer = writeBuffer.Data(); // add a reference
486 4 : m_Size = writeBuffer.Size();
487 4 : return true;
488 12 : }
|