xref: /aosp_15_r20/external/cronet/base/process/process_metrics_win.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2013 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 #include "base/process/process_metrics.h"
6 
7 #include <windows.h>  // Must be in front of other Windows header files.
8 
9 #include <psapi.h>
10 #include <stddef.h>
11 #include <stdint.h>
12 #include <winternl.h>
13 
14 #include <algorithm>
15 
16 #include "base/debug/crash_logging.h"
17 #include "base/logging.h"
18 #include "base/memory/ptr_util.h"
19 #include "base/notreached.h"
20 #include "base/system/sys_info.h"
21 #include "base/threading/scoped_blocking_call.h"
22 #include "base/values.h"
23 #include "build/build_config.h"
24 
25 namespace base {
26 namespace {
27 
28 // ntstatus.h conflicts with windows.h so define this locally.
29 #define STATUS_SUCCESS ((NTSTATUS)0x00000000L)
30 
31 // Definition of this struct is taken from the book:
32 // Windows NT/200, Native API reference, Gary Nebbett
33 struct SYSTEM_PERFORMANCE_INFORMATION {
34   // Total idle time of all processes in the system (units of 100 ns).
35   LARGE_INTEGER IdleTime;
36   // Number of bytes read (by all call to ZwReadFile).
37   LARGE_INTEGER ReadTransferCount;
38   // Number of bytes written (by all call to ZwWriteFile).
39   LARGE_INTEGER WriteTransferCount;
40   // Number of bytes transferred (e.g. DeviceIoControlFile)
41   LARGE_INTEGER OtherTransferCount;
42   // The amount of read operations.
43   ULONG ReadOperationCount;
44   // The amount of write operations.
45   ULONG WriteOperationCount;
46   // The amount of other operations.
47   ULONG OtherOperationCount;
48   // The number of pages of physical memory available to processes running on
49   // the system.
50   ULONG AvailablePages;
51   ULONG TotalCommittedPages;
52   ULONG TotalCommitLimit;
53   ULONG PeakCommitment;
54   ULONG PageFaults;
55   ULONG WriteCopyFaults;
56   ULONG TransitionFaults;
57   ULONG CacheTransitionFaults;
58   ULONG DemandZeroFaults;
59   // The number of pages read from disk to resolve page faults.
60   ULONG PagesRead;
61   // The number of read operations initiated to resolve page faults.
62   ULONG PageReadIos;
63   ULONG CacheReads;
64   ULONG CacheIos;
65   // The number of pages written to the system's pagefiles.
66   ULONG PagefilePagesWritten;
67   // The number of write operations performed on the system's pagefiles.
68   ULONG PagefilePageWriteIos;
69   ULONG MappedFilePagesWritten;
70   ULONG MappedFilePageWriteIos;
71   ULONG PagedPoolUsage;
72   ULONG NonPagedPoolUsage;
73   ULONG PagedPoolAllocs;
74   ULONG PagedPoolFrees;
75   ULONG NonPagedPoolAllocs;
76   ULONG NonPagedPoolFrees;
77   ULONG TotalFreeSystemPtes;
78   ULONG SystemCodePage;
79   ULONG TotalSystemDriverPages;
80   ULONG TotalSystemCodePages;
81   ULONG SmallNonPagedLookasideListAllocateHits;
82   ULONG SmallPagedLookasideListAllocateHits;
83   ULONG Reserved3;
84   ULONG MmSystemCachePage;
85   ULONG PagedPoolPage;
86   ULONG SystemDriverPage;
87   ULONG FastReadNoWait;
88   ULONG FastReadWait;
89   ULONG FastReadResourceMiss;
90   ULONG FastReadNotPossible;
91   ULONG FastMdlReadNoWait;
92   ULONG FastMdlReadWait;
93   ULONG FastMdlReadResourceMiss;
94   ULONG FastMdlReadNotPossible;
95   ULONG MapDataNoWait;
96   ULONG MapDataWait;
97   ULONG MapDataNoWaitMiss;
98   ULONG MapDataWaitMiss;
99   ULONG PinMappedDataCount;
100   ULONG PinReadNoWait;
101   ULONG PinReadWait;
102   ULONG PinReadNoWaitMiss;
103   ULONG PinReadWaitMiss;
104   ULONG CopyReadNoWait;
105   ULONG CopyReadWait;
106   ULONG CopyReadNoWaitMiss;
107   ULONG CopyReadWaitMiss;
108   ULONG MdlReadNoWait;
109   ULONG MdlReadWait;
110   ULONG MdlReadNoWaitMiss;
111   ULONG MdlReadWaitMiss;
112   ULONG ReadAheadIos;
113   ULONG LazyWriteIos;
114   ULONG LazyWritePages;
115   ULONG DataFlushes;
116   ULONG DataPages;
117   ULONG ContextSwitches;
118   ULONG FirstLevelTbFills;
119   ULONG SecondLevelTbFills;
120   ULONG SystemCalls;
121 };
122 
GetImpreciseCumulativeCPUUsage(const win::ScopedHandle & process)123 base::expected<TimeDelta, ProcessCPUUsageError> GetImpreciseCumulativeCPUUsage(
124     const win::ScopedHandle& process) {
125   FILETIME creation_time;
126   FILETIME exit_time;
127   FILETIME kernel_time;
128   FILETIME user_time;
129 
130   if (!process.is_valid()) {
131     return base::unexpected(ProcessCPUUsageError::kSystemError);
132   }
133 
134   if (!GetProcessTimes(process.get(), &creation_time, &exit_time, &kernel_time,
135                        &user_time)) {
136     // This should never fail when the handle is valid.
137     NOTREACHED(NotFatalUntil::M125);
138     return base::unexpected(ProcessCPUUsageError::kSystemError);
139   }
140 
141   return base::ok(TimeDelta::FromFileTime(kernel_time) +
142                   TimeDelta::FromFileTime(user_time));
143 }
144 
145 }  // namespace
146 
GetMaxFds()147 size_t GetMaxFds() {
148   // Windows is only limited by the amount of physical memory.
149   return std::numeric_limits<size_t>::max();
150 }
151 
GetHandleLimit()152 size_t GetHandleLimit() {
153   // Rounded down from value reported here:
154   // http://blogs.technet.com/b/markrussinovich/archive/2009/09/29/3283844.aspx
155   return static_cast<size_t>(1 << 23);
156 }
157 
158 // static
CreateProcessMetrics(ProcessHandle process)159 std::unique_ptr<ProcessMetrics> ProcessMetrics::CreateProcessMetrics(
160     ProcessHandle process) {
161   return WrapUnique(new ProcessMetrics(process));
162 }
163 
164 base::expected<TimeDelta, ProcessCPUUsageError>
GetCumulativeCPUUsage()165 ProcessMetrics::GetCumulativeCPUUsage() {
166 #if defined(ARCH_CPU_ARM64)
167   // Precise CPU usage is not available on Arm CPUs because they don't support
168   // constant rate TSC.
169   return GetImpreciseCumulativeCPUUsage(process_);
170 #else   // !defined(ARCH_CPU_ARM64)
171   if (!time_internal::HasConstantRateTSC()) {
172     return GetImpreciseCumulativeCPUUsage(process_);
173   }
174 
175   const double tsc_ticks_per_second = time_internal::TSCTicksPerSecond();
176   if (tsc_ticks_per_second == 0) {
177     // TSC is only initialized once TSCTicksPerSecond() is called twice 50 ms
178     // apart on the same thread to get a baseline. In unit tests, it is frequent
179     // for the initialization not to be complete. In production, it can also
180     // theoretically happen.
181     return GetImpreciseCumulativeCPUUsage(process_);
182   }
183 
184   if (!process_.is_valid()) {
185     return base::unexpected(ProcessCPUUsageError::kProcessNotFound);
186   }
187 
188   ULONG64 process_cycle_time = 0;
189   if (!QueryProcessCycleTime(process_.get(), &process_cycle_time)) {
190     // This should never fail when the handle is valid.
191     NOTREACHED(NotFatalUntil::M125);
192     return base::unexpected(ProcessCPUUsageError::kSystemError);
193   }
194 
195   const double process_time_seconds = process_cycle_time / tsc_ticks_per_second;
196   return base::ok(Seconds(process_time_seconds));
197 #endif  // !defined(ARCH_CPU_ARM64)
198 }
199 
ProcessMetrics(ProcessHandle process)200 ProcessMetrics::ProcessMetrics(ProcessHandle process) {
201   if (!process) {
202     // Don't try to duplicate an invalid handle.
203     return;
204   }
205   HANDLE duplicate_handle = INVALID_HANDLE_VALUE;
206   BOOL result = ::DuplicateHandle(::GetCurrentProcess(), process,
207                                   ::GetCurrentProcess(), &duplicate_handle,
208                                   PROCESS_QUERY_LIMITED_INFORMATION, FALSE, 0);
209   if (!result) {
210     // TODO(crbug.com/326136373): Remove this crash key and just CHECK(result)
211     // after verifying that DuplicateHandle doesn't fail for unexpected reasons
212     // in production.
213     const DWORD last_error = ::GetLastError();
214     SCOPED_CRASH_KEY_NUMBER("ProcessMetrics", "dup_handle_error", last_error);
215     NOTREACHED(NotFatalUntil::M126);
216     return;
217   }
218 
219   process_.Set(duplicate_handle);
220 }
221 
GetSystemCommitCharge()222 size_t GetSystemCommitCharge() {
223   // Get the System Page Size.
224   SYSTEM_INFO system_info;
225   GetSystemInfo(&system_info);
226 
227   PERFORMANCE_INFORMATION info;
228   if (!GetPerformanceInfo(&info, sizeof(info))) {
229     DLOG(ERROR) << "Failed to fetch internal performance info.";
230     return 0;
231   }
232   return (info.CommitTotal * system_info.dwPageSize) / 1024;
233 }
234 
235 // This function uses the following mapping between MEMORYSTATUSEX and
236 // SystemMemoryInfoKB:
237 //   ullTotalPhys ==> total
238 //   ullAvailPhys ==> avail_phys
239 //   ullTotalPageFile ==> swap_total
240 //   ullAvailPageFile ==> swap_free
GetSystemMemoryInfo(SystemMemoryInfoKB * meminfo)241 bool GetSystemMemoryInfo(SystemMemoryInfoKB* meminfo) {
242   MEMORYSTATUSEX mem_status;
243   mem_status.dwLength = sizeof(mem_status);
244   if (!::GlobalMemoryStatusEx(&mem_status)) {
245     return false;
246   }
247 
248   meminfo->total = saturated_cast<int>(mem_status.ullTotalPhys / 1024);
249   meminfo->avail_phys = saturated_cast<int>(mem_status.ullAvailPhys / 1024);
250   meminfo->swap_total = saturated_cast<int>(mem_status.ullTotalPageFile / 1024);
251   meminfo->swap_free = saturated_cast<int>(mem_status.ullAvailPageFile / 1024);
252 
253   return true;
254 }
255 
GetMallocUsage()256 size_t ProcessMetrics::GetMallocUsage() {
257   // Unsupported as getting malloc usage on Windows requires iterating through
258   // the heap which is slow and crashes.
259   return 0;
260 }
261 
262 SystemPerformanceInfo::SystemPerformanceInfo() = default;
263 SystemPerformanceInfo::SystemPerformanceInfo(
264     const SystemPerformanceInfo& other) = default;
265 SystemPerformanceInfo& SystemPerformanceInfo::operator=(
266     const SystemPerformanceInfo& other) = default;
267 
ToDict() const268 Value::Dict SystemPerformanceInfo::ToDict() const {
269   Value::Dict result;
270 
271   // Write out uint64_t variables as doubles.
272   // Note: this may discard some precision, but for JS there's no other option.
273   result.Set("idle_time", strict_cast<double>(idle_time));
274   result.Set("read_transfer_count", strict_cast<double>(read_transfer_count));
275   result.Set("write_transfer_count", strict_cast<double>(write_transfer_count));
276   result.Set("other_transfer_count", strict_cast<double>(other_transfer_count));
277   result.Set("read_operation_count", strict_cast<double>(read_operation_count));
278   result.Set("write_operation_count",
279              strict_cast<double>(write_operation_count));
280   result.Set("other_operation_count",
281              strict_cast<double>(other_operation_count));
282   result.Set("pagefile_pages_written",
283              strict_cast<double>(pagefile_pages_written));
284   result.Set("pagefile_pages_write_ios",
285              strict_cast<double>(pagefile_pages_write_ios));
286   result.Set("available_pages", strict_cast<double>(available_pages));
287   result.Set("pages_read", strict_cast<double>(pages_read));
288   result.Set("page_read_ios", strict_cast<double>(page_read_ios));
289 
290   return result;
291 }
292 
293 // Retrieves performance counters from the operating system.
294 // Fills in the provided |info| structure. Returns true on success.
GetSystemPerformanceInfo(SystemPerformanceInfo * info)295 BASE_EXPORT bool GetSystemPerformanceInfo(SystemPerformanceInfo* info) {
296   SYSTEM_PERFORMANCE_INFORMATION counters = {};
297   {
298     // The call to NtQuerySystemInformation might block on a lock.
299     base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
300                                                   BlockingType::MAY_BLOCK);
301     if (::NtQuerySystemInformation(::SystemPerformanceInformation, &counters,
302                                    sizeof(SYSTEM_PERFORMANCE_INFORMATION),
303                                    nullptr) != STATUS_SUCCESS) {
304       return false;
305     }
306   }
307 
308   info->idle_time = static_cast<uint64_t>(counters.IdleTime.QuadPart);
309   info->read_transfer_count =
310       static_cast<uint64_t>(counters.ReadTransferCount.QuadPart);
311   info->write_transfer_count =
312       static_cast<uint64_t>(counters.WriteTransferCount.QuadPart);
313   info->other_transfer_count =
314       static_cast<uint64_t>(counters.OtherTransferCount.QuadPart);
315   info->read_operation_count = counters.ReadOperationCount;
316   info->write_operation_count = counters.WriteOperationCount;
317   info->other_operation_count = counters.OtherOperationCount;
318   info->pagefile_pages_written = counters.PagefilePagesWritten;
319   info->pagefile_pages_write_ios = counters.PagefilePageWriteIos;
320   info->available_pages = counters.AvailablePages;
321   info->pages_read = counters.PagesRead;
322   info->page_read_ios = counters.PageReadIos;
323 
324   return true;
325 }
326 
327 }  // namespace base
328