win_iocp_handle_service.ipp 16 KB

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