mapped_region.hpp 32 KB

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