LCOV - code coverage report
Current view: top level - source/ps/XML - Xeromyces.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 84 104 80.8 %
Date: 2026-12-03 01:19:39 Functions: 8 10 80.0 %

          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 "Xeromyces.h"
      21             : 
      22             : #include "lib/debug.h"
      23             : #include "lib/file/vfs/vfs.h"
      24             : #include "lib/path.h"
      25             : #include "lib/status.h"
      26             : #include "maths/MD5.h"
      27             : #include "ps/CLogger.h"
      28             : #include "ps/CStr.h"
      29             : #include "ps/CacheLoader.h"
      30             : #include "ps/Filesystem.h"
      31             : #include "ps/XML/RelaxNG.h"
      32             : 
      33             : #include <cstring>
      34             : #include <libxml/parser.h>
      35             : #include <libxml/xmlerror.h>
      36             : #include <libxml/xmlversion.h>
      37             : #include <map>
      38             : #include <mutex>
      39             : #include <type_traits>
      40             : #include <utility>
      41             : 
      42             : static std::mutex g_ValidatorCacheLock;
      43             : static std::map<const std::string, RelaxNGValidator> g_ValidatorCache;
      44             : 
      45           5 : static void errorHandler(void* /*userData*/,
      46             :     std::conditional_t<LIBXML_VERSION >= 21200, const xmlError, xmlError>* error)
      47             : {
      48             :     // Strip a trailing newline
      49           5 :     std::string message = error->message;
      50           5 :     if (message.length() > 0 && message[message.length()-1] == '\n')
      51           5 :         message.erase(message.length()-1);
      52             : 
      53           5 :     if (error->file)
      54             :     {
      55          12 :         LOGERROR("CXeromyces: Parse {}: {}:{}: {}",
      56             :             error->level == XML_ERR_WARNING ? "warning" : "error", error->file, error->line,
      57             :             message);
      58             :     }
      59             :     else
      60             :     {
      61           8 :         LOGERROR("CXeromyces: Parse {}: {} {}",
      62             :             error->level == XML_ERR_WARNING ? "warning" : "error", error->line, message);
      63             :     }
      64             :     // TODO: The (non-fatal) warnings and errors don't get stored in the XMB,
      65             :     // so the caching is less transparent than it should be
      66           5 : }
      67             : 
      68         114 : CXeromycesEngine::CXeromycesEngine()
      69             : {
      70         114 :     xmlInitParser();
      71         114 :     xmlSetStructuredErrorFunc(NULL, &errorHandler);
      72         114 :     std::lock_guard<std::mutex> lock(g_ValidatorCacheLock);
      73         114 :     g_ValidatorCache.insert(std::make_pair(std::string(), RelaxNGValidator()));
      74         114 : }
      75             : 
      76         114 : CXeromycesEngine::~CXeromycesEngine()
      77             : {
      78         114 :     ClearSchemaCache();
      79         114 :     std::lock_guard<std::mutex> lock(g_ValidatorCacheLock);
      80         114 :     g_ValidatorCache.clear();
      81         114 :     xmlSetStructuredErrorFunc(NULL, NULL);
      82         114 :     xmlCleanupParser();
      83         114 : }
      84             : 
      85          46 : bool CXeromycesEngine::AddValidator(const PIVFS& vfs, const std::string& name, const VfsPath& grammarPath)
      86             : {
      87          46 :     RelaxNGValidator validator;
      88          46 :     if (!validator.LoadGrammarFile(vfs, grammarPath))
      89             :     {
      90          33 :         LOGERROR("CXeromyces: failed adding validator for '{}'", grammarPath.string8());
      91          11 :         return false;
      92             :     }
      93          35 :     {
      94          35 :         std::lock_guard<std::mutex> lock(g_ValidatorCacheLock);
      95          35 :         std::map<const std::string, RelaxNGValidator>::iterator it = g_ValidatorCache.find(name);
      96          35 :         if (it != g_ValidatorCache.end())
      97           4 :             g_ValidatorCache.erase(it);
      98          35 :         g_ValidatorCache.insert(std::make_pair(name, validator));
      99           0 :     }
     100          35 :     return true;
     101          46 : }
     102             : 
     103           0 : bool CXeromycesEngine::ValidateEncoded(const std::string& name, const std::string& filename, const std::string& document)
     104             : {
     105           0 :     std::lock_guard<std::mutex> lock(g_ValidatorCacheLock);
     106           0 :     return GetValidator(name).ValidateEncoded(filename, document);
     107           0 : }
     108             : 
     109             : /**
     110             :  * NOTE: Callers MUST acquire the g_ValidatorCacheLock before calling this.
     111             :  */
     112       16795 : RelaxNGValidator& CXeromycesEngine::GetValidator(const std::string& name)
     113             : {
     114       16795 :     if (g_ValidatorCache.find(name) == g_ValidatorCache.end())
     115          10 :         return g_ValidatorCache.find("")->second;
     116       16785 :     return g_ValidatorCache.find(name)->second;
     117             : }
     118             : 
     119        8998 : PSRETURN CXeromyces::Load(const PIVFS& vfs, const VfsPath& filename, const std::string& validatorName /* = "" */)
     120             : {
     121       26994 :     CCacheLoader cacheLoader(vfs, L".xmb");
     122             : 
     123        8998 :     MD5 validatorGrammarHash;
     124        8998 :     {
     125        8998 :         std::lock_guard<std::mutex> lock(g_ValidatorCacheLock);
     126        8998 :         validatorGrammarHash = g_Xeromyces.GetValidator(validatorName).GetGrammarHash();
     127           0 :     }
     128        8998 :     VfsPath xmbPath;
     129        8998 :     Status ret = cacheLoader.TryLoadingCached(filename, validatorGrammarHash, XMBStorage::XMBVersion, xmbPath);
     130             : 
     131        8998 :     if (ret == INFO::OK)
     132             :     {
     133             :         // Found a cached XMB - load it
     134        6829 :         if (m_Data.ReadFromFile(vfs, xmbPath) && Initialise(m_Data))
     135             :             return PSRETURN_OK;
     136             :         // If this fails then we'll continue and (re)create the loose cache -
     137             :         // this failure legitimately happens due to partially-written XMB files or XMB version upgrades.
     138             :         // NB: at this point xmbPath may point to an archived file, we want to write a loose cached version.
     139           0 :         xmbPath = cacheLoader.LooseCachePath(filename, validatorGrammarHash, XMBStorage::XMBVersion);
     140             :     }
     141        2169 :     else if (ret == INFO::SKIPPED)
     142             :     {
     143             :         // No cached version was found - we'll need to create it
     144             :     }
     145             :     else
     146             :     {
     147         140 :         ENSURE(ret < 0);
     148             : 
     149             :         // No source file or archive cache was found, so we can't load the
     150             :         // XML file at all
     151         420 :         LOGERROR("CCacheLoader failed to find archived or source file for: \"{}\"",
     152             :             filename.string8());
     153         140 :         return PSRETURN_Xeromyces_XMLOpenFailed;
     154             :     }
     155             : 
     156             :     // XMB isn't up to date with the XML, so rebuild it
     157        2029 :     return ConvertFile(vfs, filename, xmbPath, validatorName);
     158        8998 : }
     159             : 
     160           0 : bool CXeromyces::GenerateCachedXMB(const PIVFS& vfs, const VfsPath& sourcePath, VfsPath& archiveCachePath, const std::string& validatorName /* = "" */)
     161             : {
     162           0 :     CCacheLoader cacheLoader(vfs, L".xmb");
     163             : 
     164           0 :     archiveCachePath = cacheLoader.ArchiveCachePath(sourcePath);
     165             : 
     166           0 :     return (ConvertFile(vfs, sourcePath, VfsPath("cache") / archiveCachePath, validatorName) == PSRETURN_OK);
     167           0 : }
     168             : 
     169        2029 : PSRETURN CXeromyces::ConvertFile(const PIVFS& vfs, const VfsPath& filename, const VfsPath& xmbPath, const std::string& validatorName)
     170             : {
     171        2029 :     CVFSFile input;
     172        2029 :     if (input.Load(vfs, filename))
     173             :     {
     174           0 :         LOGERROR("CXeromyces: Failed to open XML file {}", filename.string8());
     175           0 :         return PSRETURN_Xeromyces_XMLOpenFailed;
     176             :     }
     177             : 
     178        6087 :     xmlDocPtr doc = xmlReadMemory((const char*)input.GetBuffer(), input.GetBufferSize(), CStrW(filename.string()).ToUTF8().c_str(), NULL,
     179             :         XML_PARSE_NONET|XML_PARSE_NOCDATA);
     180        2029 :     if (!doc)
     181             :     {
     182           3 :         LOGERROR("CXeromyces: Failed to parse XML file {}", filename.string8());
     183           1 :         return PSRETURN_Xeromyces_XMLParseError;
     184             :     }
     185             : 
     186        2028 :     {
     187        2028 :         std::lock_guard<std::mutex> lock(g_ValidatorCacheLock);
     188        2028 :         RelaxNGValidator& validator = g_Xeromyces.GetValidator(validatorName);
     189        2028 :         if (validator.CanValidate() && !validator.ValidateEncoded(doc))
     190             :         {
     191           0 :             LOGERROR("CXeromyces: failed to validate XML file {}", filename.string8());
     192           0 :             return PSRETURN_Xeromyces_XMLValidationFailed;
     193             :         }
     194           0 :     }
     195             : 
     196        2028 :     m_Data.LoadXMLDoc(doc);
     197        2028 :     xmlFreeDoc(doc);
     198             : 
     199             :     // Save the file to disk, so it can be loaded quickly next time.
     200             :     // Don't save if invalid, because we want the syntax error every program start.
     201        2028 :     vfs->CreateFile(xmbPath, {m_Data.m_Buffer.get(), m_Data.m_Size});
     202             : 
     203             :     // Set up the XMBData
     204        2028 :     const bool ok = Initialise(m_Data);
     205        2028 :     ENSURE(ok);
     206             : 
     207             :     return PSRETURN_OK;
     208        2029 : }
     209             : 
     210        5770 : PSRETURN CXeromyces::LoadString(const char* xml, const std::string& validatorName /* = "" */)
     211             : {
     212        5770 :     xmlDocPtr doc = xmlReadMemory(xml, (int)strlen(xml), "(no file)", NULL, XML_PARSE_NONET|XML_PARSE_NOCDATA);
     213        5770 :     if (!doc)
     214             :     {
     215           1 :         LOGERROR("CXeromyces: Failed to parse XML string");
     216           1 :         return PSRETURN_Xeromyces_XMLParseError;
     217             :     }
     218             : 
     219        5769 :     {
     220        5769 :         std::lock_guard<std::mutex> lock(g_ValidatorCacheLock);
     221        5769 :         RelaxNGValidator& validator = g_Xeromyces.GetValidator(validatorName);
     222        5769 :         if (validator.CanValidate() && !validator.ValidateEncoded(doc))
     223             :         {
     224           0 :             LOGERROR("CXeromyces: failed to validate XML string");
     225           0 :             return PSRETURN_Xeromyces_XMLValidationFailed;
     226             :         }
     227           0 :     }
     228             : 
     229        5769 :     m_Data.LoadXMLDoc(doc);
     230        5769 :     xmlFreeDoc(doc);
     231             : 
     232             :     // Set up the XMBData
     233        5769 :     const bool ok = Initialise(m_Data);
     234        5769 :     ENSURE(ok);
     235             : 
     236             :     return PSRETURN_OK;
     237             : }

Generated by: LCOV version 1.16