intermodule_singleton_common.hpp 19 KB

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