com_init_balancer.h 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright 2020 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_COM_INIT_BALANCER_H_
  5. #define BASE_WIN_COM_INIT_BALANCER_H_
  6. #include <objidl.h>
  7. #include <winnt.h>
  8. #include <wrl/implements.h>
  9. #include "base/base_export.h"
  10. #include "base/optional.h"
  11. #include "base/threading/thread_checker.h"
  12. #include "base/win/windows_types.h"
  13. namespace base {
  14. namespace win {
  15. namespace internal {
  16. // Implementation class of the IInitializeSpy Interface that prevents premature
  17. // uninitialization of the COM library, often caused by unbalanced
  18. // CoInitialize/CoUninitialize pairs. The use of this class is encouraged in
  19. // COM-supporting threads that execute third-party code.
  20. //
  21. // Disable() must be called before uninitializing the COM library in order to
  22. // revoke the registered spy and allow for the successful uninitialization of
  23. // the COM library.
  24. class BASE_EXPORT ComInitBalancer
  25. : public Microsoft::WRL::RuntimeClass<
  26. Microsoft::WRL::RuntimeClassFlags<Microsoft::WRL::ClassicCom>,
  27. IInitializeSpy> {
  28. public:
  29. // Constructs a COM initialize balancer. |co_init| defines the apartment's
  30. // concurrency model used by the balancer.
  31. explicit ComInitBalancer(DWORD co_init);
  32. ComInitBalancer(const ComInitBalancer&) = delete;
  33. ComInitBalancer& operator=(const ComInitBalancer&) = delete;
  34. ~ComInitBalancer() override;
  35. // Disables balancer by revoking the registered spy and consequently
  36. // unblocking attempts to uninitialize the COM library.
  37. void Disable();
  38. DWORD GetReferenceCountForTesting() const;
  39. private:
  40. // IInitializeSpy:
  41. IFACEMETHODIMP PreInitialize(DWORD apartment_type,
  42. DWORD reference_count) override;
  43. IFACEMETHODIMP PostInitialize(HRESULT result,
  44. DWORD apartment_type,
  45. DWORD new_reference_count) override;
  46. IFACEMETHODIMP PreUninitialize(DWORD reference_count) override;
  47. IFACEMETHODIMP PostUninitialize(DWORD new_reference_count) override;
  48. const DWORD co_init_;
  49. // The current apartment reference count set after the completion of the last
  50. // call made to CoInitialize or CoUninitialize.
  51. DWORD reference_count_ = 0;
  52. base::Optional<ULARGE_INTEGER> spy_cookie_;
  53. THREAD_CHECKER(thread_checker_);
  54. };
  55. } // namespace internal
  56. } // namespace win
  57. } // namespace base
  58. #endif // BASE_WIN_COM_INIT_BALANCER_H_