intermodule_singleton_common.hpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. //////////////////////////////////////////////////////////////////////////////
  2. //
  3. // (C) Copyright Ion Gaztanaga 2009-2012. Distributed under the Boost
  4. // Software License, Version 1.0. (See accompanying file
  5. // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. //
  7. // See http://www.boost.org/libs/interprocess for documentation.
  8. //
  9. //////////////////////////////////////////////////////////////////////////////
  10. #ifndef BOOST_INTERPROCESS_INTERMODULE_SINGLETON_COMMON_HPP
  11. #define BOOST_INTERPROCESS_INTERMODULE_SINGLETON_COMMON_HPP
  12. #ifndef BOOST_CONFIG_HPP
  13. # include <boost/config.hpp>
  14. #endif
  15. #
  16. #if defined(BOOST_HAS_PRAGMA_ONCE)
  17. #pragma once
  18. #endif
  19. #include <boost/interprocess/detail/config_begin.hpp>
  20. #include <boost/interprocess/detail/workaround.hpp>
  21. #include <boost/interprocess/detail/atomic.hpp>
  22. #include <boost/interprocess/detail/os_thread_functions.hpp>
  23. #include <boost/interprocess/exceptions.hpp>
  24. #include <boost/container/detail/type_traits.hpp> //alignment_of, aligned_storage
  25. #include <boost/interprocess/detail/mpl.hpp>
  26. #include <boost/interprocess/sync/spin/wait.hpp>
  27. #include <boost/assert.hpp>
  28. #include <cstddef>
  29. #include <cstdio>
  30. #include <cstdlib>
  31. #include <cstring>
  32. #include <string>
  33. #include <typeinfo>
  34. #include <sstream>
  35. namespace boost{
  36. namespace interprocess{
  37. namespace ipcdetail{
  38. namespace intermodule_singleton_helpers {
  39. inline void get_pid_creation_time_str(std::string &s)
  40. {
  41. std::stringstream stream;
  42. stream << get_current_process_id() << '_';
  43. const unsigned long long total_microsecs = get_current_process_creation_time();
  44. const unsigned long secs = static_cast<unsigned long>(total_microsecs/1000000ul);
  45. const unsigned long usecs = static_cast<unsigned long>(total_microsecs%1000000ul);
  46. stream << secs << '.' << usecs;
  47. s = stream.str();
  48. }
  49. inline const char *get_map_base_name()
  50. { return "bip.gmem.map."; }
  51. inline void get_map_name(std::string &map_name)
  52. {
  53. get_pid_creation_time_str(map_name);
  54. map_name.insert(0, get_map_base_name());
  55. }
  56. inline std::size_t get_map_size()
  57. { return 65536; }
  58. template<class ThreadSafeGlobalMap>
  59. struct thread_safe_global_map_dependant;
  60. } //namespace intermodule_singleton_helpers {
  61. //This class contains common code for all singleton types, so that we instantiate this
  62. //code just once per module. This class also holds a thread soafe global map
  63. //to be used by all instances protected with a reference count
  64. template<class ThreadSafeGlobalMap>
  65. class intermodule_singleton_common
  66. {
  67. public:
  68. typedef void*(singleton_constructor_t)(ThreadSafeGlobalMap &);
  69. typedef void (singleton_destructor_t)(void *, ThreadSafeGlobalMap &);
  70. static const ::boost::uint32_t Uninitialized = 0u;
  71. static const ::boost::uint32_t Initializing = 1u;
  72. static const ::boost::uint32_t Initialized = 2u;
  73. static const ::boost::uint32_t Broken = 3u;
  74. static const ::boost::uint32_t Destroyed = 4u;
  75. //Initialize this_module_singleton_ptr, creates the global map if needed and also creates an unique
  76. //opaque type in global map through a singleton_constructor_t function call,
  77. //initializing the passed pointer to that unique instance.
  78. //
  79. //We have two concurrency types here. a)the global map/singleton creation must
  80. //be safe between threads of this process but in different modules/dlls. b)
  81. //the pointer to the singleton is per-module, so we have to protect this
  82. //initization between threads of the same module.
  83. //
  84. //All static variables declared here are shared between inside a module
  85. //so atomic operations will synchronize only threads of the same module.
  86. static void initialize_singleton_logic
  87. (void *&ptr, volatile boost::uint32_t &this_module_singleton_initialized, singleton_constructor_t constructor, bool phoenix)
  88. {
  89. //If current module is not initialized enter to lock free logic
  90. if(atomic_read32(&this_module_singleton_initialized) != Initialized){
  91. //Now a single thread of the module will succeed in this CAS.
  92. //trying to pass from Uninitialized to Initializing
  93. ::boost::uint32_t previous_module_singleton_initialized = atomic_cas32
  94. (&this_module_singleton_initialized, Initializing, Uninitialized);
  95. //If the thread succeeded the CAS (winner) it will compete with other
  96. //winner threads from other modules to create the global map
  97. if(previous_module_singleton_initialized == Destroyed){
  98. //Trying to resurrect a dead Phoenix singleton. Just try to
  99. //mark it as uninitialized and start again
  100. if(phoenix){
  101. atomic_cas32(&this_module_singleton_initialized, Uninitialized, Destroyed);
  102. previous_module_singleton_initialized = atomic_cas32
  103. (&this_module_singleton_initialized, Initializing, Uninitialized);
  104. }
  105. //Trying to resurrect a non-Phoenix dead singleton is an error
  106. else{
  107. throw interprocess_exception("Boost.Interprocess: Dead reference on non-Phoenix singleton of type");
  108. }
  109. }
  110. if(previous_module_singleton_initialized == Uninitialized){
  111. BOOST_INTERPROCESS_TRY{
  112. //Now initialize the global map, this function must solve concurrency
  113. //issues between threads of several modules
  114. initialize_global_map_handle();
  115. //Now try to create the singleton in global map.
  116. //This function solves concurrency issues
  117. //between threads of several modules
  118. ThreadSafeGlobalMap *const pmap = get_map_ptr();
  119. void *tmp = constructor(*pmap);
  120. //Increment the module reference count that reflects how many
  121. //singletons this module holds, so that we can safely destroy
  122. //module global map object when no singleton is left
  123. atomic_inc32(&this_module_singleton_count);
  124. //Insert a barrier before assigning the pointer to
  125. //make sure this assignment comes after the initialization
  126. atomic_write32(&this_module_singleton_initialized, Initializing);
  127. //Assign the singleton address to the module-local pointer
  128. ptr = tmp;
  129. //Memory barrier inserted, all previous operations should complete
  130. //before this one. Now marked as initialized
  131. atomic_write32(&this_module_singleton_initialized, Initialized);
  132. }
  133. BOOST_INTERPROCESS_CATCH(...){
  134. //Mark singleton failed to initialize
  135. atomic_write32(&this_module_singleton_initialized, Broken);
  136. BOOST_INTERPROCESS_RETHROW
  137. } BOOST_INTERPROCESS_CATCH_END
  138. }
  139. //If previous state was initializing, this means that another winner thread is
  140. //trying to initialize the singleton. Just wait until completes its work.
  141. else if(previous_module_singleton_initialized == Initializing){
  142. spin_wait swait;
  143. while(1){
  144. previous_module_singleton_initialized = atomic_read32(&this_module_singleton_initialized);
  145. if(previous_module_singleton_initialized >= Initialized){
  146. //Already initialized, or exception thrown by initializer thread
  147. break;
  148. }
  149. else if(previous_module_singleton_initialized == Initializing){
  150. swait.yield();
  151. }
  152. else{
  153. //This can't be happening!
  154. BOOST_ASSERT(0);
  155. }
  156. }
  157. }
  158. else if(previous_module_singleton_initialized == Initialized){
  159. //Nothing to do here, the singleton is ready
  160. }
  161. //If previous state was greater than initialized, then memory is broken
  162. //trying to initialize the singleton.
  163. else{//(previous_module_singleton_initialized > Initialized)
  164. throw interprocess_exception("boost::interprocess::intermodule_singleton initialization failed");
  165. }
  166. }
  167. BOOST_ASSERT(ptr != 0);
  168. }
  169. static void finalize_singleton_logic(void *&ptr, volatile boost::uint32_t &this_module_singleton_initialized, singleton_destructor_t destructor)
  170. {
  171. //Protect destruction against lazy singletons not initialized in this execution
  172. if(ptr){
  173. //Note: this destructor might provoke a Phoenix singleton
  174. //resurrection. This means that this_module_singleton_count
  175. //might change after this call.
  176. ThreadSafeGlobalMap * const pmap = get_map_ptr();
  177. destructor(ptr, *pmap);
  178. ptr = 0;
  179. //Memory barrier to make sure pointer is nulled.
  180. //Mark this singleton as destroyed.
  181. atomic_write32(&this_module_singleton_initialized, Destroyed);
  182. //If this is the last singleton of this module
  183. //apply map destruction.
  184. //Note: singletons are destroyed when the module is unloaded
  185. //so no threads should be executing or holding references
  186. //to this module
  187. if(1 == atomic_dec32(&this_module_singleton_count)){
  188. destroy_global_map_handle();
  189. }
  190. }
  191. }
  192. private:
  193. static ThreadSafeGlobalMap *get_map_ptr()
  194. {
  195. return static_cast<ThreadSafeGlobalMap *>(static_cast<void*>(mem_holder.map_mem));
  196. }
  197. static void initialize_global_map_handle()
  198. {
  199. //Obtain unique map name and size
  200. spin_wait swait;
  201. while(1){
  202. //Try to pass map state to initializing
  203. ::boost::uint32_t tmp = atomic_cas32(&this_module_map_initialized, Initializing, Uninitialized);
  204. if(tmp == Initialized || tmp == Broken){
  205. break;
  206. }
  207. else if(tmp == Destroyed){
  208. tmp = atomic_cas32(&this_module_map_initialized, Uninitialized, Destroyed);
  209. continue;
  210. }
  211. //If some other thread is doing the work wait
  212. else if(tmp == Initializing){
  213. swait.yield();
  214. }
  215. else{ //(tmp == Uninitialized)
  216. //If not initialized try it again?
  217. BOOST_INTERPROCESS_TRY{
  218. //Remove old global map from the system
  219. intermodule_singleton_helpers::thread_safe_global_map_dependant<ThreadSafeGlobalMap>::remove_old_gmem();
  220. //in-place construction of the global map class
  221. ThreadSafeGlobalMap * const pmap = get_map_ptr();
  222. intermodule_singleton_helpers::thread_safe_global_map_dependant
  223. <ThreadSafeGlobalMap>::construct_map(static_cast<void*>(pmap));
  224. //Use global map's internal lock to initialize the lock file
  225. //that will mark this gmem as "in use".
  226. typename intermodule_singleton_helpers::thread_safe_global_map_dependant<ThreadSafeGlobalMap>::
  227. lock_file_logic f(*pmap);
  228. //If function failed (maybe a competing process has erased the shared
  229. //memory between creation and file locking), retry with a new instance.
  230. if(f.retry()){
  231. pmap->~ThreadSafeGlobalMap();
  232. atomic_write32(&this_module_map_initialized, Destroyed);
  233. }
  234. else{
  235. //Locking succeeded, so this global map module-instance is ready
  236. atomic_write32(&this_module_map_initialized, Initialized);
  237. break;
  238. }
  239. }
  240. BOOST_INTERPROCESS_CATCH(...){
  241. //
  242. BOOST_INTERPROCESS_RETHROW
  243. } BOOST_INTERPROCESS_CATCH_END
  244. }
  245. }
  246. }
  247. static void destroy_global_map_handle()
  248. {
  249. if(!atomic_read32(&this_module_singleton_count)){
  250. //This module is being unloaded, so destroy
  251. //the global map object of this module
  252. //and unlink the global map if it's the last
  253. ThreadSafeGlobalMap * const pmap = get_map_ptr();
  254. typename intermodule_singleton_helpers::thread_safe_global_map_dependant<ThreadSafeGlobalMap>::
  255. unlink_map_logic f(*pmap);
  256. pmap->~ThreadSafeGlobalMap();
  257. atomic_write32(&this_module_map_initialized, Destroyed);
  258. //Do some cleanup for other processes old gmem instances
  259. intermodule_singleton_helpers::thread_safe_global_map_dependant<ThreadSafeGlobalMap>::remove_old_gmem();
  260. }
  261. }
  262. //Static data, zero-initalized without any dependencies
  263. //this_module_singleton_count is the number of singletons used by this module
  264. static volatile boost::uint32_t this_module_singleton_count;
  265. //this_module_map_initialized is the state of this module's map class object.
  266. //Values: Uninitialized, Initializing, Initialized, Broken
  267. static volatile boost::uint32_t this_module_map_initialized;
  268. //Raw memory to construct the global map manager
  269. static union mem_holder_t
  270. {
  271. unsigned char map_mem [sizeof(ThreadSafeGlobalMap)];
  272. ::boost::container::dtl::max_align_t aligner;
  273. } mem_holder;
  274. };
  275. template<class ThreadSafeGlobalMap>
  276. volatile boost::uint32_t intermodule_singleton_common<ThreadSafeGlobalMap>::this_module_singleton_count;
  277. template<class ThreadSafeGlobalMap>
  278. volatile boost::uint32_t intermodule_singleton_common<ThreadSafeGlobalMap>::this_module_map_initialized;
  279. template<class ThreadSafeGlobalMap>
  280. typename intermodule_singleton_common<ThreadSafeGlobalMap>::mem_holder_t
  281. intermodule_singleton_common<ThreadSafeGlobalMap>::mem_holder;
  282. //A reference count to be stored in global map holding the number
  283. //of singletons (one per module) attached to the instance pointed by
  284. //the internal ptr.
  285. struct ref_count_ptr
  286. {
  287. ref_count_ptr(void *p, boost::uint32_t count)
  288. : ptr(p), singleton_ref_count(count)
  289. {}
  290. void *ptr;
  291. //This reference count serves to count the number of attached
  292. //modules to this singleton
  293. volatile boost::uint32_t singleton_ref_count;
  294. };
  295. //Now this class is a singleton, initializing the singleton in
  296. //the first get() function call if LazyInit is true. If false
  297. //then the singleton will be initialized when loading the module.
  298. template<typename C, bool LazyInit, bool Phoenix, class ThreadSafeGlobalMap>
  299. class intermodule_singleton_impl
  300. {
  301. public:
  302. static C& get() //Let's make inlining easy
  303. {
  304. if(!this_module_singleton_ptr){
  305. if(lifetime.dummy_function()){ //This forces lifetime instantiation, for reference counted destruction
  306. atentry_work();
  307. }
  308. }
  309. return *static_cast<C*>(this_module_singleton_ptr);
  310. }
  311. private:
  312. static void atentry_work()
  313. {
  314. intermodule_singleton_common<ThreadSafeGlobalMap>::initialize_singleton_logic
  315. (this_module_singleton_ptr, this_module_singleton_initialized, singleton_constructor, Phoenix);
  316. }
  317. static void atexit_work()
  318. {
  319. intermodule_singleton_common<ThreadSafeGlobalMap>::finalize_singleton_logic
  320. (this_module_singleton_ptr, this_module_singleton_initialized, singleton_destructor);
  321. }
  322. //These statics will be zero-initialized without any constructor call dependency
  323. //this_module_singleton_ptr will be a module-local pointer to the singleton
  324. static void* this_module_singleton_ptr;
  325. //this_module_singleton_count will be used to synchronize threads of the same module
  326. //for access to a singleton instance, and to flag the state of the
  327. //singleton.
  328. static volatile boost::uint32_t this_module_singleton_initialized;
  329. //This class destructor will trigger singleton destruction
  330. struct lifetime_type_lazy
  331. {
  332. bool dummy_function()
  333. { return m_dummy == 0; }
  334. ~lifetime_type_lazy()
  335. {
  336. //if(!Phoenix){
  337. //atexit_work();
  338. //}
  339. }
  340. //Dummy volatile so that the compiler can't resolve its value at compile-time
  341. //and can't avoid lifetime_type instantiation if dummy_function() is called.
  342. static volatile int m_dummy;
  343. };
  344. struct lifetime_type_static
  345. : public lifetime_type_lazy
  346. {
  347. lifetime_type_static()
  348. { atentry_work(); }
  349. };
  350. typedef typename if_c
  351. <LazyInit, lifetime_type_lazy, lifetime_type_static>::type lifetime_type;
  352. static lifetime_type lifetime;
  353. //A functor to be executed inside global map lock that just
  354. //searches for the singleton in map and if not present creates a new one.
  355. //If singleton constructor throws, the exception is propagated
  356. struct init_atomic_func
  357. {
  358. init_atomic_func(ThreadSafeGlobalMap &m)
  359. : m_map(m), ret_ptr()
  360. {}
  361. void operator()()
  362. {
  363. ref_count_ptr *rcount = intermodule_singleton_helpers::thread_safe_global_map_dependant
  364. <ThreadSafeGlobalMap>::find(m_map, typeid(C).name());
  365. if(!rcount){
  366. C *p = new C;
  367. BOOST_INTERPROCESS_TRY{
  368. ref_count_ptr val(p, 0u);
  369. rcount = intermodule_singleton_helpers::thread_safe_global_map_dependant
  370. <ThreadSafeGlobalMap>::insert(m_map, typeid(C).name(), val);
  371. }
  372. BOOST_INTERPROCESS_CATCH(...){
  373. intermodule_singleton_helpers::thread_safe_global_map_dependant
  374. <ThreadSafeGlobalMap>::erase(m_map, typeid(C).name());
  375. delete p;
  376. BOOST_INTERPROCESS_RETHROW
  377. } BOOST_INTERPROCESS_CATCH_END
  378. }
  379. //if(Phoenix){
  380. BOOST_INTERPROCESS_ATEXIT(&atexit_work);
  381. //}
  382. atomic_inc32(&rcount->singleton_ref_count);
  383. ret_ptr = rcount->ptr;
  384. }
  385. void *data() const
  386. { return ret_ptr; }
  387. private:
  388. ThreadSafeGlobalMap &m_map;
  389. void *ret_ptr;
  390. };
  391. //A functor to be executed inside global map lock that just
  392. //deletes the singleton in map if the attached count reaches to zero
  393. struct fini_atomic_func
  394. {
  395. fini_atomic_func(ThreadSafeGlobalMap &m)
  396. : m_map(m)
  397. {}
  398. void operator()()
  399. {
  400. ref_count_ptr *rcount = intermodule_singleton_helpers::thread_safe_global_map_dependant
  401. <ThreadSafeGlobalMap>::find(m_map, typeid(C).name());
  402. //The object must exist
  403. BOOST_ASSERT(rcount);
  404. BOOST_ASSERT(rcount->singleton_ref_count > 0);
  405. //Check if last reference
  406. if(atomic_dec32(&rcount->singleton_ref_count) == 1){
  407. //If last, destroy the object
  408. BOOST_ASSERT(rcount->ptr != 0);
  409. C *pc = static_cast<C*>(rcount->ptr);
  410. //Now destroy map entry
  411. bool destroyed = intermodule_singleton_helpers::thread_safe_global_map_dependant
  412. <ThreadSafeGlobalMap>::erase(m_map, typeid(C).name());
  413. (void)destroyed; BOOST_ASSERT(destroyed == true);
  414. delete pc;
  415. }
  416. }
  417. private:
  418. ThreadSafeGlobalMap &m_map;
  419. };
  420. //A wrapper to execute init_atomic_func
  421. static void *singleton_constructor(ThreadSafeGlobalMap &map)
  422. {
  423. init_atomic_func f(map);
  424. intermodule_singleton_helpers::thread_safe_global_map_dependant
  425. <ThreadSafeGlobalMap>::atomic_func(map, f);
  426. return f.data();
  427. }
  428. //A wrapper to execute fini_atomic_func
  429. static void singleton_destructor(void *p, ThreadSafeGlobalMap &map)
  430. { (void)p;
  431. fini_atomic_func f(map);
  432. intermodule_singleton_helpers::thread_safe_global_map_dependant
  433. <ThreadSafeGlobalMap>::atomic_func(map, f);
  434. }
  435. };
  436. template <typename C, bool L, bool P, class ThreadSafeGlobalMap>
  437. volatile int intermodule_singleton_impl<C, L, P, ThreadSafeGlobalMap>::lifetime_type_lazy::m_dummy = 0;
  438. //These will be zero-initialized by the loader
  439. template <typename C, bool L, bool P, class ThreadSafeGlobalMap>
  440. void *intermodule_singleton_impl<C, L, P, ThreadSafeGlobalMap>::this_module_singleton_ptr = 0;
  441. template <typename C, bool L, bool P, class ThreadSafeGlobalMap>
  442. volatile boost::uint32_t intermodule_singleton_impl<C, L, P, ThreadSafeGlobalMap>::this_module_singleton_initialized = 0;
  443. template <typename C, bool L, bool P, class ThreadSafeGlobalMap>
  444. typename intermodule_singleton_impl<C, L, P, ThreadSafeGlobalMap>::lifetime_type
  445. intermodule_singleton_impl<C, L, P, ThreadSafeGlobalMap>::lifetime;
  446. } //namespace ipcdetail{
  447. } //namespace interprocess{
  448. } //namespace boost{
  449. #include <boost/interprocess/detail/config_end.hpp>
  450. #endif //#ifndef BOOST_INTERPROCESS_INTERMODULE_SINGLETON_COMMON_HPP