1 //////////////////////////////////////////////////////////////////////////////
3 // (C) Copyright Ion Gaztanaga 2006-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)
7 // See http://www.boost.org/libs/interprocess for documentation.
9 //////////////////////////////////////////////////////////////////////////////
11 #ifndef BOOST_INTERPROCESS_MANAGED_OPEN_OR_CREATE_IMPL
12 #define BOOST_INTERPROCESS_MANAGED_OPEN_OR_CREATE_IMPL
14 #ifndef BOOST_CONFIG_HPP
15 # include <boost/config.hpp>
18 #if defined(BOOST_HAS_PRAGMA_ONCE)
22 #include <boost/interprocess/detail/config_begin.hpp>
23 #include <boost/interprocess/detail/os_thread_functions.hpp>
24 #include <boost/interprocess/detail/os_file_functions.hpp>
25 #include <boost/interprocess/creation_tags.hpp>
26 #include <boost/interprocess/mapped_region.hpp>
27 #include <boost/interprocess/detail/utilities.hpp>
28 #include <boost/interprocess/detail/type_traits.hpp>
29 #include <boost/interprocess/detail/atomic.hpp>
30 #include <boost/interprocess/detail/interprocess_tester.hpp>
31 #include <boost/interprocess/creation_tags.hpp>
32 #include <boost/interprocess/detail/mpl.hpp>
33 #include <boost/interprocess/permissions.hpp>
34 #include <boost/container/detail/type_traits.hpp> //alignment_of, aligned_storage
35 #include <boost/interprocess/sync/spin/wait.hpp>
36 #include <boost/interprocess/detail/timed_utils.hpp>
37 #include <boost/move/move.hpp>
38 #include <boost/cstdint.hpp>
41 namespace interprocess {
44 template <bool StoreDevice, class DeviceAbstraction>
45 class managed_open_or_create_impl_device_holder
48 DeviceAbstraction &get_device()
49 { static DeviceAbstraction dev; return dev; }
51 const DeviceAbstraction &get_device() const
52 { static DeviceAbstraction dev; return dev; }
55 template <class DeviceAbstraction>
56 class managed_open_or_create_impl_device_holder<true, DeviceAbstraction>
59 DeviceAbstraction &get_device()
62 const DeviceAbstraction &get_device() const
66 DeviceAbstraction dev;
69 template<class DeviceAbstraction, std::size_t MemAlignment, bool FileBased, bool StoreDevice>
70 class managed_open_or_create_impl
71 : public managed_open_or_create_impl_device_holder<StoreDevice, DeviceAbstraction>
74 BOOST_MOVABLE_BUT_NOT_COPYABLE(managed_open_or_create_impl)
75 typedef bool_<FileBased> file_like_t;
77 static const unsigned MaxCreateOrOpenTries = BOOST_INTERPROCESS_MANAGED_OPEN_OR_CREATE_INITIALIZE_MAX_TRIES;
78 static const unsigned MaxInitializeTimeSec = BOOST_INTERPROCESS_MANAGED_OPEN_OR_CREATE_INITIALIZE_TIMEOUT_SEC;
80 typedef managed_open_or_create_impl_device_holder<StoreDevice, DeviceAbstraction> DevHolder;
89 static const std::size_t RequiredAlignment =
90 MemAlignment ? MemAlignment
91 : boost::container::dtl::alignment_of< boost::container::dtl::max_align_t >::value
95 static const std::size_t ManagedOpenOrCreateUserOffset =
96 ct_rounded_size<sizeof(boost::uint32_t), RequiredAlignment>::value;
98 managed_open_or_create_impl()
101 template <class DeviceId>
102 managed_open_or_create_impl(create_only_t,
107 const permissions &perm)
116 , null_mapped_region_function());
119 template <class DeviceId>
120 managed_open_or_create_impl(open_only_t,
132 , null_mapped_region_function());
135 template <class DeviceId>
136 managed_open_or_create_impl(open_or_create_t,
141 const permissions &perm)
150 , null_mapped_region_function());
153 template <class DeviceId, class ConstructFunc>
154 managed_open_or_create_impl(create_only_t,
159 const ConstructFunc &construct_func,
160 const permissions &perm)
172 template <class DeviceId, class ConstructFunc>
173 managed_open_or_create_impl(open_only_t,
177 const ConstructFunc &construct_func)
189 template <class DeviceId, class ConstructFunc>
190 managed_open_or_create_impl(open_or_create_t,
195 const ConstructFunc &construct_func,
196 const permissions &perm)
208 managed_open_or_create_impl(BOOST_RV_REF(managed_open_or_create_impl) moved)
209 { this->swap(moved); }
211 managed_open_or_create_impl &operator=(BOOST_RV_REF(managed_open_or_create_impl) moved)
213 managed_open_or_create_impl tmp(boost::move(moved));
218 ~managed_open_or_create_impl()
221 std::size_t get_user_size() const
222 { return m_mapped_region.get_size() - ManagedOpenOrCreateUserOffset; }
224 void *get_user_address() const
225 { return static_cast<char*>(m_mapped_region.get_address()) + ManagedOpenOrCreateUserOffset; }
227 std::size_t get_real_size() const
228 { return m_mapped_region.get_size(); }
230 void *get_real_address() const
231 { return m_mapped_region.get_address(); }
233 void swap(managed_open_or_create_impl &other)
235 this->m_mapped_region.swap(other.m_mapped_region);
239 { return m_mapped_region.flush(); }
241 const mapped_region &get_mapped_region() const
242 { return m_mapped_region; }
244 DeviceAbstraction &get_device()
245 { return this->DevHolder::get_device(); }
247 const DeviceAbstraction &get_device() const
248 { return this->DevHolder::get_device(); }
252 //These are templatized to allow explicit instantiations
254 static void truncate_device(DeviceAbstraction &, offset_t, false_)
258 static void truncate_device(DeviceAbstraction &dev, offset_t size, true_)
259 { dev.truncate(size); }
263 static bool check_offset_t_size(std::size_t , false_)
264 { return true; } //Empty
267 static bool check_offset_t_size(std::size_t size, true_)
268 { return size == std::size_t(offset_t(size)); }
270 //These are templatized to allow explicit instantiations
271 template<bool dummy, class DeviceId>
272 static void create_device(DeviceAbstraction &dev, const DeviceId & id, std::size_t size, const permissions &perm, false_ /*file_like*/)
274 DeviceAbstraction tmp(create_only, id, read_write, size, perm);
278 template<bool dummy, class DeviceId>
279 static void create_device(DeviceAbstraction &dev, const DeviceId & id, std::size_t, const permissions &perm, true_ /*file_like*/)
281 DeviceAbstraction tmp(create_only, id, read_write, perm);
285 template <class DeviceId>
286 static bool do_create_else_open(DeviceAbstraction &dev, const DeviceId & id, std::size_t size, const permissions &perm)
288 //This loop is very ugly, but brute force is sometimes better
289 //than diplomacy. In POSIX file-based resources we can' know if we
290 //effectively created the file or not (there is no ERROR_ALREADY_EXISTS equivalent),
291 //so we try to create exclusively and fallback to open if already exists, with
292 //some retries if opening also fails because the file does not exist
293 //(there is a race, the creator just removed the file after creating it).
295 //We'll put a maximum retry limit just to avoid possible deadlocks, we don't
296 //want to support pathological use cases.
301 create_device<FileBased>(dev, id, size, perm, file_like_t());
304 BOOST_CATCH(interprocess_exception &ex){
305 #ifndef BOOST_NO_EXCEPTIONS
306 if(ex.get_error_code() != already_exists_error){
309 else if (++tries == MaxCreateOrOpenTries) {
310 //File existing when trying to create, but non-existing when
311 //trying to open, and tried MaxCreateOrOpenTries times. Something fishy
312 //is happening here and we can't solve it
313 throw interprocess_exception(error_info(corrupted_error));
317 DeviceAbstraction tmp(open_only, id, read_write);
321 BOOST_CATCH(interprocess_exception &e){
322 if(e.get_error_code() != not_found_error){
330 #endif //#ifndef BOOST_NO_EXCEPTIONS
340 template <class ConstructFunc>
341 static void do_map_after_create
342 (DeviceAbstraction &dev, mapped_region &final_region,
343 std::size_t size, const void *addr, ConstructFunc construct_func)
346 //If this throws, we are lost
347 truncate_device<FileBased>(dev, static_cast<offset_t>(size), file_like_t());
349 //If the following throws, we will truncate the file to 1
350 mapped_region region(dev, read_write, 0, 0, addr);
351 boost::uint32_t *patomic_word = 0; //avoid gcc warning
352 patomic_word = static_cast<boost::uint32_t*>(region.get_address());
353 boost::uint32_t previous = atomic_cas32(patomic_word, InitializingSegment, UninitializedSegment);
355 if(previous == UninitializedSegment){
357 construct_func( static_cast<char*>(region.get_address()) + ManagedOpenOrCreateUserOffset
358 , size - ManagedOpenOrCreateUserOffset, true);
359 //All ok, just move resources to the external mapped region
360 final_region.swap(region);
363 atomic_write32(patomic_word, CorruptedSegment);
366 atomic_write32(patomic_word, InitializedSegment);
369 atomic_write32(patomic_word, CorruptedSegment);
370 throw interprocess_exception(error_info(corrupted_error));
375 truncate_device<FileBased>(dev, 1u, file_like_t());
385 template <class ConstructFunc>
386 static void do_map_after_open
387 ( DeviceAbstraction &dev, mapped_region &final_region
388 , const void *addr, ConstructFunc construct_func
389 , bool ronly, bool cow)
391 const usduration TimeoutSec(usduration_seconds(MaxInitializeTimeSec));
394 offset_t filesize = 0;
397 //If a file device was used, the creator might be truncating the device, so wait
398 //until the file size is enough to map the initial word
399 ustime ustime_start = microsec_clock<ustime>::universal_time();
402 if(!get_file_size(file_handle_from_mapping_handle(dev.get_mapping_handle()), filesize)){
403 error_info err = system_error_code();
404 throw interprocess_exception(err);
409 //More than MaxZeroTruncateTimeSec seconds waiting to the creator
410 //to minimally increase the size of the file: something bad has happened
411 const usduration elapsed(microsec_clock<ustime>::universal_time() - ustime_start);
412 if (elapsed > TimeoutSec){
413 throw interprocess_exception(error_info(corrupted_error));
418 //The creator detected an error creating the file and signalled it with size 1
420 throw interprocess_exception(error_info(corrupted_error));
424 mapped_region region(dev, ronly ? read_only : (cow ? copy_on_write : read_write), 0, 0, addr);
426 boost::uint32_t *patomic_word = static_cast<boost::uint32_t*>(region.get_address());
427 boost::uint32_t value = atomic_read32(patomic_word);
429 if (value != InitializedSegment){
430 ustime ustime_start = microsec_clock<ustime>::universal_time();
432 while ((value = atomic_read32(patomic_word)) != InitializedSegment){
433 if(value == CorruptedSegment){
434 throw interprocess_exception(error_info(corrupted_error));
436 //More than MaxZeroTruncateTimeSec seconds waiting to the creator
437 //to minimally increase the size of the file: something bad has happened
438 const usduration elapsed(microsec_clock<ustime>::universal_time() - ustime_start);
439 if (elapsed > TimeoutSec){
440 throw interprocess_exception(error_info(corrupted_error));
444 //The size of the file might have grown while Uninitialized -> Initializing, so remap
446 mapped_region null_map;
447 region.swap(null_map);
449 mapped_region final_size_map(dev, ronly ? read_only : (cow ? copy_on_write : read_write), 0, 0, addr);
450 final_size_map.swap(region);
452 construct_func( static_cast<char*>(region.get_address()) + ManagedOpenOrCreateUserOffset
453 , region.get_size() - ManagedOpenOrCreateUserOffset
455 //All ok, just move resources to the external mapped region
456 final_region.swap(region);
459 template <class DeviceId, class ConstructFunc> inline
460 void priv_open_or_create
464 mode_t mode, const void *addr,
465 const permissions &perm,
466 ConstructFunc construct_func)
469 //Check if the requested size is enough to build the managed metadata
470 const std::size_t func_min_size = construct_func.get_min_size();
471 if( (std::size_t(-1) - ManagedOpenOrCreateUserOffset) < func_min_size ||
472 size < (func_min_size + ManagedOpenOrCreateUserOffset) ){
473 throw interprocess_exception(error_info(size_error));
475 //Check size can be represented by offset_t (used by truncate)
476 if (!check_offset_t_size<FileBased>(size, file_like_t())){
477 throw interprocess_exception(error_info(size_error));
481 //Now create the device (file, shm file, etc.)
482 DeviceAbstraction dev;
484 bool created = false;
488 DeviceAbstraction tmp(open_only, id, mode == read_write ? read_write : read_only);
490 ronly = mode == read_only;
491 cow = mode == copy_on_write;
493 else if(type == DoCreate){
494 create_device<FileBased>(dev, id, size, perm, file_like_t());
497 else { //DoOpenOrCreate
498 created = this->do_create_else_open(dev, id, size, perm);
502 this->do_map_after_create(dev, m_mapped_region, size, addr, construct_func);
505 this->do_map_after_open(dev, m_mapped_region, addr, construct_func, ronly, cow);
509 this->DevHolder::get_device() = boost::move(dev);
513 friend void swap(managed_open_or_create_impl &left, managed_open_or_create_impl &right)
519 friend class interprocess_tester;
520 void dont_close_on_destruction()
521 { interprocess_tester::dont_close_on_destruction(m_mapped_region); }
523 mapped_region m_mapped_region;
526 } //namespace ipcdetail {
528 } //namespace interprocess {
529 } //namespace boost {
531 #include <boost/interprocess/detail/config_end.hpp>
533 #endif //#ifndef BOOST_INTERPROCESS_MANAGED_OPEN_OR_CREATE_IMPL