win_iocp_handle_service.ipp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  1. //
  2. // detail/impl/win_iocp_handle_service.ipp
  3. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com)
  6. // Copyright (c) 2008 Rep Invariant Systems, Inc. (info@repinvariant.com)
  7. //
  8. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  9. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  10. //
  11. #ifndef BOOST_ASIO_DETAIL_IMPL_WIN_IOCP_HANDLE_SERVICE_IPP
  12. #define BOOST_ASIO_DETAIL_IMPL_WIN_IOCP_HANDLE_SERVICE_IPP
  13. #if defined(_MSC_VER) && (_MSC_VER >= 1200)
  14. # pragma once
  15. #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
  16. #include <boost/asio/detail/config.hpp>
  17. #if defined(BOOST_ASIO_HAS_IOCP)
  18. #include <boost/asio/detail/win_iocp_handle_service.hpp>
  19. #include <boost/asio/detail/push_options.hpp>
  20. namespace boost {
  21. namespace asio {
  22. namespace detail {
  23. class win_iocp_handle_service::overlapped_wrapper
  24. : public OVERLAPPED
  25. {
  26. public:
  27. explicit overlapped_wrapper(boost::system::error_code& ec)
  28. {
  29. Internal = 0;
  30. InternalHigh = 0;
  31. Offset = 0;
  32. OffsetHigh = 0;
  33. // Create a non-signalled manual-reset event, for GetOverlappedResult.
  34. hEvent = ::CreateEventW(0, TRUE, FALSE, 0);
  35. if (hEvent)
  36. {
  37. // As documented in GetQueuedCompletionStatus, setting the low order
  38. // bit of this event prevents our synchronous writes from being treated
  39. // as completion port events.
  40. DWORD_PTR tmp = reinterpret_cast<DWORD_PTR>(hEvent);
  41. hEvent = reinterpret_cast<HANDLE>(tmp | 1);
  42. }
  43. else
  44. {
  45. DWORD last_error = ::GetLastError();
  46. ec = boost::system::error_code(last_error,
  47. boost::asio::error::get_system_category());
  48. }
  49. }
  50. ~overlapped_wrapper()
  51. {
  52. if (hEvent)
  53. {
  54. ::CloseHandle(hEvent);
  55. }
  56. }
  57. };
  58. win_iocp_handle_service::win_iocp_handle_service(execution_context& context)
  59. : execution_context_service_base<win_iocp_handle_service>(context),
  60. iocp_service_(boost::asio::use_service<win_iocp_io_context>(context)),
  61. nt_set_info_(0),
  62. mutex_(),
  63. impl_list_(0)
  64. {
  65. }
  66. void win_iocp_handle_service::shutdown()
  67. {
  68. // Close all implementations, causing all operations to complete.
  69. boost::asio::detail::mutex::scoped_lock lock(mutex_);
  70. implementation_type* impl = impl_list_;
  71. while (impl)
  72. {
  73. close_for_destruction(*impl);
  74. impl = impl->next_;
  75. }
  76. }
  77. void win_iocp_handle_service::construct(
  78. win_iocp_handle_service::implementation_type& impl)
  79. {
  80. impl.handle_ = INVALID_HANDLE_VALUE;
  81. impl.safe_cancellation_thread_id_ = 0;
  82. // Insert implementation into linked list of all implementations.
  83. boost::asio::detail::mutex::scoped_lock lock(mutex_);
  84. impl.next_ = impl_list_;
  85. impl.prev_ = 0;
  86. if (impl_list_)
  87. impl_list_->prev_ = &impl;
  88. impl_list_ = &impl;
  89. }
  90. void win_iocp_handle_service::move_construct(
  91. win_iocp_handle_service::implementation_type& impl,
  92. win_iocp_handle_service::implementation_type& other_impl)
  93. {
  94. impl.handle_ = other_impl.handle_;
  95. other_impl.handle_ = INVALID_HANDLE_VALUE;
  96. impl.safe_cancellation_thread_id_ = other_impl.safe_cancellation_thread_id_;
  97. other_impl.safe_cancellation_thread_id_ = 0;
  98. // Insert implementation into linked list of all implementations.
  99. boost::asio::detail::mutex::scoped_lock lock(mutex_);
  100. impl.next_ = impl_list_;
  101. impl.prev_ = 0;
  102. if (impl_list_)
  103. impl_list_->prev_ = &impl;
  104. impl_list_ = &impl;
  105. }
  106. void win_iocp_handle_service::move_assign(
  107. win_iocp_handle_service::implementation_type& impl,
  108. win_iocp_handle_service& other_service,
  109. win_iocp_handle_service::implementation_type& other_impl)
  110. {
  111. close_for_destruction(impl);
  112. if (this != &other_service)
  113. {
  114. // Remove implementation from linked list of all implementations.
  115. boost::asio::detail::mutex::scoped_lock lock(mutex_);
  116. if (impl_list_ == &impl)
  117. impl_list_ = impl.next_;
  118. if (impl.prev_)
  119. impl.prev_->next_ = impl.next_;
  120. if (impl.next_)
  121. impl.next_->prev_= impl.prev_;
  122. impl.next_ = 0;
  123. impl.prev_ = 0;
  124. }
  125. impl.handle_ = other_impl.handle_;
  126. other_impl.handle_ = INVALID_HANDLE_VALUE;
  127. impl.safe_cancellation_thread_id_ = other_impl.safe_cancellation_thread_id_;
  128. other_impl.safe_cancellation_thread_id_ = 0;
  129. if (this != &other_service)
  130. {
  131. // Insert implementation into linked list of all implementations.
  132. boost::asio::detail::mutex::scoped_lock lock(other_service.mutex_);
  133. impl.next_ = other_service.impl_list_;
  134. impl.prev_ = 0;
  135. if (other_service.impl_list_)
  136. other_service.impl_list_->prev_ = &impl;
  137. other_service.impl_list_ = &impl;
  138. }
  139. }
  140. void win_iocp_handle_service::destroy(
  141. win_iocp_handle_service::implementation_type& impl)
  142. {
  143. close_for_destruction(impl);
  144. // Remove implementation from linked list of all implementations.
  145. boost::asio::detail::mutex::scoped_lock lock(mutex_);
  146. if (impl_list_ == &impl)
  147. impl_list_ = impl.next_;
  148. if (impl.prev_)
  149. impl.prev_->next_ = impl.next_;
  150. if (impl.next_)
  151. impl.next_->prev_= impl.prev_;
  152. impl.next_ = 0;
  153. impl.prev_ = 0;
  154. }
  155. boost::system::error_code win_iocp_handle_service::assign(
  156. win_iocp_handle_service::implementation_type& impl,
  157. const native_handle_type& handle, boost::system::error_code& ec)
  158. {
  159. if (is_open(impl))
  160. {
  161. ec = boost::asio::error::already_open;
  162. BOOST_ASIO_ERROR_LOCATION(ec);
  163. return ec;
  164. }
  165. if (iocp_service_.register_handle(handle, ec))
  166. {
  167. BOOST_ASIO_ERROR_LOCATION(ec);
  168. return ec;
  169. }
  170. impl.handle_ = handle;
  171. ec = boost::system::error_code();
  172. return ec;
  173. }
  174. boost::system::error_code win_iocp_handle_service::close(
  175. win_iocp_handle_service::implementation_type& impl,
  176. boost::system::error_code& ec)
  177. {
  178. if (is_open(impl))
  179. {
  180. BOOST_ASIO_HANDLER_OPERATION((iocp_service_.context(), "handle",
  181. &impl, reinterpret_cast<uintmax_t>(impl.handle_), "close"));
  182. if (!::CloseHandle(impl.handle_))
  183. {
  184. DWORD last_error = ::GetLastError();
  185. ec = boost::system::error_code(last_error,
  186. boost::asio::error::get_system_category());
  187. }
  188. else
  189. {
  190. ec = boost::system::error_code();
  191. }
  192. impl.handle_ = INVALID_HANDLE_VALUE;
  193. impl.safe_cancellation_thread_id_ = 0;
  194. }
  195. else
  196. {
  197. ec = boost::system::error_code();
  198. }
  199. BOOST_ASIO_ERROR_LOCATION(ec);
  200. return ec;
  201. }
  202. win_iocp_handle_service::native_handle_type win_iocp_handle_service::release(
  203. win_iocp_handle_service::implementation_type& impl,
  204. boost::system::error_code& ec)
  205. {
  206. if (!is_open(impl))
  207. return INVALID_HANDLE_VALUE;
  208. cancel(impl, ec);
  209. if (ec)
  210. {
  211. BOOST_ASIO_ERROR_LOCATION(ec);
  212. return INVALID_HANDLE_VALUE;
  213. }
  214. nt_set_info_fn fn = get_nt_set_info();
  215. if (fn == 0)
  216. {
  217. ec = boost::asio::error::operation_not_supported;
  218. BOOST_ASIO_ERROR_LOCATION(ec);
  219. return INVALID_HANDLE_VALUE;
  220. }
  221. ULONG_PTR iosb[2] = { 0, 0 };
  222. void* info[2] = { 0, 0 };
  223. if (fn(impl.handle_, iosb, &info, sizeof(info),
  224. 61 /* FileReplaceCompletionInformation */))
  225. {
  226. ec = boost::asio::error::operation_not_supported;
  227. BOOST_ASIO_ERROR_LOCATION(ec);
  228. return INVALID_HANDLE_VALUE;
  229. }
  230. native_handle_type tmp = impl.handle_;
  231. impl.handle_ = INVALID_HANDLE_VALUE;
  232. return tmp;
  233. }
  234. boost::system::error_code win_iocp_handle_service::cancel(
  235. win_iocp_handle_service::implementation_type& impl,
  236. boost::system::error_code& ec)
  237. {
  238. if (!is_open(impl))
  239. {
  240. ec = boost::asio::error::bad_descriptor;
  241. BOOST_ASIO_ERROR_LOCATION(ec);
  242. return ec;
  243. }
  244. BOOST_ASIO_HANDLER_OPERATION((iocp_service_.context(), "handle",
  245. &impl, reinterpret_cast<uintmax_t>(impl.handle_), "cancel"));
  246. if (FARPROC cancel_io_ex_ptr = ::GetProcAddress(
  247. ::GetModuleHandleA("KERNEL32"), "CancelIoEx"))
  248. {
  249. // The version of Windows supports cancellation from any thread.
  250. typedef BOOL (WINAPI* cancel_io_ex_t)(HANDLE, LPOVERLAPPED);
  251. cancel_io_ex_t cancel_io_ex = reinterpret_cast<cancel_io_ex_t>(
  252. reinterpret_cast<void*>(cancel_io_ex_ptr));
  253. if (!cancel_io_ex(impl.handle_, 0))
  254. {
  255. DWORD last_error = ::GetLastError();
  256. if (last_error == ERROR_NOT_FOUND)
  257. {
  258. // ERROR_NOT_FOUND means that there were no operations to be
  259. // cancelled. We swallow this error to match the behaviour on other
  260. // platforms.
  261. ec = boost::system::error_code();
  262. }
  263. else
  264. {
  265. ec = boost::system::error_code(last_error,
  266. boost::asio::error::get_system_category());
  267. }
  268. }
  269. else
  270. {
  271. ec = boost::system::error_code();
  272. }
  273. }
  274. else if (impl.safe_cancellation_thread_id_ == 0)
  275. {
  276. // No operations have been started, so there's nothing to cancel.
  277. ec = boost::system::error_code();
  278. }
  279. else if (impl.safe_cancellation_thread_id_ == ::GetCurrentThreadId())
  280. {
  281. // Asynchronous operations have been started from the current thread only,
  282. // so it is safe to try to cancel them using CancelIo.
  283. if (!::CancelIo(impl.handle_))
  284. {
  285. DWORD last_error = ::GetLastError();
  286. ec = boost::system::error_code(last_error,
  287. boost::asio::error::get_system_category());
  288. }
  289. else
  290. {
  291. ec = boost::system::error_code();
  292. }
  293. }
  294. else
  295. {
  296. // Asynchronous operations have been started from more than one thread,
  297. // so cancellation is not safe.
  298. ec = boost::asio::error::operation_not_supported;
  299. }
  300. BOOST_ASIO_ERROR_LOCATION(ec);
  301. return ec;
  302. }
  303. size_t win_iocp_handle_service::do_write(
  304. win_iocp_handle_service::implementation_type& impl, uint64_t offset,
  305. const boost::asio::const_buffer& buffer, boost::system::error_code& ec)
  306. {
  307. if (!is_open(impl))
  308. {
  309. ec = boost::asio::error::bad_descriptor;
  310. BOOST_ASIO_ERROR_LOCATION(ec);
  311. return 0;
  312. }
  313. // A request to write 0 bytes on a handle is a no-op.
  314. if (buffer.size() == 0)
  315. {
  316. ec = boost::system::error_code();
  317. return 0;
  318. }
  319. overlapped_wrapper overlapped(ec);
  320. if (ec)
  321. {
  322. BOOST_ASIO_ERROR_LOCATION(ec);
  323. return 0;
  324. }
  325. // Write the data.
  326. overlapped.Offset = offset & 0xFFFFFFFF;
  327. overlapped.OffsetHigh = (offset >> 32) & 0xFFFFFFFF;
  328. BOOL ok = ::WriteFile(impl.handle_, buffer.data(),
  329. static_cast<DWORD>(buffer.size()), 0, &overlapped);
  330. if (!ok)
  331. {
  332. DWORD last_error = ::GetLastError();
  333. if (last_error != ERROR_IO_PENDING)
  334. {
  335. ec = boost::system::error_code(last_error,
  336. boost::asio::error::get_system_category());
  337. BOOST_ASIO_ERROR_LOCATION(ec);
  338. return 0;
  339. }
  340. }
  341. // Wait for the operation to complete.
  342. DWORD bytes_transferred = 0;
  343. ok = ::GetOverlappedResult(impl.handle_,
  344. &overlapped, &bytes_transferred, TRUE);
  345. if (!ok)
  346. {
  347. DWORD last_error = ::GetLastError();
  348. ec = boost::system::error_code(last_error,
  349. boost::asio::error::get_system_category());
  350. BOOST_ASIO_ERROR_LOCATION(ec);
  351. return 0;
  352. }
  353. ec = boost::system::error_code();
  354. return bytes_transferred;
  355. }
  356. void win_iocp_handle_service::start_write_op(
  357. win_iocp_handle_service::implementation_type& impl, uint64_t offset,
  358. const boost::asio::const_buffer& buffer, operation* op)
  359. {
  360. update_cancellation_thread_id(impl);
  361. iocp_service_.work_started();
  362. if (!is_open(impl))
  363. {
  364. iocp_service_.on_completion(op, boost::asio::error::bad_descriptor);
  365. }
  366. else if (buffer.size() == 0)
  367. {
  368. // A request to write 0 bytes on a handle is a no-op.
  369. iocp_service_.on_completion(op);
  370. }
  371. else
  372. {
  373. DWORD bytes_transferred = 0;
  374. op->Offset = offset & 0xFFFFFFFF;
  375. op->OffsetHigh = (offset >> 32) & 0xFFFFFFFF;
  376. BOOL ok = ::WriteFile(impl.handle_, buffer.data(),
  377. static_cast<DWORD>(buffer.size()),
  378. &bytes_transferred, op);
  379. DWORD last_error = ::GetLastError();
  380. if (!ok && last_error != ERROR_IO_PENDING
  381. && last_error != ERROR_MORE_DATA)
  382. {
  383. iocp_service_.on_completion(op, last_error, bytes_transferred);
  384. }
  385. else
  386. {
  387. iocp_service_.on_pending(op);
  388. }
  389. }
  390. }
  391. size_t win_iocp_handle_service::do_read(
  392. win_iocp_handle_service::implementation_type& impl, uint64_t offset,
  393. const boost::asio::mutable_buffer& buffer, boost::system::error_code& ec)
  394. {
  395. if (!is_open(impl))
  396. {
  397. ec = boost::asio::error::bad_descriptor;
  398. BOOST_ASIO_ERROR_LOCATION(ec);
  399. return 0;
  400. }
  401. // A request to read 0 bytes on a stream handle is a no-op.
  402. if (buffer.size() == 0)
  403. {
  404. ec = boost::system::error_code();
  405. return 0;
  406. }
  407. overlapped_wrapper overlapped(ec);
  408. if (ec)
  409. {
  410. BOOST_ASIO_ERROR_LOCATION(ec);
  411. return 0;
  412. }
  413. // Read some data.
  414. overlapped.Offset = offset & 0xFFFFFFFF;
  415. overlapped.OffsetHigh = (offset >> 32) & 0xFFFFFFFF;
  416. BOOL ok = ::ReadFile(impl.handle_, buffer.data(),
  417. static_cast<DWORD>(buffer.size()), 0, &overlapped);
  418. if (!ok)
  419. {
  420. DWORD last_error = ::GetLastError();
  421. if (last_error != ERROR_IO_PENDING && last_error != ERROR_MORE_DATA)
  422. {
  423. if (last_error == ERROR_HANDLE_EOF)
  424. {
  425. ec = boost::asio::error::eof;
  426. }
  427. else
  428. {
  429. ec = boost::system::error_code(last_error,
  430. boost::asio::error::get_system_category());
  431. }
  432. BOOST_ASIO_ERROR_LOCATION(ec);
  433. return 0;
  434. }
  435. }
  436. // Wait for the operation to complete.
  437. DWORD bytes_transferred = 0;
  438. ok = ::GetOverlappedResult(impl.handle_,
  439. &overlapped, &bytes_transferred, TRUE);
  440. if (!ok)
  441. {
  442. DWORD last_error = ::GetLastError();
  443. if (last_error == ERROR_HANDLE_EOF)
  444. {
  445. ec = boost::asio::error::eof;
  446. }
  447. else
  448. {
  449. ec = boost::system::error_code(last_error,
  450. boost::asio::error::get_system_category());
  451. }
  452. BOOST_ASIO_ERROR_LOCATION(ec);
  453. return (last_error == ERROR_MORE_DATA) ? bytes_transferred : 0;
  454. }
  455. ec = boost::system::error_code();
  456. return bytes_transferred;
  457. }
  458. void win_iocp_handle_service::start_read_op(
  459. win_iocp_handle_service::implementation_type& impl, uint64_t offset,
  460. const boost::asio::mutable_buffer& buffer, operation* op)
  461. {
  462. update_cancellation_thread_id(impl);
  463. iocp_service_.work_started();
  464. if (!is_open(impl))
  465. {
  466. iocp_service_.on_completion(op, boost::asio::error::bad_descriptor);
  467. }
  468. else if (buffer.size() == 0)
  469. {
  470. // A request to read 0 bytes on a handle is a no-op.
  471. iocp_service_.on_completion(op);
  472. }
  473. else
  474. {
  475. DWORD bytes_transferred = 0;
  476. op->Offset = offset & 0xFFFFFFFF;
  477. op->OffsetHigh = (offset >> 32) & 0xFFFFFFFF;
  478. BOOL ok = ::ReadFile(impl.handle_, buffer.data(),
  479. static_cast<DWORD>(buffer.size()),
  480. &bytes_transferred, op);
  481. DWORD last_error = ::GetLastError();
  482. if (!ok && last_error != ERROR_IO_PENDING
  483. && last_error != ERROR_MORE_DATA)
  484. {
  485. iocp_service_.on_completion(op, last_error, bytes_transferred);
  486. }
  487. else
  488. {
  489. iocp_service_.on_pending(op);
  490. }
  491. }
  492. }
  493. void win_iocp_handle_service::update_cancellation_thread_id(
  494. win_iocp_handle_service::implementation_type& impl)
  495. {
  496. if (impl.safe_cancellation_thread_id_ == 0)
  497. impl.safe_cancellation_thread_id_ = ::GetCurrentThreadId();
  498. else if (impl.safe_cancellation_thread_id_ != ::GetCurrentThreadId())
  499. impl.safe_cancellation_thread_id_ = ~DWORD(0);
  500. }
  501. void win_iocp_handle_service::close_for_destruction(implementation_type& impl)
  502. {
  503. if (is_open(impl))
  504. {
  505. BOOST_ASIO_HANDLER_OPERATION((iocp_service_.context(), "handle",
  506. &impl, reinterpret_cast<uintmax_t>(impl.handle_), "close"));
  507. ::CloseHandle(impl.handle_);
  508. impl.handle_ = INVALID_HANDLE_VALUE;
  509. impl.safe_cancellation_thread_id_ = 0;
  510. }
  511. }
  512. win_iocp_handle_service::nt_set_info_fn
  513. win_iocp_handle_service::get_nt_set_info()
  514. {
  515. void* ptr = interlocked_compare_exchange_pointer(&nt_set_info_, 0, 0);
  516. if (!ptr)
  517. {
  518. if (HMODULE h = ::GetModuleHandleA("NTDLL.DLL"))
  519. ptr = reinterpret_cast<void*>(GetProcAddress(h, "NtSetInformationFile"));
  520. // On failure, set nt_set_info_ to a special value to indicate that the
  521. // NtSetInformationFile function is unavailable. That way we won't bother
  522. // trying to look it up again.
  523. interlocked_exchange_pointer(&nt_set_info_, ptr ? ptr : this);
  524. }
  525. return reinterpret_cast<nt_set_info_fn>(ptr == this ? 0 : ptr);
  526. }
  527. void* win_iocp_handle_service::interlocked_compare_exchange_pointer(
  528. void** dest, void* exch, void* cmp)
  529. {
  530. #if defined(_M_IX86)
  531. return reinterpret_cast<void*>(InterlockedCompareExchange(
  532. reinterpret_cast<PLONG>(dest), reinterpret_cast<LONG>(exch),
  533. reinterpret_cast<LONG>(cmp)));
  534. #else
  535. return InterlockedCompareExchangePointer(dest, exch, cmp);
  536. #endif
  537. }
  538. void* win_iocp_handle_service::interlocked_exchange_pointer(
  539. void** dest, void* val)
  540. {
  541. #if defined(_M_IX86)
  542. return reinterpret_cast<void*>(InterlockedExchange(
  543. reinterpret_cast<PLONG>(dest), reinterpret_cast<LONG>(val)));
  544. #else
  545. return InterlockedExchangePointer(dest, val);
  546. #endif
  547. }
  548. } // namespace detail
  549. } // namespace asio
  550. } // namespace boost
  551. #include <boost/asio/detail/pop_options.hpp>
  552. #endif // defined(BOOST_ASIO_HAS_IOCP)
  553. #endif // BOOST_ASIO_DETAIL_IMPL_WIN_IOCP_HANDLE_SERVICE_IPP