com_init_balancer.cc 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. #include <objbase.h>
  5. #include "base/check_op.h"
  6. #include "base/win/com_init_balancer.h"
  7. namespace base {
  8. namespace win {
  9. namespace internal {
  10. ComInitBalancer::ComInitBalancer(DWORD co_init) : co_init_(co_init) {
  11. ULARGE_INTEGER spy_cookie = {};
  12. HRESULT hr = ::CoRegisterInitializeSpy(this, &spy_cookie);
  13. if (SUCCEEDED(hr))
  14. spy_cookie_ = spy_cookie;
  15. }
  16. ComInitBalancer::~ComInitBalancer() {
  17. DCHECK(!spy_cookie_.has_value());
  18. }
  19. void ComInitBalancer::Disable() {
  20. if (spy_cookie_.has_value()) {
  21. ::CoRevokeInitializeSpy(spy_cookie_.value());
  22. reference_count_ = 0;
  23. spy_cookie_.reset();
  24. }
  25. }
  26. DWORD ComInitBalancer::GetReferenceCountForTesting() const {
  27. return reference_count_;
  28. }
  29. IFACEMETHODIMP
  30. ComInitBalancer::PreInitialize(DWORD apartment_type, DWORD reference_count) {
  31. return S_OK;
  32. }
  33. IFACEMETHODIMP
  34. ComInitBalancer::PostInitialize(HRESULT result,
  35. DWORD apartment_type,
  36. DWORD new_reference_count) {
  37. reference_count_ = new_reference_count;
  38. return result;
  39. }
  40. IFACEMETHODIMP
  41. ComInitBalancer::PreUninitialize(DWORD reference_count) {
  42. if (reference_count == 1 && spy_cookie_.has_value()) {
  43. // Increase the reference count to prevent premature and unbalanced
  44. // uninitalization of the COM library.
  45. ::CoInitializeEx(nullptr, co_init_);
  46. }
  47. return S_OK;
  48. }
  49. IFACEMETHODIMP
  50. ComInitBalancer::PostUninitialize(DWORD new_reference_count) {
  51. reference_count_ = new_reference_count;
  52. return S_OK;
  53. }
  54. } // namespace internal
  55. } // namespace win
  56. } // namespace base