polymorphic_impl.hpp 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825
  1. /*! \file polymorphic_impl.hpp
  2. \brief Internal polymorphism support
  3. \ingroup Internal */
  4. /*
  5. Copyright (c) 2014, Randolph Voorhies, Shane Grant
  6. All rights reserved.
  7. Redistribution and use in source and binary forms, with or without
  8. modification, are permitted provided that the following conditions are met:
  9. * Redistributions of source code must retain the above copyright
  10. notice, this list of conditions and the following disclaimer.
  11. * Redistributions in binary form must reproduce the above copyright
  12. notice, this list of conditions and the following disclaimer in the
  13. documentation and/or other materials provided with the distribution.
  14. * Neither the name of the copyright holder nor the
  15. names of its contributors may be used to endorse or promote products
  16. derived from this software without specific prior written permission.
  17. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  18. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  19. WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  20. DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
  21. DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  22. (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  23. LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  24. ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  25. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  26. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  27. */
  28. /* This code is heavily inspired by the boost serialization implementation by the following authors
  29. (C) Copyright 2002 Robert Ramey - http://www.rrsd.com .
  30. Use, modification and distribution is subject to the Boost Software
  31. License, Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt)
  32. See http://www.boost.org for updates, documentation, and revision history.
  33. (C) Copyright 2006 David Abrahams - http://www.boost.org.
  34. See /boost/serialization/export.hpp, /boost/archive/detail/register_archive.hpp,
  35. and /boost/serialization/void_cast.hpp for their implementation. Additional details
  36. found in other files split across serialization and archive.
  37. */
  38. #ifndef CEREAL_DETAILS_POLYMORPHIC_IMPL_HPP_
  39. #define CEREAL_DETAILS_POLYMORPHIC_IMPL_HPP_
  40. #include "cereal/details/polymorphic_impl_fwd.hpp"
  41. #include "cereal/details/static_object.hpp"
  42. #include "cereal/types/memory.hpp"
  43. #include "cereal/types/string.hpp"
  44. #include <functional>
  45. #include <typeindex>
  46. #include <map>
  47. #include <limits>
  48. #include <set>
  49. #include <stack>
  50. //! Helper macro to omit unused warning
  51. #if defined(__GNUC__)
  52. // GCC / clang don't want the function
  53. #define CEREAL_BIND_TO_ARCHIVES_UNUSED_FUNCTION
  54. #else
  55. #define CEREAL_BIND_TO_ARCHIVES_UNUSED_FUNCTION static void unused() { (void)b; }
  56. #endif
  57. //! Binds a polymorphic type to all registered archives
  58. /*! This binds a polymorphic type to all compatible registered archives that
  59. have been registered with CEREAL_REGISTER_ARCHIVE. This must be called
  60. after all archives are registered (usually after the archives themselves
  61. have been included). */
  62. #ifdef CEREAL_HAS_CPP17
  63. #define CEREAL_BIND_TO_ARCHIVES(...) \
  64. namespace cereal { \
  65. namespace detail { \
  66. template<> \
  67. struct init_binding<__VA_ARGS__> { \
  68. static inline bind_to_archives<__VA_ARGS__> const & b= \
  69. ::cereal::detail::StaticObject< \
  70. bind_to_archives<__VA_ARGS__> \
  71. >::getInstance().bind(); \
  72. CEREAL_BIND_TO_ARCHIVES_UNUSED_FUNCTION \
  73. }; \
  74. }} /* end namespaces */
  75. #else
  76. #define CEREAL_BIND_TO_ARCHIVES(...) \
  77. namespace cereal { \
  78. namespace detail { \
  79. template<> \
  80. struct init_binding<__VA_ARGS__> { \
  81. static bind_to_archives<__VA_ARGS__> const& b; \
  82. CEREAL_BIND_TO_ARCHIVES_UNUSED_FUNCTION \
  83. }; \
  84. bind_to_archives<__VA_ARGS__> const & init_binding<__VA_ARGS__>::b = \
  85. ::cereal::detail::StaticObject< \
  86. bind_to_archives<__VA_ARGS__> \
  87. >::getInstance().bind(); \
  88. }} /* end namespaces */
  89. #endif
  90. namespace cereal
  91. {
  92. /* Polymorphic casting support */
  93. namespace detail
  94. {
  95. //! Base type for polymorphic void casting
  96. /*! Contains functions for casting between registered base and derived types.
  97. This is necessary so that cereal can properly cast between polymorphic types
  98. even though void pointers are used, which normally have no type information.
  99. Runtime type information is used instead to index a compile-time made mapping
  100. that can perform the proper cast. In the case of multiple levels of inheritance,
  101. cereal will attempt to find the shortest path by using registered relationships to
  102. perform the cast.
  103. This class will be allocated as a StaticObject and only referenced by pointer,
  104. allowing a templated derived version of it to define strongly typed functions
  105. that cast between registered base and derived types. */
  106. struct PolymorphicCaster
  107. {
  108. PolymorphicCaster() = default;
  109. PolymorphicCaster( const PolymorphicCaster & ) = default;
  110. PolymorphicCaster & operator=( const PolymorphicCaster & ) = default;
  111. PolymorphicCaster( PolymorphicCaster && ) CEREAL_NOEXCEPT {}
  112. PolymorphicCaster & operator=( PolymorphicCaster && ) CEREAL_NOEXCEPT { return *this; }
  113. virtual ~PolymorphicCaster() CEREAL_NOEXCEPT = default;
  114. //! Downcasts to the proper derived type
  115. virtual void const * downcast( void const * const ptr ) const = 0;
  116. //! Upcast to proper base type
  117. virtual void * upcast( void * const ptr ) const = 0;
  118. //! Upcast to proper base type, shared_ptr version
  119. virtual std::shared_ptr<void> upcast( std::shared_ptr<void> const & ptr ) const = 0;
  120. };
  121. //! Holds registered mappings between base and derived types for casting
  122. /*! This will be allocated as a StaticObject and holds a map containing
  123. all registered mappings between base and derived types. */
  124. struct PolymorphicCasters
  125. {
  126. //! Maps from a derived type index to a set of chainable casters
  127. using DerivedCasterMap = std::unordered_map<std::type_index, std::vector<PolymorphicCaster const *>>;
  128. //! Maps from base type index to a map from derived type index to caster
  129. std::unordered_map<std::type_index, DerivedCasterMap> map;
  130. std::multimap<std::type_index, std::type_index> reverseMap;
  131. //! Error message used for unregistered polymorphic casts
  132. #define UNREGISTERED_POLYMORPHIC_CAST_EXCEPTION(LoadSave) \
  133. throw cereal::Exception("Trying to " #LoadSave " a registered polymorphic type with an unregistered polymorphic cast.\n" \
  134. "Could not find a path to a base class (" + util::demangle(baseInfo.name()) + ") for type: " + ::cereal::util::demangledName<Derived>() + "\n" \
  135. "Make sure you either serialize the base class at some point via cereal::base_class or cereal::virtual_base_class.\n" \
  136. "Alternatively, manually register the association with CEREAL_REGISTER_POLYMORPHIC_RELATION.");
  137. //! Checks if the mapping object that can perform the upcast or downcast exists, and returns it if so
  138. /*! Uses the type index from the base and derived class to find the matching
  139. registered caster. If no matching caster exists, the bool in the pair will be false and the vector
  140. reference should not be used. */
  141. static std::pair<bool, std::vector<PolymorphicCaster const *> const &>
  142. lookup_if_exists( std::type_index const & baseIndex, std::type_index const & derivedIndex )
  143. {
  144. // First phase of lookup - match base type index
  145. auto const & baseMap = StaticObject<PolymorphicCasters>::getInstance().map;
  146. auto baseIter = baseMap.find( baseIndex );
  147. if (baseIter == baseMap.end())
  148. return {false, {}};
  149. // Second phase - find a match from base to derived
  150. auto const & derivedMap = baseIter->second;
  151. auto derivedIter = derivedMap.find( derivedIndex );
  152. if (derivedIter == derivedMap.end())
  153. return {false, {}};
  154. return {true, derivedIter->second};
  155. }
  156. //! Gets the mapping object that can perform the upcast or downcast
  157. /*! Uses the type index from the base and derived class to find the matching
  158. registered caster. If no matching caster exists, calls the exception function.
  159. The returned PolymorphicCaster is capable of upcasting or downcasting between the two types. */
  160. template <class F> inline
  161. static std::vector<PolymorphicCaster const *> const & lookup( std::type_index const & baseIndex, std::type_index const & derivedIndex, F && exceptionFunc )
  162. {
  163. // First phase of lookup - match base type index
  164. auto const & baseMap = StaticObject<PolymorphicCasters>::getInstance().map;
  165. auto baseIter = baseMap.find( baseIndex );
  166. if( baseIter == baseMap.end() )
  167. exceptionFunc();
  168. // Second phase - find a match from base to derived
  169. auto const & derivedMap = baseIter->second;
  170. auto derivedIter = derivedMap.find( derivedIndex );
  171. if( derivedIter == derivedMap.end() )
  172. exceptionFunc();
  173. return derivedIter->second;
  174. }
  175. //! Performs a downcast to the derived type using a registered mapping
  176. template <class Derived> inline
  177. static const Derived * downcast( const void * dptr, std::type_info const & baseInfo )
  178. {
  179. auto const & mapping = lookup( baseInfo, typeid(Derived), [&](){ UNREGISTERED_POLYMORPHIC_CAST_EXCEPTION(save) } );
  180. for( auto const * dmap : mapping )
  181. dptr = dmap->downcast( dptr );
  182. return static_cast<Derived const *>( dptr );
  183. }
  184. //! Performs an upcast to the registered base type using the given a derived type
  185. /*! The return is untyped because the final casting to the base type must happen in the polymorphic
  186. serialization function, where the type is known at compile time */
  187. template <class Derived> inline
  188. static void * upcast( Derived * const dptr, std::type_info const & baseInfo )
  189. {
  190. auto const & mapping = lookup( baseInfo, typeid(Derived), [&](){ UNREGISTERED_POLYMORPHIC_CAST_EXCEPTION(load) } );
  191. void * uptr = dptr;
  192. for( auto mIter = mapping.rbegin(), mEnd = mapping.rend(); mIter != mEnd; ++mIter )
  193. uptr = (*mIter)->upcast( uptr );
  194. return uptr;
  195. }
  196. //! Upcasts for shared pointers
  197. template <class Derived> inline
  198. static std::shared_ptr<void> upcast( std::shared_ptr<Derived> const & dptr, std::type_info const & baseInfo )
  199. {
  200. auto const & mapping = lookup( baseInfo, typeid(Derived), [&](){ UNREGISTERED_POLYMORPHIC_CAST_EXCEPTION(load) } );
  201. std::shared_ptr<void> uptr = dptr;
  202. for( auto mIter = mapping.rbegin(), mEnd = mapping.rend(); mIter != mEnd; ++mIter )
  203. uptr = (*mIter)->upcast( uptr );
  204. return uptr;
  205. }
  206. #undef UNREGISTERED_POLYMORPHIC_CAST_EXCEPTION
  207. };
  208. #ifdef CEREAL_OLDER_GCC
  209. #define CEREAL_EMPLACE_MAP(map, key, value) \
  210. map.insert( std::make_pair(std::move(key), std::move(value)) );
  211. #else // NOT CEREAL_OLDER_GCC
  212. #define CEREAL_EMPLACE_MAP(map, key, value) \
  213. map.emplace( key, value );
  214. #endif // NOT_CEREAL_OLDER_GCC
  215. //! Strongly typed derivation of PolymorphicCaster
  216. template <class Base, class Derived>
  217. struct PolymorphicVirtualCaster : PolymorphicCaster
  218. {
  219. //! Inserts an entry in the polymorphic casting map for this pairing
  220. /*! Creates an explicit mapping between Base and Derived in both upwards and
  221. downwards directions, allowing void pointers to either to be properly cast
  222. assuming dynamic type information is available */
  223. PolymorphicVirtualCaster()
  224. {
  225. const auto baseKey = std::type_index(typeid(Base));
  226. const auto derivedKey = std::type_index(typeid(Derived));
  227. // First insert the relation Base->Derived
  228. const auto lock = StaticObject<PolymorphicCasters>::lock();
  229. auto & baseMap = StaticObject<PolymorphicCasters>::getInstance().map;
  230. {
  231. auto & derivedMap = baseMap.insert( {baseKey, PolymorphicCasters::DerivedCasterMap{}} ).first->second;
  232. auto & derivedVec = derivedMap.insert( {derivedKey, {}} ).first->second;
  233. derivedVec.push_back( this );
  234. }
  235. // Insert reverse relation Derived->Base
  236. auto & reverseMap = StaticObject<PolymorphicCasters>::getInstance().reverseMap;
  237. CEREAL_EMPLACE_MAP(reverseMap, derivedKey, baseKey);
  238. // Find all chainable unregistered relations
  239. /* The strategy here is to process only the nodes in the class hierarchy graph that have been
  240. affected by the new insertion. The algorithm iteratively processes a node an ensures that it
  241. is updated with all new shortest length paths. It then processes the parents of the active node,
  242. with the knowledge that all children have already been processed.
  243. Note that for the following, we'll use the nomenclature of parent and child to not confuse with
  244. the inserted base derived relationship */
  245. {
  246. // Checks whether there is a path from parent->child and returns a <dist, path> pair
  247. // dist is set to MAX if the path does not exist
  248. auto checkRelation = [](std::type_index const & parentInfo, std::type_index const & childInfo) ->
  249. std::pair<size_t, std::vector<PolymorphicCaster const *> const &>
  250. {
  251. auto result = PolymorphicCasters::lookup_if_exists( parentInfo, childInfo );
  252. if( result.first )
  253. {
  254. auto const & path = result.second;
  255. return {path.size(), path};
  256. }
  257. else
  258. return {(std::numeric_limits<size_t>::max)(), {}};
  259. };
  260. std::stack<std::type_index> parentStack; // Holds the parent nodes to be processed
  261. std::vector<std::type_index> dirtySet; // Marks child nodes that have been changed
  262. std::unordered_set<std::type_index> processedParents; // Marks parent nodes that have been processed
  263. // Checks if a child has been marked dirty
  264. auto isDirty = [&](std::type_index const & c)
  265. {
  266. auto const dirtySetSize = dirtySet.size();
  267. for( size_t i = 0; i < dirtySetSize; ++i )
  268. if( dirtySet[i] == c )
  269. return true;
  270. return false;
  271. };
  272. // Begin processing the base key and mark derived as dirty
  273. parentStack.push( baseKey );
  274. dirtySet.emplace_back( derivedKey );
  275. while( !parentStack.empty() )
  276. {
  277. using Relations = std::unordered_multimap<std::type_index, std::pair<std::type_index, std::vector<PolymorphicCaster const *>>>;
  278. Relations unregisteredRelations; // Defer insertions until after main loop to prevent iterator invalidation
  279. const auto parent = parentStack.top();
  280. parentStack.pop();
  281. // Update paths to all children marked dirty
  282. for( auto const & childPair : baseMap[parent] )
  283. {
  284. const auto child = childPair.first;
  285. if( isDirty( child ) && baseMap.count( child ) )
  286. {
  287. auto parentChildPath = checkRelation( parent, child );
  288. // Search all paths from the child to its own children (finalChild),
  289. // looking for a shorter path from parent to finalChild
  290. for( auto const & finalChildPair : baseMap[child] )
  291. {
  292. const auto finalChild = finalChildPair.first;
  293. auto parentFinalChildPath = checkRelation( parent, finalChild );
  294. auto childFinalChildPath = checkRelation( child, finalChild );
  295. const size_t newLength = 1u + parentChildPath.first;
  296. if( newLength < parentFinalChildPath.first )
  297. {
  298. std::vector<PolymorphicCaster const *> path = parentChildPath.second;
  299. path.insert( path.end(), childFinalChildPath.second.begin(), childFinalChildPath.second.end() );
  300. // Check to see if we have a previous uncommitted path in unregisteredRelations
  301. // that is shorter. If so, ignore this path
  302. auto hintRange = unregisteredRelations.equal_range( parent );
  303. auto hint = hintRange.first;
  304. for( ; hint != hintRange.second; ++hint )
  305. if( hint->second.first == finalChild )
  306. break;
  307. const bool uncommittedExists = hint != unregisteredRelations.end();
  308. if( uncommittedExists && (hint->second.second.size() <= newLength) )
  309. continue;
  310. auto newPath = std::pair<std::type_index, std::vector<PolymorphicCaster const *>>{finalChild, std::move(path)};
  311. // Insert the new path if it doesn't exist, otherwise this will just lookup where to do the
  312. // replacement
  313. #ifdef CEREAL_OLDER_GCC
  314. auto old = unregisteredRelations.insert( hint, std::make_pair(parent, newPath) );
  315. #else // NOT CEREAL_OLDER_GCC
  316. auto old = unregisteredRelations.emplace_hint( hint, parent, newPath );
  317. #endif // NOT CEREAL_OLDER_GCC
  318. // If there was an uncommitted path, we need to perform a replacement
  319. if( uncommittedExists )
  320. old->second = newPath;
  321. }
  322. } // end loop over child's children
  323. } // end if dirty and child has children
  324. } // end loop over children
  325. // Insert chained relations
  326. for( auto const & it : unregisteredRelations )
  327. {
  328. auto & derivedMap = baseMap.find( it.first )->second;
  329. derivedMap[it.second.first] = it.second.second;
  330. CEREAL_EMPLACE_MAP(reverseMap, it.second.first, it.first );
  331. }
  332. // Mark current parent as modified
  333. dirtySet.emplace_back( parent );
  334. // Insert all parents of the current parent node that haven't yet been processed
  335. auto parentRange = reverseMap.equal_range( parent );
  336. for( auto pIter = parentRange.first; pIter != parentRange.second; ++pIter )
  337. {
  338. const auto pParent = pIter->second;
  339. if( !processedParents.count( pParent ) )
  340. {
  341. parentStack.push( pParent );
  342. processedParents.insert( pParent );
  343. }
  344. }
  345. } // end loop over parent stack
  346. } // end chainable relations
  347. } // end PolymorphicVirtualCaster()
  348. #undef CEREAL_EMPLACE_MAP
  349. //! Performs the proper downcast with the templated types
  350. void const * downcast( void const * const ptr ) const override
  351. {
  352. return dynamic_cast<Derived const*>( static_cast<Base const*>( ptr ) );
  353. }
  354. //! Performs the proper upcast with the templated types
  355. void * upcast( void * const ptr ) const override
  356. {
  357. return dynamic_cast<Base*>( static_cast<Derived*>( ptr ) );
  358. }
  359. //! Performs the proper upcast with the templated types (shared_ptr version)
  360. std::shared_ptr<void> upcast( std::shared_ptr<void> const & ptr ) const override
  361. {
  362. return std::dynamic_pointer_cast<Base>( std::static_pointer_cast<Derived>( ptr ) );
  363. }
  364. };
  365. //! Registers a polymorphic casting relation between a Base and Derived type
  366. /*! Registering a relation allows cereal to properly cast between the two types
  367. given runtime type information and void pointers.
  368. Registration happens automatically via cereal::base_class and cereal::virtual_base_class
  369. instantiations. For cases where neither is called, see the CEREAL_REGISTER_POLYMORPHIC_RELATION
  370. macro */
  371. template <class Base, class Derived>
  372. struct RegisterPolymorphicCaster
  373. {
  374. static PolymorphicCaster const * bind( std::true_type /* is_polymorphic<Base> */)
  375. {
  376. return &StaticObject<PolymorphicVirtualCaster<Base, Derived>>::getInstance();
  377. }
  378. static PolymorphicCaster const * bind( std::false_type /* is_polymorphic<Base> */ )
  379. { return nullptr; }
  380. //! Performs registration (binding) between Base and Derived
  381. /*! If the type is not polymorphic, nothing will happen */
  382. static PolymorphicCaster const * bind()
  383. { return bind( typename std::is_polymorphic<Base>::type() ); }
  384. };
  385. }
  386. /* General polymorphism support */
  387. namespace detail
  388. {
  389. //! Binds a compile time type with a user defined string
  390. template <class T>
  391. struct binding_name {};
  392. //! A structure holding a map from type_indices to output serializer functions
  393. /*! A static object of this map should be created for each registered archive
  394. type, containing entries for every registered type that describe how to
  395. properly cast the type to its real type in polymorphic scenarios for
  396. shared_ptr, weak_ptr, and unique_ptr. */
  397. template <class Archive>
  398. struct OutputBindingMap
  399. {
  400. //! A serializer function
  401. /*! Serializer functions return nothing and take an archive as
  402. their first parameter (will be cast properly inside the function,
  403. a pointer to actual data (contents of smart_ptr's get() function)
  404. as their second parameter, and the type info of the owning smart_ptr
  405. as their final parameter */
  406. typedef std::function<void(void*, void const *, std::type_info const &)> Serializer;
  407. //! Struct containing the serializer functions for all pointer types
  408. struct Serializers
  409. {
  410. Serializer shared_ptr, //!< Serializer function for shared/weak pointers
  411. unique_ptr; //!< Serializer function for unique pointers
  412. };
  413. //! A map of serializers for pointers of all registered types
  414. std::map<std::type_index, Serializers> map;
  415. };
  416. //! An empty noop deleter
  417. template<class T> struct EmptyDeleter { void operator()(T *) const {} };
  418. //! A structure holding a map from type name strings to input serializer functions
  419. /*! A static object of this map should be created for each registered archive
  420. type, containing entries for every registered type that describe how to
  421. properly cast the type to its real type in polymorphic scenarios for
  422. shared_ptr, weak_ptr, and unique_ptr. */
  423. template <class Archive>
  424. struct InputBindingMap
  425. {
  426. //! Shared ptr serializer function
  427. /*! Serializer functions return nothing and take an archive as
  428. their first parameter (will be cast properly inside the function,
  429. a shared_ptr (or unique_ptr for the unique case) of any base
  430. type, and the type id of said base type as the third parameter.
  431. Internally it will properly be loaded and cast to the correct type. */
  432. typedef std::function<void(void*, std::shared_ptr<void> &, std::type_info const &)> SharedSerializer;
  433. //! Unique ptr serializer function
  434. typedef std::function<void(void*, std::unique_ptr<void, EmptyDeleter<void>> &, std::type_info const &)> UniqueSerializer;
  435. //! Struct containing the serializer functions for all pointer types
  436. struct Serializers
  437. {
  438. SharedSerializer shared_ptr; //!< Serializer function for shared/weak pointers
  439. UniqueSerializer unique_ptr; //!< Serializer function for unique pointers
  440. };
  441. //! A map of serializers for pointers of all registered types
  442. std::map<std::string, Serializers> map;
  443. };
  444. // forward decls for archives from cereal.hpp
  445. class InputArchiveBase;
  446. class OutputArchiveBase;
  447. //! Creates a binding (map entry) between an input archive type and a polymorphic type
  448. /*! Bindings are made when types are registered, assuming that at least one
  449. archive has already been registered. When this struct is created,
  450. it will insert (at run time) an entry into a map that properly handles
  451. casting for serializing polymorphic objects */
  452. template <class Archive, class T> struct InputBindingCreator
  453. {
  454. //! Initialize the binding
  455. InputBindingCreator()
  456. {
  457. auto & map = StaticObject<InputBindingMap<Archive>>::getInstance().map;
  458. auto lock = StaticObject<InputBindingMap<Archive>>::lock();
  459. auto key = std::string(binding_name<T>::name());
  460. auto lb = map.lower_bound(key);
  461. if (lb != map.end() && lb->first == key)
  462. return;
  463. typename InputBindingMap<Archive>::Serializers serializers;
  464. serializers.shared_ptr =
  465. [](void * arptr, std::shared_ptr<void> & dptr, std::type_info const & baseInfo)
  466. {
  467. Archive & ar = *static_cast<Archive*>(arptr);
  468. std::shared_ptr<T> ptr;
  469. ar( CEREAL_NVP_("ptr_wrapper", ::cereal::memory_detail::make_ptr_wrapper(ptr)) );
  470. dptr = PolymorphicCasters::template upcast<T>( ptr, baseInfo );
  471. };
  472. serializers.unique_ptr =
  473. [](void * arptr, std::unique_ptr<void, EmptyDeleter<void>> & dptr, std::type_info const & baseInfo)
  474. {
  475. Archive & ar = *static_cast<Archive*>(arptr);
  476. std::unique_ptr<T> ptr;
  477. ar( CEREAL_NVP_("ptr_wrapper", ::cereal::memory_detail::make_ptr_wrapper(ptr)) );
  478. dptr.reset( PolymorphicCasters::template upcast<T>( ptr.release(), baseInfo ));
  479. };
  480. map.insert( lb, { std::move(key), std::move(serializers) } );
  481. }
  482. };
  483. //! Creates a binding (map entry) between an output archive type and a polymorphic type
  484. /*! Bindings are made when types are registered, assuming that at least one
  485. archive has already been registered. When this struct is created,
  486. it will insert (at run time) an entry into a map that properly handles
  487. casting for serializing polymorphic objects */
  488. template <class Archive, class T> struct OutputBindingCreator
  489. {
  490. //! Writes appropriate metadata to the archive for this polymorphic type
  491. static void writeMetadata(Archive & ar)
  492. {
  493. // Register the polymorphic type name with the archive, and get the id
  494. char const * name = binding_name<T>::name();
  495. std::uint32_t id = ar.registerPolymorphicType(name);
  496. // Serialize the id
  497. ar( CEREAL_NVP_("polymorphic_id", id) );
  498. // If the msb of the id is 1, then the type name is new, and we should serialize it
  499. if( id & detail::msb_32bit )
  500. {
  501. std::string namestring(name);
  502. ar( CEREAL_NVP_("polymorphic_name", namestring) );
  503. }
  504. }
  505. //! Holds a properly typed shared_ptr to the polymorphic type
  506. class PolymorphicSharedPointerWrapper
  507. {
  508. public:
  509. /*! Wrap a raw polymorphic pointer in a shared_ptr to its true type
  510. The wrapped pointer will not be responsible for ownership of the held pointer
  511. so it will not attempt to destroy it; instead the refcount of the wrapped
  512. pointer will be tied to a fake 'ownership pointer' that will do nothing
  513. when it ultimately goes out of scope.
  514. The main reason for doing this, other than not to destroy the true object
  515. with our wrapper pointer, is to avoid meddling with the internal reference
  516. count in a polymorphic type that inherits from std::enable_shared_from_this.
  517. @param dptr A void pointer to the contents of the shared_ptr to serialize */
  518. PolymorphicSharedPointerWrapper( T const * dptr ) : refCount(), wrappedPtr( refCount, dptr )
  519. { }
  520. //! Get the wrapped shared_ptr */
  521. inline std::shared_ptr<T const> const & operator()() const { return wrappedPtr; }
  522. private:
  523. std::shared_ptr<void> refCount; //!< The ownership pointer
  524. std::shared_ptr<T const> wrappedPtr; //!< The wrapped pointer
  525. };
  526. //! Does the actual work of saving a polymorphic shared_ptr
  527. /*! This function will properly create a shared_ptr from the void * that is passed in
  528. before passing it to the archive for serialization.
  529. In addition, this will also preserve the state of any internal enable_shared_from_this mechanisms
  530. @param ar The archive to serialize to
  531. @param dptr Pointer to the actual data held by the shared_ptr */
  532. static inline void savePolymorphicSharedPtr( Archive & ar, T const * dptr, std::true_type /* has_shared_from_this */ )
  533. {
  534. ::cereal::memory_detail::EnableSharedStateHelper<T> state( const_cast<T *>(dptr) );
  535. PolymorphicSharedPointerWrapper psptr( dptr );
  536. ar( CEREAL_NVP_("ptr_wrapper", memory_detail::make_ptr_wrapper( psptr() ) ) );
  537. }
  538. //! Does the actual work of saving a polymorphic shared_ptr
  539. /*! This function will properly create a shared_ptr from the void * that is passed in
  540. before passing it to the archive for serialization.
  541. This version is for types that do not inherit from std::enable_shared_from_this.
  542. @param ar The archive to serialize to
  543. @param dptr Pointer to the actual data held by the shared_ptr */
  544. static inline void savePolymorphicSharedPtr( Archive & ar, T const * dptr, std::false_type /* has_shared_from_this */ )
  545. {
  546. PolymorphicSharedPointerWrapper psptr( dptr );
  547. ar( CEREAL_NVP_("ptr_wrapper", memory_detail::make_ptr_wrapper( psptr() ) ) );
  548. }
  549. //! Initialize the binding
  550. OutputBindingCreator()
  551. {
  552. auto & map = StaticObject<OutputBindingMap<Archive>>::getInstance().map;
  553. auto key = std::type_index(typeid(T));
  554. auto lb = map.lower_bound(key);
  555. if (lb != map.end() && lb->first == key)
  556. return;
  557. typename OutputBindingMap<Archive>::Serializers serializers;
  558. serializers.shared_ptr =
  559. [&](void * arptr, void const * dptr, std::type_info const & baseInfo)
  560. {
  561. Archive & ar = *static_cast<Archive*>(arptr);
  562. writeMetadata(ar);
  563. auto ptr = PolymorphicCasters::template downcast<T>( dptr, baseInfo );
  564. #if defined(_MSC_VER) && _MSC_VER < 1916 && !defined(__clang__)
  565. savePolymorphicSharedPtr( ar, ptr, ::cereal::traits::has_shared_from_this<T>::type() ); // MSVC doesn't like typename here
  566. #else // not _MSC_VER
  567. savePolymorphicSharedPtr( ar, ptr, typename ::cereal::traits::has_shared_from_this<T>::type() );
  568. #endif // _MSC_VER
  569. };
  570. serializers.unique_ptr =
  571. [&](void * arptr, void const * dptr, std::type_info const & baseInfo)
  572. {
  573. Archive & ar = *static_cast<Archive*>(arptr);
  574. writeMetadata(ar);
  575. std::unique_ptr<T const, EmptyDeleter<T const>> const ptr( PolymorphicCasters::template downcast<T>( dptr, baseInfo ) );
  576. ar( CEREAL_NVP_("ptr_wrapper", memory_detail::make_ptr_wrapper(ptr)) );
  577. };
  578. map.insert( { std::move(key), std::move(serializers) } );
  579. }
  580. };
  581. //! Used to help out argument dependent lookup for finding potential overloads
  582. //! of instantiate_polymorphic_binding
  583. struct adl_tag {};
  584. //! Tag for init_binding, bind_to_archives and instantiate_polymorphic_binding.
  585. //! For C++14 and below, we must instantiate a unique StaticObject per TU that is
  586. //! otherwise identical -- otherwise we get multiple definition problems (ODR violations).
  587. //! To achieve this, put a tag in an anonymous namespace and use it as a template argument.
  588. //!
  589. //! For C++17, we can use static inline global variables to unify these definitions across
  590. //! all TUs in the same shared object (DLL). The tag is therefore not necessary.
  591. //! For convenience, keep it to not complicate other code, but don't put it in
  592. //! an anonymous namespace. Now the template instantiations will correspond
  593. //! to the same type, and since they are marked inline with C++17, they will be merged
  594. //! across all TUs.
  595. #ifdef CEREAL_HAS_CPP17
  596. struct polymorphic_binding_tag {};
  597. #else
  598. namespace { struct polymorphic_binding_tag {}; }
  599. #endif
  600. //! Causes the static object bindings between an archive type and a serializable type T
  601. template <class Archive, class T>
  602. struct create_bindings
  603. {
  604. static const InputBindingCreator<Archive, T> &
  605. load(std::true_type)
  606. {
  607. return cereal::detail::StaticObject<InputBindingCreator<Archive, T>>::getInstance();
  608. }
  609. static const OutputBindingCreator<Archive, T> &
  610. save(std::true_type)
  611. {
  612. return cereal::detail::StaticObject<OutputBindingCreator<Archive, T>>::getInstance();
  613. }
  614. inline static void load(std::false_type) {}
  615. inline static void save(std::false_type) {}
  616. };
  617. //! When specialized, causes the compiler to instantiate its parameter
  618. template <void(*)()>
  619. struct instantiate_function {};
  620. /*! This struct is used as the return type of instantiate_polymorphic_binding
  621. for specific Archive types. When the compiler looks for overloads of
  622. instantiate_polymorphic_binding, it will be forced to instantiate this
  623. struct during overload resolution, even though it will not be part of a valid
  624. overload */
  625. template <class Archive, class T>
  626. struct polymorphic_serialization_support
  627. {
  628. #if defined(_MSC_VER) && !defined(__INTEL_COMPILER)
  629. //! Creates the appropriate bindings depending on whether the archive supports
  630. //! saving or loading
  631. virtual CEREAL_DLL_EXPORT void instantiate() CEREAL_USED;
  632. #else // NOT _MSC_VER
  633. //! Creates the appropriate bindings depending on whether the archive supports
  634. //! saving or loading
  635. static CEREAL_DLL_EXPORT void instantiate() CEREAL_USED;
  636. //! This typedef causes the compiler to instantiate this static function
  637. typedef instantiate_function<instantiate> unused;
  638. #endif // _MSC_VER
  639. };
  640. // instantiate implementation
  641. template <class Archive, class T>
  642. CEREAL_DLL_EXPORT void polymorphic_serialization_support<Archive,T>::instantiate()
  643. {
  644. create_bindings<Archive,T>::save( std::integral_constant<bool,
  645. std::is_base_of<detail::OutputArchiveBase, Archive>::value &&
  646. traits::is_output_serializable<T, Archive>::value>{} );
  647. create_bindings<Archive,T>::load( std::integral_constant<bool,
  648. std::is_base_of<detail::InputArchiveBase, Archive>::value &&
  649. traits::is_input_serializable<T, Archive>::value>{} );
  650. }
  651. //! Begins the binding process of a type to all registered archives
  652. /*! Archives need to be registered prior to this struct being instantiated via
  653. the CEREAL_REGISTER_ARCHIVE macro. Overload resolution will then force
  654. several static objects to be made that allow us to bind together all
  655. registered archive types with the parameter type T. */
  656. template <class T, class Tag = polymorphic_binding_tag>
  657. struct bind_to_archives
  658. {
  659. //! Binding for non abstract types
  660. void bind(std::false_type) const
  661. {
  662. instantiate_polymorphic_binding(static_cast<T*>(nullptr), 0, Tag{}, adl_tag{});
  663. }
  664. //! Binding for abstract types
  665. void bind(std::true_type) const
  666. { }
  667. //! Binds the type T to all registered archives
  668. /*! If T is abstract, we will not serialize it and thus
  669. do not need to make a binding */
  670. bind_to_archives const & bind() const
  671. {
  672. static_assert( std::is_polymorphic<T>::value,
  673. "Attempting to register non polymorphic type" );
  674. bind( std::is_abstract<T>() );
  675. return *this;
  676. }
  677. };
  678. //! Used to hide the static object used to bind T to registered archives
  679. template <class T, class Tag = polymorphic_binding_tag>
  680. struct init_binding;
  681. //! Base case overload for instantiation
  682. /*! This will end up always being the best overload due to the second
  683. parameter always being passed as an int. All other overloads will
  684. accept pointers to archive types and have lower precedence than int.
  685. Since the compiler needs to check all possible overloads, the
  686. other overloads created via CEREAL_REGISTER_ARCHIVE, which will have
  687. lower precedence due to requiring a conversion from int to (Archive*),
  688. will cause their return types to be instantiated through the static object
  689. mechanisms even though they are never called.
  690. See the documentation for the other functions to try and understand this */
  691. template <class T, typename BindingTag>
  692. void instantiate_polymorphic_binding( T*, int, BindingTag, adl_tag ) {}
  693. } // namespace detail
  694. } // namespace cereal
  695. #endif // CEREAL_DETAILS_POLYMORPHIC_IMPL_HPP_