1 // Copyright 2022 The Chromium Authors 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef BASE_WIN_SCOPED_PDH_QUERY_H_ 6 #define BASE_WIN_SCOPED_PDH_QUERY_H_ 7 8 #include <pdh.h> 9 10 #include "base/base_export.h" 11 #include "base/scoped_generic.h" 12 13 namespace base::win { 14 15 namespace internal { 16 17 struct ScopedPdhQueryTraits { InvalidValueScopedPdhQueryTraits18 static PDH_HQUERY InvalidValue() { return nullptr; } FreeScopedPdhQueryTraits19 static void Free(PDH_HQUERY query) { ::PdhCloseQuery(query); } 20 }; 21 22 } // namespace internal 23 24 // ScopedPdhQuery is a wrapper around a PDH_HQUERY, the handle used by 25 // Performance Counters functions (see 26 // https://learn.microsoft.com/en-us/windows/win32/api/_perf/.) Prefer this to 27 // using PDH_HQUERY directly to make sure that handles are always closed when 28 // going out of scope. 29 // 30 // Example use: 31 // 32 // ScopedPdhQuery pdh_query = ScopedPdhQuery::Create(); 33 // if (pdh_query.is_valid()) { 34 // ::PdhCollectQueryData(pdh_query.get(), ...); 35 // } 36 // 37 // To adopt an already-open handle: 38 // 39 // PDH_HQUERY pdh_handle; 40 // PDH_STATUS status = ::PdhOpenQuery(..., &pdh_handle); 41 // if (status == ERROR_SUCCESS) { 42 // ScopedPdhQuery pdh_query(pdh_handle); 43 // ::PdhCollectCollectQueryData(pdh_query.get(), ...); 44 // } 45 class BASE_EXPORT ScopedPdhQuery 46 : public ScopedGeneric<PDH_HQUERY, internal::ScopedPdhQueryTraits> { 47 public: 48 // Constructs a ScopedPdhQuery from a PDH_HQUERY, and takes ownership of 49 // `pdh_query` if it is not null. 50 explicit ScopedPdhQuery(PDH_HQUERY pdh_query = nullptr) ScopedGeneric(pdh_query)51 : ScopedGeneric(pdh_query) {} 52 53 // Returns a ScopedPdhQuery to the default real-time data source. Equivalent 54 // to ::PdhOpenQuery(nullptr, nullptr, &pdh_query). 55 static ScopedPdhQuery Create(); 56 }; 57 58 } // namespace base::win 59 60 #endif // BASE_WIN_SCOPED_PDH_QUERY_H_ 61