BinaryDeserializer.h 13 KB

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