scoped_handle.h 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. // Copyright (c) 2012 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef BASE_WIN_SCOPED_HANDLE_H_
  5. #define BASE_WIN_SCOPED_HANDLE_H_
  6. #include <ostream>
  7. #include "base/base_export.h"
  8. #include "base/check_op.h"
  9. #include "base/dcheck_is_on.h"
  10. #include "base/gtest_prod_util.h"
  11. #include "base/location.h"
  12. #include "base/win/windows_types.h"
  13. #include "build/build_config.h"
  14. // TODO(rvargas): remove this with the rest of the verifier.
  15. #if defined(COMPILER_MSVC)
  16. #include <intrin.h>
  17. #define BASE_WIN_GET_CALLER _ReturnAddress()
  18. #elif defined(COMPILER_GCC)
  19. #define BASE_WIN_GET_CALLER \
  20. __builtin_extract_return_addr(__builtin_return_address(0))
  21. #endif
  22. namespace base {
  23. namespace win {
  24. enum class HandleOperation {
  25. kHandleAlreadyTracked,
  26. kCloseHandleNotTracked,
  27. kCloseHandleNotOwner,
  28. kCloseHandleHook,
  29. kDuplicateHandleHook
  30. };
  31. std::ostream& operator<<(std::ostream& os, HandleOperation operation);
  32. // Generic wrapper for raw handles that takes care of closing handles
  33. // automatically. The class interface follows the style of
  34. // the ScopedFILE class with two additions:
  35. // - IsValid() method can tolerate multiple invalid handle values such as NULL
  36. // and INVALID_HANDLE_VALUE (-1) for Win32 handles.
  37. // - Set() (and the constructors and assignment operators that call it)
  38. // preserve the Windows LastError code. This ensures that GetLastError() can
  39. // be called after stashing a handle in a GenericScopedHandle object. Doing
  40. // this explicitly is necessary because of bug 528394 and VC++ 2015.
  41. template <class Traits, class Verifier>
  42. class GenericScopedHandle {
  43. public:
  44. using Handle = typename Traits::Handle;
  45. GenericScopedHandle() : handle_(Traits::NullHandle()) {}
  46. explicit GenericScopedHandle(Handle handle) : handle_(Traits::NullHandle()) {
  47. Set(handle);
  48. }
  49. GenericScopedHandle(GenericScopedHandle&& other)
  50. : handle_(Traits::NullHandle()) {
  51. Set(other.Take());
  52. }
  53. GenericScopedHandle(const GenericScopedHandle&) = delete;
  54. GenericScopedHandle& operator=(const GenericScopedHandle&) = delete;
  55. ~GenericScopedHandle() { Close(); }
  56. bool is_valid() const { return Traits::IsHandleValid(handle_); }
  57. // TODO(crbug.com/1291793): Migrate callers to is_valid().
  58. bool IsValid() const { return is_valid(); }
  59. GenericScopedHandle& operator=(GenericScopedHandle&& other) {
  60. DCHECK_NE(this, &other);
  61. Set(other.Take());
  62. return *this;
  63. }
  64. void Set(Handle handle) {
  65. if (handle_ != handle) {
  66. // Preserve old LastError to avoid bug 528394.
  67. auto last_error = ::GetLastError();
  68. Close();
  69. if (Traits::IsHandleValid(handle)) {
  70. handle_ = handle;
  71. Verifier::StartTracking(handle, this, BASE_WIN_GET_CALLER,
  72. GetProgramCounter());
  73. }
  74. ::SetLastError(last_error);
  75. }
  76. }
  77. Handle get() const { return handle_; }
  78. // TODO(crbug.com/1291793): Migrate callers to get().
  79. Handle Get() const { return get(); }
  80. // Transfers ownership away from this object.
  81. [[nodiscard]] Handle release() {
  82. Handle temp = handle_;
  83. handle_ = Traits::NullHandle();
  84. if (Traits::IsHandleValid(temp)) {
  85. Verifier::StopTracking(temp, this, BASE_WIN_GET_CALLER,
  86. GetProgramCounter());
  87. }
  88. return temp;
  89. }
  90. // TODO(crbug.com/1291793): Migrate callers to release().
  91. [[nodiscard]] Handle Take() { return release(); }
  92. // Explicitly closes the owned handle.
  93. void Close() {
  94. if (Traits::IsHandleValid(handle_)) {
  95. Verifier::StopTracking(handle_, this, BASE_WIN_GET_CALLER,
  96. GetProgramCounter());
  97. Traits::CloseHandle(handle_);
  98. handle_ = Traits::NullHandle();
  99. }
  100. }
  101. private:
  102. FRIEND_TEST_ALL_PREFIXES(ScopedHandleDeathTest, HandleVerifierWrongOwner);
  103. FRIEND_TEST_ALL_PREFIXES(ScopedHandleDeathTest,
  104. HandleVerifierUntrackedHandle);
  105. Handle handle_;
  106. };
  107. #undef BASE_WIN_GET_CALLER
  108. // The traits class for Win32 handles that can be closed via CloseHandle() API.
  109. class HandleTraits {
  110. public:
  111. using Handle = HANDLE;
  112. HandleTraits() = delete;
  113. HandleTraits(const HandleTraits&) = delete;
  114. HandleTraits& operator=(const HandleTraits&) = delete;
  115. // Closes the handle.
  116. static bool BASE_EXPORT CloseHandle(HANDLE handle);
  117. // Returns true if the handle value is valid.
  118. static bool IsHandleValid(HANDLE handle) {
  119. return handle != nullptr && handle != INVALID_HANDLE_VALUE;
  120. }
  121. // Returns NULL handle value.
  122. static HANDLE NullHandle() { return nullptr; }
  123. };
  124. // Do-nothing verifier.
  125. class DummyVerifierTraits {
  126. public:
  127. using Handle = HANDLE;
  128. DummyVerifierTraits() = delete;
  129. DummyVerifierTraits(const DummyVerifierTraits&) = delete;
  130. DummyVerifierTraits& operator=(const DummyVerifierTraits&) = delete;
  131. static void StartTracking(HANDLE handle,
  132. const void* owner,
  133. const void* pc1,
  134. const void* pc2) {}
  135. static void StopTracking(HANDLE handle,
  136. const void* owner,
  137. const void* pc1,
  138. const void* pc2) {}
  139. };
  140. // Performs actual run-time tracking.
  141. class BASE_EXPORT VerifierTraits {
  142. public:
  143. using Handle = HANDLE;
  144. VerifierTraits() = delete;
  145. VerifierTraits(const VerifierTraits&) = delete;
  146. VerifierTraits& operator=(const VerifierTraits&) = delete;
  147. static void StartTracking(HANDLE handle,
  148. const void* owner,
  149. const void* pc1,
  150. const void* pc2);
  151. static void StopTracking(HANDLE handle,
  152. const void* owner,
  153. const void* pc1,
  154. const void* pc2);
  155. };
  156. using UncheckedScopedHandle =
  157. GenericScopedHandle<HandleTraits, DummyVerifierTraits>;
  158. using CheckedScopedHandle = GenericScopedHandle<HandleTraits, VerifierTraits>;
  159. #if DCHECK_IS_ON()
  160. using ScopedHandle = CheckedScopedHandle;
  161. #else
  162. using ScopedHandle = UncheckedScopedHandle;
  163. #endif
  164. // This function may be called by the embedder to disable the use of
  165. // VerifierTraits at runtime. It has no effect if DummyVerifierTraits is used
  166. // for ScopedHandle.
  167. BASE_EXPORT void DisableHandleVerifier();
  168. // This should be called whenever the OS is closing a handle, if extended
  169. // verification of improper handle closing is desired. If |handle| is being
  170. // tracked by the handle verifier and ScopedHandle is not the one closing it,
  171. // a CHECK is generated.
  172. BASE_EXPORT void OnHandleBeingClosed(HANDLE handle, HandleOperation operation);
  173. } // namespace win
  174. } // namespace base
  175. #endif // BASE_WIN_SCOPED_HANDLE_H_