1 //////////////////////////////////////////////////////////////////////////////
2 //
3 // (C) Copyright Ion Gaztanaga 2005-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 
11 #ifndef BOOST_INTERPROCESS_MAPPED_REGION_HPP
12 #define BOOST_INTERPROCESS_MAPPED_REGION_HPP
13 
14 #ifndef BOOST_CONFIG_HPP
15 #  include <boost/config.hpp>
16 #endif
17 #
18 #if defined(BOOST_HAS_PRAGMA_ONCE)
19 #  pragma once
20 #endif
21 
22 #include <boost/interprocess/detail/config_begin.hpp>
23 #include <boost/interprocess/detail/workaround.hpp>
24 
25 #include <boost/interprocess/interprocess_fwd.hpp>
26 #include <boost/interprocess/exceptions.hpp>
27 #include <boost/move/utility_core.hpp>
28 #include <boost/interprocess/detail/utilities.hpp>
29 #include <boost/interprocess/detail/os_file_functions.hpp>
30 #include <string>
31 #include <boost/cstdint.hpp>
32 #include <boost/assert.hpp>
33 #include <boost/move/adl_move_swap.hpp>
34 
35 //Some Unixes use caddr_t instead of void * in madvise
36 //              SunOS                                 Tru64                               HP-UX                    AIX
37 #if defined(sun) || defined(__sun) || defined(__osf__) || defined(__osf) || defined(_hpux) || defined(hpux) || defined(_AIX)
38 #define BOOST_INTERPROCESS_MADVISE_USES_CADDR_T
39 #include <sys/types.h>
40 #endif
41 
42 //A lot of UNIXes have destructive semantics for MADV_DONTNEED, so
43 //we need to be careful to allow it.
44 #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
45 #define BOOST_INTERPROCESS_MADV_DONTNEED_HAS_NONDESTRUCTIVE_SEMANTICS
46 #endif
47 
48 #if defined (BOOST_INTERPROCESS_WINDOWS)
49 #  include <boost/interprocess/detail/win32_api.hpp>
50 #else
51 #  ifdef BOOST_HAS_UNISTD_H
52 #    include <fcntl.h>
53 #    include <sys/mman.h>     //mmap
54 #    include <unistd.h>
55 #    include <sys/stat.h>
56 #    include <sys/types.h>
57 #    if defined(BOOST_INTERPROCESS_XSI_SHARED_MEMORY_OBJECTS)
58 #      include <sys/shm.h>      //System V shared memory...
59 #    endif
60 #    include <boost/assert.hpp>
61 #  else
62 #    error Unknown platform
63 #  endif
64 
65 #endif   //#if defined (BOOST_INTERPROCESS_WINDOWS)
66 
67 //!\file
68 //!Describes mapped region class
69 
70 namespace boost {
71 namespace interprocess {
72 
73 #if !defined(BOOST_INTERPROCESS_DOXYGEN_INVOKED)
74 
75 //Solaris declares madvise only in some configurations but defines MADV_XXX, a bit confusing.
76 //Predeclare it here to avoid any compilation error
77 #if (defined(sun) || defined(__sun)) && defined(MADV_NORMAL)
78 extern "C" int madvise(caddr_t, size_t, int);
79 #endif
80 
81 namespace ipcdetail{ class interprocess_tester; }
82 namespace ipcdetail{ class raw_mapped_region_creator; }
83 
84 #endif   //#ifndef BOOST_INTERPROCESS_DOXYGEN_INVOKED
85 
86 //!The mapped_region class represents a portion or region created from a
87 //!memory_mappable object.
88 //!
89 //!The OS can map a region bigger than the requested one, as region must
90 //!be multiple of the page size, but mapped_region will always refer to
91 //!the region specified by the user.
92 class mapped_region
93 {
94    #if !defined(BOOST_INTERPROCESS_DOXYGEN_INVOKED)
95    //Non-copyable
96    BOOST_MOVABLE_BUT_NOT_COPYABLE(mapped_region)
97    #endif   //#ifndef BOOST_INTERPROCESS_DOXYGEN_INVOKED
98 
99    public:
100 
101    //!Creates a mapping region of the mapped memory "mapping", starting in
102    //!offset "offset", and the mapping's size will be "size". The mapping
103    //!can be opened for read only, read-write or copy-on-write.
104    //!
105    //!If an address is specified, both the offset and the address must be
106    //!multiples of the page size.
107    //!
108    //!The map is created using "default_map_options". This flag is OS
109    //!dependant and it should not be changed unless the user needs to
110    //!specify special options.
111    //!
112    //!In Windows systems "map_options" is a DWORD value passed as
113    //!"dwDesiredAccess" to "MapViewOfFileEx". If "default_map_options" is passed
114    //!it's initialized to zero. "map_options" is XORed with FILE_MAP_[COPY|READ|WRITE].
115    //!
116    //!In UNIX systems and POSIX mappings "map_options" is an int value passed as "flags"
117    //!to "mmap". If "default_map_options" is specified it's initialized to MAP_NOSYNC
118    //!if that option exists and to zero otherwise. "map_options" XORed with MAP_PRIVATE or MAP_SHARED.
119    //!
120    //!In UNIX systems and XSI mappings "map_options" is an int value passed as "shmflg"
121    //!to "shmat". If "default_map_options" is specified it's initialized to zero.
122    //!"map_options" is XORed with SHM_RDONLY if needed.
123    //!
124    //!The OS could allocate more pages than size/page_size(), but get_address()
125    //!will always return the address passed in this function (if not null) and
126    //!get_size() will return the specified size.
127    template<class MemoryMappable>
128    mapped_region(const MemoryMappable& mapping
129                 ,mode_t mode
130                 ,offset_t offset = 0
131                 ,std::size_t size = 0
132                 ,const void *address = 0
133                 ,map_options_t map_options = default_map_options);
134 
135    //!Default constructor. Address will be 0 (nullptr).
136    //!Size will be 0.
137    //!Does not throw
138    mapped_region() BOOST_NOEXCEPT;
139 
140    //!Move constructor. *this will be constructed taking ownership of "other"'s
141    //!region and "other" will be left in default constructor state.
mapped_region(BOOST_RV_REF (mapped_region)other)142    mapped_region(BOOST_RV_REF(mapped_region) other)  BOOST_NOEXCEPT
143    #if defined (BOOST_INTERPROCESS_WINDOWS)
144    :  m_base(0), m_size(0)
145    ,  m_page_offset(0)
146    ,  m_mode(read_only)
147    ,  m_file_or_mapping_hnd(ipcdetail::invalid_file())
148    #else
149    :  m_base(0), m_size(0), m_page_offset(0), m_mode(read_only), m_is_xsi(false)
150    #endif
151    {  this->swap(other);   }
152 
153    //!Destroys the mapped region.
154    //!Does not throw
155    ~mapped_region();
156 
157    //!Move assignment. If *this owns a memory mapped region, it will be
158    //!destroyed and it will take ownership of "other"'s memory mapped region.
operator =(BOOST_RV_REF (mapped_region)other)159    mapped_region &operator=(BOOST_RV_REF(mapped_region) other) BOOST_NOEXCEPT
160    {
161       mapped_region tmp(boost::move(other));
162       this->swap(tmp);
163       return *this;
164    }
165 
166    //!Swaps the mapped_region with another
167    //!mapped region
168    void swap(mapped_region &other) BOOST_NOEXCEPT;
169 
170    //!Returns the size of the mapping. Never throws.
171    std::size_t get_size() const BOOST_NOEXCEPT;
172 
173    //!Returns the base address of the mapping.
174    //!Never throws.
175    void*       get_address() const BOOST_NOEXCEPT;
176 
177    //!Returns the mode of the mapping used to construct the mapped region.
178    //!Never throws.
179    mode_t get_mode() const BOOST_NOEXCEPT;
180 
181    //!Flushes to the disk a byte range within the mapped memory.
182    //!If 'async' is true, the function will return before flushing operation is completed
183    //!If 'async' is false, function will return once data has been written into the underlying
184    //!device (i.e., in mapped files OS cached information is written to disk).
185    //!Never throws. Returns false if operation could not be performed.
186    bool flush(std::size_t mapping_offset = 0, std::size_t numbytes = 0, bool async = true);
187 
188    //!Shrinks current mapped region. If after shrinking there is no longer need for a previously
189    //!mapped memory page, accessing that page can trigger a segmentation fault.
190    //!Depending on the OS, this operation might fail (XSI shared memory), it can decommit storage
191    //!and free a portion of the virtual address space (e.g.POSIX) or this
192    //!function can release some physical memory without freeing any virtual address space(Windows).
193    //!Returns true on success. Never throws.
194    bool shrink_by(std::size_t bytes, bool from_back = true);
195 
196    //!This enum specifies region usage behaviors that an application can specify
197    //!to the mapped region implementation.
198    enum advice_types{
199       //!Specifies that the application has no advice to give on its behavior with respect to
200       //!the region. It is the default characteristic if no advice is given for a range of memory.
201       advice_normal,
202       //!Specifies that the application expects to access the region sequentially from
203       //!lower addresses to higher addresses. The implementation can lower the priority of
204       //!preceding pages within the region once a page have been accessed.
205       advice_sequential,
206       //!Specifies that the application expects to access the region in a random order,
207       //!and prefetching is likely not advantageous.
208       advice_random,
209       //!Specifies that the application expects to access the region in the near future.
210       //!The implementation can prefetch pages of the region.
211       advice_willneed,
212       //!Specifies that the application expects that it will not access the region in the near future.
213       //!The implementation can unload pages within the range to save system resources.
214       advice_dontneed
215    };
216 
217    //!Advises the implementation on the expected behavior of the application with respect to the data
218    //!in the region. The implementation may use this information to optimize handling of the region data.
219    //!This function has no effect on the semantics of access to memory in the region, although it may affect
220    //!the performance of access.
221    //!If the advise type is not known to the implementation, the function returns false. True otherwise.
222    bool advise(advice_types advise);
223 
224    //!Returns the size of the page. This size is the minimum memory that
225    //!will be used by the system when mapping a memory mappable source and
226    //!will restrict the address and the offset to map.
227    static std::size_t get_page_size() BOOST_NOEXCEPT;
228 
229    #if !defined(BOOST_INTERPROCESS_DOXYGEN_INVOKED)
230    private:
231    //!Closes a previously opened memory mapping. Never throws
232    void priv_close();
233 
234    void* priv_map_address()  const;
235    std::size_t priv_map_size()  const;
236    bool priv_flush_param_check(std::size_t mapping_offset, void *&addr, std::size_t &numbytes) const;
237    bool priv_shrink_param_check(std::size_t bytes, bool from_back, void *&shrink_page_start, std::size_t &shrink_page_bytes);
238    static void priv_size_from_mapping_size
239       (offset_t mapping_size, offset_t offset, offset_t page_offset, std::size_t &size);
240    static offset_t priv_page_offset_addr_fixup(offset_t page_offset, const void *&addr);
241 
242    template<int dummy>
243    struct page_size_holder
244    {
245       static const std::size_t PageSize;
246       static std::size_t get_page_size();
247    };
248 
249    void*             m_base;
250    std::size_t       m_size;
251    std::size_t       m_page_offset;
252    mode_t            m_mode;
253    #if defined(BOOST_INTERPROCESS_WINDOWS)
254    file_handle_t     m_file_or_mapping_hnd;
255    #else
256    bool              m_is_xsi;
257    #endif
258 
259    friend class ipcdetail::interprocess_tester;
260    friend class ipcdetail::raw_mapped_region_creator;
261    void dont_close_on_destruction();
262    #if defined(BOOST_INTERPROCESS_WINDOWS) && !defined(BOOST_INTERPROCESS_FORCE_GENERIC_EMULATION)
263    template<int Dummy>
264    static void destroy_syncs_in_range(const void *addr, std::size_t size);
265    #endif
266    #endif   //#ifndef BOOST_INTERPROCESS_DOXYGEN_INVOKED
267 };
268 
269 #if !defined(BOOST_INTERPROCESS_DOXYGEN_INVOKED)
270 
swap(mapped_region & x,mapped_region & y)271 inline void swap(mapped_region &x, mapped_region &y) BOOST_NOEXCEPT
272 {  x.swap(y);  }
273 
~mapped_region()274 inline mapped_region::~mapped_region()
275 {  this->priv_close(); }
276 
get_size() const277 inline std::size_t mapped_region::get_size() const BOOST_NOEXCEPT
278 {  return m_size; }
279 
get_mode() const280 inline mode_t mapped_region::get_mode() const BOOST_NOEXCEPT
281 {  return m_mode;   }
282 
get_address() const283 inline void*    mapped_region::get_address() const BOOST_NOEXCEPT
284 {  return m_base; }
285 
priv_map_address() const286 inline void*    mapped_region::priv_map_address()  const
287 {  return static_cast<char*>(m_base) - m_page_offset; }
288 
priv_map_size() const289 inline std::size_t mapped_region::priv_map_size()  const
290 {  return m_size + m_page_offset; }
291 
priv_flush_param_check(std::size_t mapping_offset,void * & addr,std::size_t & numbytes) const292 inline bool mapped_region::priv_flush_param_check
293    (std::size_t mapping_offset, void *&addr, std::size_t &numbytes) const
294 {
295    //Check some errors
296    if(m_base == 0)
297       return false;
298 
299    if(mapping_offset >= m_size || numbytes > (m_size - size_t(mapping_offset))){
300       return false;
301    }
302 
303    //Update flush size if the user does not provide it
304    if(numbytes == 0){
305       numbytes = m_size - mapping_offset;
306    }
307    addr = (char*)this->priv_map_address() + mapping_offset;
308    numbytes += m_page_offset;
309    return true;
310 }
311 
priv_shrink_param_check(std::size_t bytes,bool from_back,void * & shrink_page_start,std::size_t & shrink_page_bytes)312 inline bool mapped_region::priv_shrink_param_check
313    (std::size_t bytes, bool from_back, void *&shrink_page_start, std::size_t &shrink_page_bytes)
314 {
315    //Check some errors
316    if(m_base == 0 || bytes > m_size){
317       return false;
318    }
319    else if(bytes == m_size){
320       this->priv_close();
321       return true;
322    }
323    else{
324       const std::size_t page_size = mapped_region::get_page_size();
325       if(from_back){
326          const std::size_t new_pages = (m_size + m_page_offset - bytes - 1)/page_size + 1;
327          shrink_page_start = static_cast<char*>(this->priv_map_address()) + new_pages*page_size;
328          shrink_page_bytes = m_page_offset + m_size - new_pages*page_size;
329          m_size -= bytes;
330       }
331       else{
332          shrink_page_start = this->priv_map_address();
333          m_page_offset += bytes;
334          shrink_page_bytes = (m_page_offset/page_size)*page_size;
335          m_page_offset = m_page_offset % page_size;
336          m_size -= bytes;
337          m_base  = static_cast<char *>(m_base) + bytes;
338          BOOST_ASSERT(shrink_page_bytes%page_size == 0);
339       }
340       return true;
341    }
342 }
343 
priv_size_from_mapping_size(offset_t mapping_size,offset_t offset,offset_t page_offset,std::size_t & size)344 inline void mapped_region::priv_size_from_mapping_size
345    (offset_t mapping_size, offset_t offset, offset_t page_offset, std::size_t &size)
346 {
347    //Check if mapping size fits in the user address space
348    //as offset_t is the maximum file size and it's signed.
349    if(mapping_size < offset ||
350       boost::uintmax_t(mapping_size - (offset - page_offset)) >
351          boost::uintmax_t(std::size_t(-1))){
352       error_info err(size_error);
353       throw interprocess_exception(err);
354    }
355    size = static_cast<std::size_t>(mapping_size - offset);
356 }
357 
priv_page_offset_addr_fixup(offset_t offset,const void * & address)358 inline offset_t mapped_region::priv_page_offset_addr_fixup(offset_t offset, const void *&address)
359 {
360    //We can't map any offset so we have to obtain system's
361    //memory granularity
362    const std::size_t page_size  = mapped_region::get_page_size();
363 
364    //We calculate the difference between demanded and valid offset
365    //(always less than a page in std::size_t, thus, representable by std::size_t)
366    const std::size_t page_offset =
367       static_cast<std::size_t>(offset - (offset / offset_t(page_size)) * offset_t(page_size));
368    //Update the mapping address
369    if(address){
370       address = static_cast<const char*>(address) - page_offset;
371    }
372    return offset_t(page_offset);
373 }
374 
375 #if defined (BOOST_INTERPROCESS_WINDOWS)
376 
mapped_region()377 inline mapped_region::mapped_region() BOOST_NOEXCEPT
378    :  m_base(0), m_size(0), m_page_offset(0), m_mode(read_only)
379    ,  m_file_or_mapping_hnd(ipcdetail::invalid_file())
380 {}
381 
382 template<int dummy>
get_page_size()383 inline std::size_t mapped_region::page_size_holder<dummy>::get_page_size()
384 {
385    winapi::interprocess_system_info info;
386    winapi::get_system_info(&info);
387    return std::size_t(info.dwAllocationGranularity);
388 }
389 
390 template<class MemoryMappable>
mapped_region(const MemoryMappable & mapping,mode_t mode,offset_t offset,std::size_t size,const void * address,map_options_t map_options)391 inline mapped_region::mapped_region
392    (const MemoryMappable &mapping
393    ,mode_t mode
394    ,offset_t offset
395    ,std::size_t size
396    ,const void *address
397    ,map_options_t map_options)
398    :  m_base(0), m_size(0), m_page_offset(0), m_mode(mode)
399    ,  m_file_or_mapping_hnd(ipcdetail::invalid_file())
400 {
401    mapping_handle_t mhandle = mapping.get_mapping_handle();
402    {
403       file_handle_t native_mapping_handle = 0;
404 
405       //Set accesses
406       //For "create_file_mapping"
407       unsigned long protection = 0;
408       //For "mapviewoffile"
409       unsigned long map_access = map_options == default_map_options ? 0 : map_options;
410 
411       switch(mode)
412       {
413          case read_only:
414          case read_private:
415             protection   |= winapi::page_readonly;
416             map_access   |= winapi::file_map_read;
417          break;
418          case read_write:
419             protection   |= winapi::page_readwrite;
420             map_access   |= winapi::file_map_write;
421          break;
422          case copy_on_write:
423             protection   |= winapi::page_writecopy;
424             map_access   |= winapi::file_map_copy;
425          break;
426          default:
427             {
428                error_info err(mode_error);
429                throw interprocess_exception(err);
430             }
431          break;
432       }
433 
434       //For file mapping (including emulated shared memory through temporary files),
435       //the device is a file handle so we need to obtain file's size and call create_file_mapping
436       //to obtain the mapping handle.
437       //For files we don't need the file mapping after mapping the memory, as the file is there
438       //so we'll program the handle close
439       void * handle_to_close = winapi::invalid_handle_value;
440       if(!mhandle.is_shm){
441          //Create mapping handle
442          native_mapping_handle = winapi::create_file_mapping
443             ( ipcdetail::file_handle_from_mapping_handle(mapping.get_mapping_handle())
444             , protection, 0, (char*)0, 0);
445 
446          //Check if all is correct
447          if(!native_mapping_handle){
448             error_info err ((int)winapi::get_last_error());
449             throw interprocess_exception(err);
450          }
451          handle_to_close = native_mapping_handle;
452       }
453       else{
454          //For windows_shared_memory the device handle is already a mapping handle
455          //and we need to maintain it
456          native_mapping_handle = mhandle.handle;
457       }
458       //RAII handle close on scope exit
459       const winapi::handle_closer close_handle(handle_to_close);
460       (void)close_handle;
461 
462       const offset_t page_offset = priv_page_offset_addr_fixup(offset, address);
463 
464       //Obtain mapping size if user provides 0 size
465       if(size == 0){
466          offset_t mapping_size;
467          if(!winapi::get_file_mapping_size(native_mapping_handle, mapping_size)){
468             error_info err((int)winapi::get_last_error());
469             throw interprocess_exception(err);
470          }
471          //This can throw
472          priv_size_from_mapping_size(mapping_size, offset, page_offset, size);
473       }
474 
475       //Map with new offsets and size
476       void *base = winapi::map_view_of_file_ex
477                                  (native_mapping_handle,
478                                  map_access,
479                                  ::boost::ulong_long_type(offset - page_offset),
480                                  static_cast<std::size_t>(page_offset + size),
481                                  const_cast<void*>(address));
482       //Check error
483       if(!base){
484          error_info err((int)winapi::get_last_error());
485          throw interprocess_exception(err);
486       }
487 
488       //Calculate new base for the user
489       m_base = static_cast<char*>(base) + page_offset;
490       m_page_offset = static_cast<std::size_t>(page_offset);
491       m_size = size;
492    }
493    //Windows shared memory needs the duplication of the handle if we want to
494    //make mapped_region independent from the mappable device
495    //
496    //For mapped files, we duplicate the file handle to be able to FlushFileBuffers
497    if(!winapi::duplicate_current_process_handle(mhandle.handle, &m_file_or_mapping_hnd)){
498       error_info err((int)winapi::get_last_error());
499       this->priv_close();
500       throw interprocess_exception(err);
501    }
502 }
503 
flush(std::size_t mapping_offset,std::size_t numbytes,bool async)504 inline bool mapped_region::flush(std::size_t mapping_offset, std::size_t numbytes, bool async)
505 {
506    void *addr;
507    if(!this->priv_flush_param_check(mapping_offset, addr, numbytes)){
508       return false;
509    }
510    //Flush it all
511    if(!winapi::flush_view_of_file(addr, numbytes)){
512       return false;
513    }
514    //m_file_or_mapping_hnd can be a file handle or a mapping handle.
515    //so flushing file buffers has only sense for files...
516    else if(!async && m_file_or_mapping_hnd != winapi::invalid_handle_value &&
517            winapi::get_file_type(m_file_or_mapping_hnd) == winapi::file_type_disk){
518       return winapi::flush_file_buffers(m_file_or_mapping_hnd);
519    }
520    return true;
521 }
522 
shrink_by(std::size_t bytes,bool from_back)523 inline bool mapped_region::shrink_by(std::size_t bytes, bool from_back)
524 {
525    void *shrink_page_start = 0;
526    std::size_t shrink_page_bytes = 0;
527    if(!this->priv_shrink_param_check(bytes, from_back, shrink_page_start, shrink_page_bytes)){
528       return false;
529    }
530    else if(shrink_page_bytes){
531       //In Windows, we can't decommit the storage or release the virtual address space,
532       //the best we can do is try to remove some memory from the process working set.
533       //With a bit of luck we can free some physical memory.
534       unsigned long old_protect_ignored;
535       bool b_ret = winapi::virtual_unlock(shrink_page_start, shrink_page_bytes)
536                            || (winapi::get_last_error() == winapi::error_not_locked);
537       (void)old_protect_ignored;
538       //Change page protection to forbid any further access
539       b_ret = b_ret && winapi::virtual_protect
540          (shrink_page_start, shrink_page_bytes, winapi::page_noaccess, old_protect_ignored);
541       return b_ret;
542    }
543    else{
544       return true;
545    }
546 }
547 
advise(advice_types)548 inline bool mapped_region::advise(advice_types)
549 {
550    //Windows has no madvise/posix_madvise equivalent
551    return false;
552 }
553 
priv_close()554 inline void mapped_region::priv_close()
555 {
556    if(m_base){
557       void *addr = this->priv_map_address();
558       #if !defined(BOOST_INTERPROCESS_FORCE_GENERIC_EMULATION)
559       mapped_region::destroy_syncs_in_range<0>(addr, m_size);
560       #endif
561       winapi::unmap_view_of_file(addr);
562       m_base = 0;
563    }
564    if(m_file_or_mapping_hnd != ipcdetail::invalid_file()){
565       winapi::close_handle(m_file_or_mapping_hnd);
566       m_file_or_mapping_hnd = ipcdetail::invalid_file();
567    }
568 }
569 
dont_close_on_destruction()570 inline void mapped_region::dont_close_on_destruction()
571 {}
572 
573 #else    //#if defined (BOOST_INTERPROCESS_WINDOWS)
574 
mapped_region()575 inline mapped_region::mapped_region() BOOST_NOEXCEPT
576    :  m_base(0), m_size(0), m_page_offset(0), m_mode(read_only), m_is_xsi(false)
577 {}
578 
579 template<int dummy>
get_page_size()580 inline std::size_t mapped_region::page_size_holder<dummy>::get_page_size()
581 {  return std::size_t(sysconf(_SC_PAGESIZE)); }
582 
583 template<class MemoryMappable>
mapped_region(const MemoryMappable & mapping,mode_t mode,offset_t offset,std::size_t size,const void * address,map_options_t map_options)584 inline mapped_region::mapped_region
585    ( const MemoryMappable &mapping
586    , mode_t mode
587    , offset_t offset
588    , std::size_t size
589    , const void *address
590    , map_options_t map_options)
591    : m_base(0), m_size(0), m_page_offset(0), m_mode(mode), m_is_xsi(false)
592 {
593    mapping_handle_t map_hnd = mapping.get_mapping_handle();
594 
595    //Some systems dont' support XSI shared memory
596    #ifdef BOOST_INTERPROCESS_XSI_SHARED_MEMORY_OBJECTS
597    if(map_hnd.is_xsi){
598       //Get the size
599       ::shmid_ds xsi_ds;
600       int ret = ::shmctl(map_hnd.handle, IPC_STAT, &xsi_ds);
601       if(ret == -1){
602          error_info err(system_error_code());
603          throw interprocess_exception(err);
604       }
605       //Compare sizess
606       if(size == 0){
607          size = (std::size_t)xsi_ds.shm_segsz;
608       }
609       else if(size != (std::size_t)xsi_ds.shm_segsz){
610          error_info err(size_error);
611          throw interprocess_exception(err);
612       }
613       //Calculate flag
614       int flag = map_options == default_map_options ? 0 : map_options;
615       if(m_mode == read_only){
616          flag |= SHM_RDONLY;
617       }
618       else if(m_mode != read_write){
619          error_info err(mode_error);
620          throw interprocess_exception(err);
621       }
622       //Attach memory
623       //Some old shmat implementation take the address as a non-const void pointer
624       //so uncast it to make code portable.
625       void *const final_address = const_cast<void *>(address);
626       void *base = ::shmat(map_hnd.handle, final_address, flag);
627       if(base == (void*)-1){
628          error_info err(system_error_code());
629          throw interprocess_exception(err);
630       }
631       //Update members
632       m_base   = base;
633       m_size   = size;
634       m_mode   = mode;
635       m_page_offset = 0;
636       m_is_xsi = true;
637       return;
638    }
639    #endif   //ifdef BOOST_INTERPROCESS_XSI_SHARED_MEMORY_OBJECTS
640 
641    //We calculate the difference between demanded and valid offset
642    const offset_t page_offset = priv_page_offset_addr_fixup(offset, address);
643 
644    if(size == 0){
645       struct ::stat buf;
646       if(0 != fstat(map_hnd.handle, &buf)){
647          error_info err(system_error_code());
648          throw interprocess_exception(err);
649       }
650       //This can throw
651       priv_size_from_mapping_size(buf.st_size, offset, page_offset, size);
652    }
653 
654    #ifdef MAP_NOSYNC
655       #define BOOST_INTERPROCESS_MAP_NOSYNC MAP_NOSYNC
656    #else
657       #define BOOST_INTERPROCESS_MAP_NOSYNC 0
658    #endif   //MAP_NOSYNC
659 
660    //Create new mapping
661    int prot    = 0;
662    int flags   = map_options == default_map_options ? BOOST_INTERPROCESS_MAP_NOSYNC : map_options;
663 
664    #undef BOOST_INTERPROCESS_MAP_NOSYNC
665 
666    switch(mode)
667    {
668       case read_only:
669          prot  |= PROT_READ;
670          flags |= MAP_SHARED;
671       break;
672 
673       case read_private:
674          prot  |= (PROT_READ);
675          flags |= MAP_PRIVATE;
676       break;
677 
678       case read_write:
679          prot  |= (PROT_WRITE | PROT_READ);
680          flags |= MAP_SHARED;
681       break;
682 
683       case copy_on_write:
684          prot  |= (PROT_WRITE | PROT_READ);
685          flags |= MAP_PRIVATE;
686       break;
687 
688       default:
689          {
690             error_info err(mode_error);
691             throw interprocess_exception(err);
692          }
693       break;
694    }
695 
696    //Map it to the address space
697    void* base = mmap ( const_cast<void*>(address)
698                      , static_cast<std::size_t>(page_offset) + size
699                      , prot
700                      , flags
701                      , mapping.get_mapping_handle().handle
702                      , offset - page_offset);
703 
704    //Check if mapping was successful
705    if(base == MAP_FAILED){
706       error_info err = system_error_code();
707       throw interprocess_exception(err);
708    }
709 
710    //Calculate new base for the user
711    m_base = static_cast<char*>(base) + page_offset;
712    m_page_offset = static_cast<std::size_t>(page_offset);
713    m_size   = size;
714 
715    //Check for fixed mapping error
716    if(address && (base != address)){
717       error_info err(busy_error);
718       this->priv_close();
719       throw interprocess_exception(err);
720    }
721 }
722 
shrink_by(std::size_t bytes,bool from_back)723 inline bool mapped_region::shrink_by(std::size_t bytes, bool from_back)
724 {
725    void *shrink_page_start = 0;
726    std::size_t shrink_page_bytes = 0;
727    if(m_is_xsi || !this->priv_shrink_param_check(bytes, from_back, shrink_page_start, shrink_page_bytes)){
728       return false;
729    }
730    else if(shrink_page_bytes){
731       //In UNIX we can decommit and free virtual address space.
732       return 0 == munmap(shrink_page_start, shrink_page_bytes);
733    }
734    else{
735       return true;
736    }
737 }
738 
flush(std::size_t mapping_offset,std::size_t numbytes,bool async)739 inline bool mapped_region::flush(std::size_t mapping_offset, std::size_t numbytes, bool async)
740 {
741    void *addr;
742    if(m_is_xsi || !this->priv_flush_param_check(mapping_offset, addr, numbytes)){
743       return false;
744    }
745    //Flush it all
746    return msync(addr, numbytes, async ? MS_ASYNC : MS_SYNC) == 0;
747 }
748 
advise(advice_types advice)749 inline bool mapped_region::advise(advice_types advice)
750 {
751    int unix_advice = 0;
752    //Modes; 0: none, 2: posix, 1: madvise
753    const unsigned int mode_none = 0;
754    const unsigned int mode_padv = 1;
755    const unsigned int mode_madv = 2;
756    // Suppress "unused variable" warnings
757    (void)mode_padv;
758    (void)mode_madv;
759    unsigned int mode = mode_none;
760    //Choose advice either from POSIX (preferred) or native Unix
761    switch(advice){
762       case advice_normal:
763          #if defined(POSIX_MADV_NORMAL)
764          unix_advice = POSIX_MADV_NORMAL;
765          mode = mode_padv;
766          #elif defined(MADV_NORMAL)
767          unix_advice = MADV_NORMAL;
768          mode = mode_madv;
769          #endif
770       break;
771       case advice_sequential:
772          #if defined(POSIX_MADV_SEQUENTIAL)
773          unix_advice = POSIX_MADV_SEQUENTIAL;
774          mode = mode_padv;
775          #elif defined(MADV_SEQUENTIAL)
776          unix_advice = MADV_SEQUENTIAL;
777          mode = mode_madv;
778          #endif
779       break;
780       case advice_random:
781          #if defined(POSIX_MADV_RANDOM)
782          unix_advice = POSIX_MADV_RANDOM;
783          mode = mode_padv;
784          #elif defined(MADV_RANDOM)
785          unix_advice = MADV_RANDOM;
786          mode = mode_madv;
787          #endif
788       break;
789       case advice_willneed:
790          #if defined(POSIX_MADV_WILLNEED)
791          unix_advice = POSIX_MADV_WILLNEED;
792          mode = mode_padv;
793          #elif defined(MADV_WILLNEED)
794          unix_advice = MADV_WILLNEED;
795          mode = mode_madv;
796          #endif
797       break;
798       case advice_dontneed:
799          #if defined(POSIX_MADV_DONTNEED)
800          unix_advice = POSIX_MADV_DONTNEED;
801          mode = mode_padv;
802          #elif defined(MADV_DONTNEED) && defined(BOOST_INTERPROCESS_MADV_DONTNEED_HAS_NONDESTRUCTIVE_SEMANTICS)
803          unix_advice = MADV_DONTNEED;
804          mode = mode_madv;
805          #endif
806       break;
807       default:
808       return false;
809    }
810    switch(mode){
811       #if defined(POSIX_MADV_NORMAL)
812          case mode_padv:
813          return 0 == posix_madvise(this->priv_map_address(), this->priv_map_size(), unix_advice);
814       #endif
815       #if defined(MADV_NORMAL)
816          case mode_madv:
817          return 0 == madvise(
818             #if defined(BOOST_INTERPROCESS_MADVISE_USES_CADDR_T)
819             (caddr_t)
820             #endif
821             this->priv_map_address(), this->priv_map_size(), unix_advice);
822       #endif
823       default:
824       return false;
825 
826    }
827 }
828 
priv_close()829 inline void mapped_region::priv_close()
830 {
831    if(m_base != 0){
832       #ifdef BOOST_INTERPROCESS_XSI_SHARED_MEMORY_OBJECTS
833       if(m_is_xsi){
834          int ret = ::shmdt(m_base);
835          BOOST_ASSERT(ret == 0);
836          (void)ret;
837          return;
838       }
839       #endif //#ifdef BOOST_INTERPROCESS_XSI_SHARED_MEMORY_OBJECTS
840       munmap(this->priv_map_address(), this->priv_map_size());
841       m_base = 0;
842    }
843 }
844 
dont_close_on_destruction()845 inline void mapped_region::dont_close_on_destruction()
846 {  m_base = 0;   }
847 
848 #endif   //#if defined (BOOST_INTERPROCESS_WINDOWS)
849 
850 template<int dummy>
851 const std::size_t mapped_region::page_size_holder<dummy>::PageSize
852    = mapped_region::page_size_holder<dummy>::get_page_size();
853 
get_page_size()854 inline std::size_t mapped_region::get_page_size() BOOST_NOEXCEPT
855 {
856    if(!page_size_holder<0>::PageSize)
857       return page_size_holder<0>::get_page_size();
858    else
859       return page_size_holder<0>::PageSize;
860 }
861 
swap(mapped_region & other)862 inline void mapped_region::swap(mapped_region &other) BOOST_NOEXCEPT
863 {
864    ::boost::adl_move_swap(this->m_base, other.m_base);
865    ::boost::adl_move_swap(this->m_size, other.m_size);
866    ::boost::adl_move_swap(this->m_page_offset, other.m_page_offset);
867    ::boost::adl_move_swap(this->m_mode,  other.m_mode);
868    #if defined (BOOST_INTERPROCESS_WINDOWS)
869    ::boost::adl_move_swap(this->m_file_or_mapping_hnd, other.m_file_or_mapping_hnd);
870    #else
871    ::boost::adl_move_swap(this->m_is_xsi, other.m_is_xsi);
872    #endif
873 }
874 
875 //!No-op functor
876 struct null_mapped_region_function
877 {
operator ()boost::interprocess::null_mapped_region_function878    bool operator()(void *, std::size_t , bool) const
879       {   return true;   }
880 
get_min_sizeboost::interprocess::null_mapped_region_function881    static std::size_t get_min_size()
882    {  return 0;  }
883 };
884 
885 #endif   //#ifndef BOOST_INTERPROCESS_DOXYGEN_INVOKED
886 
887 }  //namespace interprocess {
888 }  //namespace boost {
889 
890 #include <boost/interprocess/detail/config_end.hpp>
891 
892 #endif   //BOOST_INTERPROCESS_MAPPED_REGION_HPP
893 
894 #if !defined(BOOST_INTERPROCESS_DOXYGEN_INVOKED)
895 
896 #ifndef BOOST_INTERPROCESS_MAPPED_REGION_EXT_HPP
897 #define BOOST_INTERPROCESS_MAPPED_REGION_EXT_HPP
898 
899 #if defined(BOOST_INTERPROCESS_WINDOWS) && !defined(BOOST_INTERPROCESS_FORCE_GENERIC_EMULATION)
900 #  include <boost/interprocess/sync/windows/sync_utils.hpp>
901 #  include <boost/interprocess/detail/windows_intermodule_singleton.hpp>
902 
903 namespace boost {
904 namespace interprocess {
905 
906 template<int Dummy>
destroy_syncs_in_range(const void * addr,std::size_t size)907 inline void mapped_region::destroy_syncs_in_range(const void *addr, std::size_t size)
908 {
909    ipcdetail::sync_handles &handles =
910       ipcdetail::windows_intermodule_singleton<ipcdetail::sync_handles>::get();
911    handles.destroy_syncs_in_range(addr, size);
912 }
913 
914 }  //namespace interprocess {
915 }  //namespace boost {
916 
917 #endif   //defined(BOOST_INTERPROCESS_WINDOWS) && !defined(BOOST_INTERPROCESS_FORCE_GENERIC_EMULATION)
918 
919 #endif   //#ifdef BOOST_INTERPROCESS_MAPPED_REGION_EXT_HPP
920 
921 #endif   //#if !defined(BOOST_INTERPROCESS_DOXYGEN_INVOKED)
922 
923