BinaryDeserializer.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  1. /*
  2. * BinaryDeserializer.h, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #pragma once
  11. #include <boost/mpl/for_each.hpp>
  12. #include "CTypeList.h"
  13. #include "../mapObjects/CGHeroInstance.h"
  14. #include "../../Global.h"
  15. class CStackInstance;
  16. class FileStream;
  17. class DLL_LINKAGE CLoaderBase
  18. {
  19. protected:
  20. IBinaryReader * reader;
  21. public:
  22. CLoaderBase(IBinaryReader * r): reader(r){};
  23. inline int read(void * data, unsigned size)
  24. {
  25. return reader->read(data, size);
  26. };
  27. };
  28. /// Main class for deserialization of classes from binary form
  29. /// Effectively revesed version of BinarySerializer
  30. class DLL_LINKAGE BinaryDeserializer : public CLoaderBase
  31. {
  32. template<typename Variant, typename Source>
  33. struct VariantLoaderHelper
  34. {
  35. Source & source;
  36. std::vector<std::function<Variant()>> funcs;
  37. VariantLoaderHelper(Source & source):
  38. source(source)
  39. {
  40. boost::mpl::for_each<typename Variant::types>(std::ref(*this));
  41. }
  42. template<typename Type>
  43. void operator()(Type)
  44. {
  45. funcs.push_back([&]() -> Variant
  46. {
  47. Type obj;
  48. source.load(obj);
  49. return Variant(obj);
  50. });
  51. }
  52. };
  53. template<typename Ser,typename T>
  54. struct LoadIfStackInstance
  55. {
  56. static bool invoke(Ser &s, T &data)
  57. {
  58. return false;
  59. }
  60. };
  61. template<typename Ser>
  62. struct LoadIfStackInstance<Ser, CStackInstance *>
  63. {
  64. static bool invoke(Ser &s, CStackInstance* &data)
  65. {
  66. CArmedInstance *armedObj;
  67. SlotID slot;
  68. s.load(armedObj);
  69. s.load(slot);
  70. if(slot != SlotID::COMMANDER_SLOT_PLACEHOLDER)
  71. {
  72. assert(armedObj->hasStackAtSlot(slot));
  73. data = armedObj->stacks[slot];
  74. }
  75. else
  76. {
  77. auto hero = dynamic_cast<CGHeroInstance *>(armedObj);
  78. assert(hero);
  79. assert(hero->commander);
  80. data = hero->commander;
  81. }
  82. return true;
  83. }
  84. };
  85. template <typename T, typename Enable = void>
  86. struct ClassObjectCreator
  87. {
  88. static T *invoke()
  89. {
  90. static_assert(!std::is_abstract<T>::value, "Cannot call new upon abstract classes!");
  91. return new T();
  92. }
  93. };
  94. template<typename T>
  95. struct ClassObjectCreator<T, typename std::enable_if<std::is_abstract<T>::value>::type>
  96. {
  97. static T *invoke()
  98. {
  99. throw std::runtime_error("Something went really wrong during deserialization. Attempted creating an object of an abstract class " + std::string(typeid(T).name()));
  100. }
  101. };
  102. STRONG_INLINE ui32 readAndCheckLength()
  103. {
  104. ui32 length;
  105. load(length);
  106. if(length > 500000)
  107. {
  108. logGlobal->warn("Warning: very big length: %d", length);
  109. reader->reportState(logGlobal);
  110. };
  111. return length;
  112. }
  113. template <typename T> class CPointerLoader;
  114. class CBasicPointerLoader
  115. {
  116. public:
  117. virtual const std::type_info * loadPtr(CLoaderBase &ar, void *data, ui32 pid) const =0; //data is pointer to the ACTUAL POINTER
  118. virtual ~CBasicPointerLoader(){}
  119. template<typename T> static CBasicPointerLoader *getApplier(const T * t=nullptr)
  120. {
  121. return new CPointerLoader<T>();
  122. }
  123. };
  124. template <typename T> class CPointerLoader : public CBasicPointerLoader
  125. {
  126. public:
  127. const std::type_info * loadPtr(CLoaderBase &ar, void *data, ui32 pid) const override //data is pointer to the ACTUAL POINTER
  128. {
  129. BinaryDeserializer &s = static_cast<BinaryDeserializer&>(ar);
  130. T *&ptr = *static_cast<T**>(data);
  131. //create new object under pointer
  132. typedef typename std::remove_pointer<T>::type npT;
  133. ptr = ClassObjectCreator<npT>::invoke(); //does new npT or throws for abstract classes
  134. s.ptrAllocated(ptr, pid);
  135. //T is most derived known type, it's time to call actual serialize
  136. assert(s.fileVersion != 0);
  137. ptr->serialize(s,s.fileVersion);
  138. return &typeid(T);
  139. }
  140. };
  141. CApplier<CBasicPointerLoader> applier;
  142. int write(const void * data, unsigned size);
  143. public:
  144. bool reverseEndianess; //if source has different endianness than us, we reverse bytes
  145. si32 fileVersion;
  146. std::map<ui32, void*> loadedPointers;
  147. std::map<ui32, const std::type_info*> loadedPointersTypes;
  148. std::map<const void*, boost::any> loadedSharedPointers;
  149. bool smartPointerSerialization;
  150. bool saving;
  151. BinaryDeserializer(IBinaryReader * r): CLoaderBase(r)
  152. {
  153. saving = false;
  154. fileVersion = 0;
  155. smartPointerSerialization = true;
  156. reverseEndianess = false;
  157. }
  158. template<class T>
  159. BinaryDeserializer & operator&(T & t)
  160. {
  161. this->load(t);
  162. return * this;
  163. }
  164. template < class T, typename std::enable_if < std::is_fundamental<T>::value && !std::is_same<T, bool>::value, int >::type = 0 >
  165. void load(T &data)
  166. {
  167. unsigned length = sizeof(data);
  168. char* dataPtr = (char*)&data;
  169. this->read(dataPtr,length);
  170. if(reverseEndianess)
  171. std::reverse(dataPtr, dataPtr + length);
  172. }
  173. template < typename T, typename std::enable_if < is_serializeable<BinaryDeserializer, T>::value, int >::type = 0 >
  174. void load(T &data)
  175. {
  176. assert( fileVersion != 0 );
  177. ////that const cast is evil because it allows to implicitly overwrite const objects when deserializing
  178. typedef typename std::remove_const<T>::type nonConstT;
  179. nonConstT &hlp = const_cast<nonConstT&>(data);
  180. hlp.serialize(*this,fileVersion);
  181. }
  182. template < typename T, typename std::enable_if < std::is_array<T>::value, int >::type = 0 >
  183. void load(T &data)
  184. {
  185. ui32 size = ARRAY_COUNT(data);
  186. for(ui32 i = 0; i < size; i++)
  187. load(data[i]);
  188. }
  189. template < typename T, typename std::enable_if < std::is_enum<T>::value, int >::type = 0 >
  190. void load(T &data)
  191. {
  192. si32 read;
  193. load( read );
  194. data = static_cast<T>(read);
  195. }
  196. template < typename T, typename std::enable_if < std::is_same<T, bool>::value, int >::type = 0 >
  197. void load(T &data)
  198. {
  199. ui8 read;
  200. load( read );
  201. data = static_cast<bool>(read);
  202. }
  203. template < typename T, typename std::enable_if < std::is_same<T, std::vector<bool> >::value, int >::type = 0 >
  204. void load(T & data)
  205. {
  206. std::vector<ui8> convData;
  207. load(convData);
  208. convData.resize(data.size());
  209. range::copy(convData, data.begin());
  210. }
  211. template <typename T, typename std::enable_if < !std::is_same<T, bool >::value, int >::type = 0>
  212. void load(std::vector<T> &data)
  213. {
  214. ui32 length = readAndCheckLength();
  215. data.resize(length);
  216. for(ui32 i=0;i<length;i++)
  217. load( data[i]);
  218. }
  219. template < typename T, typename std::enable_if < std::is_pointer<T>::value, int >::type = 0 >
  220. void load(T &data)
  221. {
  222. ui8 hlp;
  223. load( hlp );
  224. if(!hlp)
  225. {
  226. data = nullptr;
  227. return;
  228. }
  229. if(reader->smartVectorMembersSerialization)
  230. {
  231. typedef typename std::remove_const<typename std::remove_pointer<T>::type>::type TObjectType; //eg: const CGHeroInstance * => CGHeroInstance
  232. typedef typename VectorizedTypeFor<TObjectType>::type VType; //eg: CGHeroInstance -> CGobjectInstance
  233. typedef typename VectorizedIDType<TObjectType>::type IDType;
  234. if(const auto *info = reader->getVectorizedTypeInfo<VType, IDType>())
  235. {
  236. IDType id;
  237. load(id);
  238. if(id != IDType(-1))
  239. {
  240. data = static_cast<T>(reader->getVectorItemFromId<VType, IDType>(*info, id));
  241. return;
  242. }
  243. }
  244. }
  245. if(reader->sendStackInstanceByIds)
  246. {
  247. bool gotLoaded = LoadIfStackInstance<BinaryDeserializer,T>::invoke(* this, data);
  248. if(gotLoaded)
  249. return;
  250. }
  251. ui32 pid = 0xffffffff; //pointer id (or maybe rather pointee id)
  252. if(smartPointerSerialization)
  253. {
  254. load( pid ); //get the id
  255. std::map<ui32, void*>::iterator i = loadedPointers.find(pid); //lookup
  256. if(i != loadedPointers.end())
  257. {
  258. // We already got this pointer
  259. // Cast it in case we are loading it to a non-first base pointer
  260. assert(loadedPointersTypes.count(pid));
  261. data = reinterpret_cast<T>(typeList.castRaw(i->second, loadedPointersTypes.at(pid), &typeid(typename std::remove_const<typename std::remove_pointer<T>::type>::type)));
  262. return;
  263. }
  264. }
  265. //get type id
  266. ui16 tid;
  267. load( tid );
  268. if(!tid)
  269. {
  270. typedef typename std::remove_pointer<T>::type npT;
  271. typedef typename std::remove_const<npT>::type ncpT;
  272. data = ClassObjectCreator<ncpT>::invoke();
  273. ptrAllocated(data, pid);
  274. load(*data);
  275. }
  276. else
  277. {
  278. auto app = applier.getApplier(tid);
  279. if(app == nullptr)
  280. {
  281. logGlobal->error("load %d %d - no loader exists", tid, pid);
  282. data = nullptr;
  283. return;
  284. }
  285. auto typeInfo = app->loadPtr(*this,&data, pid);
  286. data = reinterpret_cast<T>(typeList.castRaw((void*)data, typeInfo, &typeid(typename std::remove_const<typename std::remove_pointer<T>::type>::type)));
  287. }
  288. }
  289. template <typename T>
  290. void ptrAllocated(const T *ptr, ui32 pid)
  291. {
  292. if(smartPointerSerialization && pid != 0xffffffff)
  293. {
  294. loadedPointersTypes[pid] = &typeid(T);
  295. loadedPointers[pid] = (void*)ptr; //add loaded pointer to our lookup map; cast is to avoid errors with const T* pt
  296. }
  297. }
  298. template<typename Base, typename Derived> void registerType(const Base * b = nullptr, const Derived * d = nullptr)
  299. {
  300. applier.registerType(b, d);
  301. }
  302. template <typename T>
  303. void load(std::shared_ptr<T> &data)
  304. {
  305. typedef typename std::remove_const<T>::type NonConstT;
  306. NonConstT *internalPtr;
  307. load(internalPtr);
  308. void *internalPtrDerived = typeList.castToMostDerived(internalPtr);
  309. if(internalPtr)
  310. {
  311. auto itr = loadedSharedPointers.find(internalPtrDerived);
  312. if(itr != loadedSharedPointers.end())
  313. {
  314. // This pointers is already loaded. The "data" needs to be pointed to it,
  315. // so their shared state is actually shared.
  316. try
  317. {
  318. auto actualType = typeList.getTypeInfo(internalPtr);
  319. auto typeWeNeedToReturn = typeList.getTypeInfo<T>();
  320. if(*actualType == *typeWeNeedToReturn)
  321. {
  322. // No casting needed, just unpack already stored shared_ptr and return it
  323. data = boost::any_cast<std::shared_ptr<T>>(itr->second);
  324. }
  325. else
  326. {
  327. // We need to perform series of casts
  328. auto ret = typeList.castShared(itr->second, actualType, typeWeNeedToReturn);
  329. data = boost::any_cast<std::shared_ptr<T>>(ret);
  330. }
  331. }
  332. catch(std::exception &e)
  333. {
  334. logGlobal->error(e.what());
  335. logGlobal->error("Failed to cast stored shared ptr. Real type: %s. Needed type %s. FIXME FIXME FIXME", itr->second.type().name(), typeid(std::shared_ptr<T>).name());
  336. //TODO scenario with inheritance -> we can have stored ptr to base and load ptr to derived (or vice versa)
  337. throw;
  338. }
  339. }
  340. else
  341. {
  342. auto hlp = std::shared_ptr<NonConstT>(internalPtr);
  343. data = hlp;
  344. loadedSharedPointers[internalPtrDerived] = typeList.castSharedToMostDerived(hlp);
  345. }
  346. }
  347. else
  348. data.reset();
  349. }
  350. template <typename T>
  351. void load(std::shared_ptr<const T> &data) //version of the above for const ptr
  352. {
  353. typedef typename std::remove_const<T>::type NonConstT;
  354. NonConstT *internalPtr;
  355. load(internalPtr);
  356. void *internalPtrDerived = typeList.castToMostDerived(internalPtr);
  357. if(internalPtr)
  358. {
  359. auto itr = loadedSharedPointers.find(internalPtrDerived);
  360. if(itr != loadedSharedPointers.end())
  361. {
  362. // This pointer is already loaded. The "data" needs to be pointed to it,
  363. // so their shared state is actually shared.
  364. try
  365. {
  366. auto actualType = typeList.getTypeInfo(internalPtr);
  367. auto typeWeNeedToReturn = typeList.getTypeInfo<T>();
  368. if(*actualType == *typeWeNeedToReturn)
  369. {
  370. // No casting needed, just unpack already stored shared_ptr and return it
  371. data = boost::any_cast<std::shared_ptr<const T>>(itr->second);
  372. }
  373. else
  374. {
  375. // We need to perform series of casts
  376. auto ret = typeList.castShared(itr->second, actualType, typeWeNeedToReturn);
  377. data = boost::any_cast<std::shared_ptr<const T>>(ret);
  378. }
  379. }
  380. catch(std::exception &e)
  381. {
  382. logGlobal->error(e.what());
  383. logGlobal->error("Failed to cast stored shared ptr. Real type: %s. Needed type %s. FIXME FIXME FIXME", itr->second.type().name(), typeid(std::shared_ptr<T>).name());
  384. //TODO scenario with inheritance -> we can have stored ptr to base and load ptr to derived (or vice versa)
  385. throw;
  386. }
  387. }
  388. else
  389. {
  390. auto hlp = std::shared_ptr<const T>(internalPtr);
  391. data = hlp; //possibly adds const
  392. loadedSharedPointers[internalPtrDerived] = typeList.castSharedToMostDerived(hlp);
  393. }
  394. }
  395. else
  396. data.reset();
  397. }
  398. template <typename T>
  399. void load(std::unique_ptr<T> &data)
  400. {
  401. T *internalPtr;
  402. load( internalPtr );
  403. data.reset(internalPtr);
  404. }
  405. template <typename T, size_t N>
  406. void load(std::array<T, N> &data)
  407. {
  408. for(ui32 i = 0; i < N; i++)
  409. load( data[i] );
  410. }
  411. template <typename T>
  412. void load(std::set<T> &data)
  413. {
  414. ui32 length = readAndCheckLength();
  415. data.clear();
  416. T ins;
  417. for(ui32 i=0;i<length;i++)
  418. {
  419. load( ins );
  420. data.insert(ins);
  421. }
  422. }
  423. template <typename T, typename U>
  424. void load(std::unordered_set<T, U> &data)
  425. {
  426. ui32 length = readAndCheckLength();
  427. data.clear();
  428. T ins;
  429. for(ui32 i=0;i<length;i++)
  430. {
  431. load(ins);
  432. data.insert(ins);
  433. }
  434. }
  435. template <typename T>
  436. void load(std::list<T> &data)
  437. {
  438. ui32 length = readAndCheckLength();
  439. data.clear();
  440. T ins;
  441. for(ui32 i=0;i<length;i++)
  442. {
  443. load(ins);
  444. data.push_back(ins);
  445. }
  446. }
  447. template <typename T1, typename T2>
  448. void load(std::pair<T1,T2> &data)
  449. {
  450. load(data.first);
  451. load(data.second);
  452. }
  453. template <typename T1, typename T2>
  454. void load(std::map<T1,T2> &data)
  455. {
  456. ui32 length = readAndCheckLength();
  457. data.clear();
  458. T1 key;
  459. T2 value;
  460. for(ui32 i=0;i<length;i++)
  461. {
  462. load(key);
  463. load(value);
  464. data.insert(std::pair<T1, T2>(std::move(key), std::move(value)));
  465. }
  466. }
  467. template <typename T1, typename T2>
  468. void load(std::multimap<T1, T2> &data)
  469. {
  470. ui32 length = readAndCheckLength();
  471. data.clear();
  472. T1 key;
  473. T2 value;
  474. for(ui32 i = 0; i < length; i++)
  475. {
  476. load(key);
  477. load(value);
  478. data.insert(std::pair<T1, T2>(std::move(key), std::move(value)));
  479. }
  480. }
  481. void load(std::string &data)
  482. {
  483. ui32 length = readAndCheckLength();
  484. data.resize(length);
  485. this->read((void*)data.c_str(),length);
  486. }
  487. template <BOOST_VARIANT_ENUM_PARAMS(typename T)>
  488. void load(boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> &data)
  489. {
  490. typedef boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> TVariant;
  491. VariantLoaderHelper<TVariant, BinaryDeserializer> loader(*this);
  492. si32 which;
  493. load( which );
  494. assert(which < loader.funcs.size());
  495. data = loader.funcs.at(which)();
  496. }
  497. template <typename T>
  498. void load(boost::optional<T> & data)
  499. {
  500. ui8 present;
  501. load( present );
  502. if(present)
  503. {
  504. //TODO: replace with emplace once we start request Boost 1.56+, see PR360
  505. T t;
  506. load(t);
  507. data = boost::make_optional(std::move(t));
  508. }
  509. else
  510. {
  511. data = boost::optional<T>();
  512. }
  513. }
  514. };
  515. class DLL_LINKAGE CLoadFile : public IBinaryReader
  516. {
  517. public:
  518. BinaryDeserializer serializer;
  519. std::string fName;
  520. std::unique_ptr<FileStream> sfile;
  521. CLoadFile(const boost::filesystem::path & fname, int minimalVersion = SERIALIZATION_VERSION); //throws!
  522. virtual ~CLoadFile();
  523. int read(void * data, unsigned size) override; //throws!
  524. void openNextFile(const boost::filesystem::path & fname, int minimalVersion); //throws!
  525. void clear();
  526. void reportState(vstd::CLoggerBase * out) override;
  527. void checkMagicBytes(const std::string & text);
  528. template<class T>
  529. CLoadFile & operator>>(T &t)
  530. {
  531. serializer & t;
  532. return * this;
  533. }
  534. };