• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/check.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();
138   }
139 
140   return base::ok(TimeDelta::FromFileTime(kernel_time) +
141                   TimeDelta::FromFileTime(user_time));
142 }
143 
144 }  // namespace
145 
GetMaxFds()146 size_t GetMaxFds() {
147   // Windows is only limited by the amount of physical memory.
148   return std::numeric_limits<size_t>::max();
149 }
150 
GetHandleLimit()151 size_t GetHandleLimit() {
152   // Rounded down from value reported here:
153   // http://blogs.technet.com/b/markrussinovich/archive/2009/09/29/3283844.aspx
154   return static_cast<size_t>(1 << 23);
155 }
156 
157 // static
CreateProcessMetrics(ProcessHandle process)158 std::unique_ptr<ProcessMetrics> ProcessMetrics::CreateProcessMetrics(
159     ProcessHandle process) {
160   return WrapUnique(new ProcessMetrics(process));
161 }
162 
163 base::expected<TimeDelta, ProcessCPUUsageError>
GetCumulativeCPUUsage()164 ProcessMetrics::GetCumulativeCPUUsage() {
165 #if defined(ARCH_CPU_ARM64)
166   // Precise CPU usage is not available on Arm CPUs because they don't support
167   // constant rate TSC.
168   return GetImpreciseCumulativeCPUUsage(process_);
169 #else   // !defined(ARCH_CPU_ARM64)
170   if (!time_internal::HasConstantRateTSC()) {
171     return GetImpreciseCumulativeCPUUsage(process_);
172   }
173 
174   const double tsc_ticks_per_second = time_internal::TSCTicksPerSecond();
175   if (tsc_ticks_per_second == 0) {
176     // TSC is only initialized once TSCTicksPerSecond() is called twice 50 ms
177     // apart on the same thread to get a baseline. In unit tests, it is frequent
178     // for the initialization not to be complete. In production, it can also
179     // theoretically happen.
180     return GetImpreciseCumulativeCPUUsage(process_);
181   }
182 
183   if (!process_.is_valid()) {
184     return base::unexpected(ProcessCPUUsageError::kProcessNotFound);
185   }
186 
187   ULONG64 process_cycle_time = 0;
188   if (!QueryProcessCycleTime(process_.get(), &process_cycle_time)) {
189     // This should never fail when the handle is valid.
190     NOTREACHED();
191   }
192 
193   const double process_time_seconds = process_cycle_time / tsc_ticks_per_second;
194   return base::ok(Seconds(process_time_seconds));
195 #endif  // !defined(ARCH_CPU_ARM64)
196 }
197 
ProcessMetrics(ProcessHandle process)198 ProcessMetrics::ProcessMetrics(ProcessHandle process) {
199   if (process == kNullProcessHandle) {
200     // Don't try to duplicate an invalid handle. However, INVALID_HANDLE_VALUE
201     // is also the pseudo-handle returned by ::GetCurrentProcess(), so DO try
202     // to duplicate that.
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     // Even with PROCESS_QUERY_LIMITED_INFORMATION, DuplicateHandle can fail
211     // with ERROR_ACCESS_DENIED. And it's always possible to run out of handles.
212     const DWORD last_error = ::GetLastError();
213     CHECK(last_error == ERROR_ACCESS_DENIED ||
214           last_error == ERROR_NO_SYSTEM_RESOURCES);
215     return;
216   }
217 
218   process_.Set(duplicate_handle);
219 }
220 
GetSystemCommitCharge()221 size_t GetSystemCommitCharge() {
222   // Get the System Page Size.
223   SYSTEM_INFO system_info;
224   GetSystemInfo(&system_info);
225 
226   PERFORMANCE_INFORMATION info;
227   if (!GetPerformanceInfo(&info, sizeof(info))) {
228     DLOG(ERROR) << "Failed to fetch internal performance info.";
229     return 0;
230   }
231   return (info.CommitTotal * system_info.dwPageSize) / 1024;
232 }
233 
234 // This function uses the following mapping between MEMORYSTATUSEX and
235 // SystemMemoryInfoKB:
236 //   ullTotalPhys ==> total
237 //   ullAvailPhys ==> avail_phys
238 //   ullTotalPageFile ==> swap_total
239 //   ullAvailPageFile ==> swap_free
GetSystemMemoryInfo(SystemMemoryInfoKB * meminfo)240 bool GetSystemMemoryInfo(SystemMemoryInfoKB* meminfo) {
241   MEMORYSTATUSEX mem_status;
242   mem_status.dwLength = sizeof(mem_status);
243   if (!::GlobalMemoryStatusEx(&mem_status)) {
244     return false;
245   }
246 
247   meminfo->total = saturated_cast<int>(mem_status.ullTotalPhys / 1024);
248   meminfo->avail_phys = saturated_cast<int>(mem_status.ullAvailPhys / 1024);
249   meminfo->swap_total = saturated_cast<int>(mem_status.ullTotalPageFile / 1024);
250   meminfo->swap_free = saturated_cast<int>(mem_status.ullAvailPageFile / 1024);
251 
252   return true;
253 }
254 
GetMallocUsage()255 size_t ProcessMetrics::GetMallocUsage() {
256   // Unsupported as getting malloc usage on Windows requires iterating through
257   // the heap which is slow and crashes.
258   return 0;
259 }
260 
261 SystemPerformanceInfo::SystemPerformanceInfo() = default;
262 SystemPerformanceInfo::SystemPerformanceInfo(
263     const SystemPerformanceInfo& other) = default;
264 SystemPerformanceInfo& SystemPerformanceInfo::operator=(
265     const SystemPerformanceInfo& other) = default;
266 
ToDict() const267 Value::Dict SystemPerformanceInfo::ToDict() const {
268   Value::Dict result;
269 
270   // Write out uint64_t variables as doubles.
271   // Note: this may discard some precision, but for JS there's no other option.
272   result.Set("idle_time", strict_cast<double>(idle_time));
273   result.Set("read_transfer_count", strict_cast<double>(read_transfer_count));
274   result.Set("write_transfer_count", strict_cast<double>(write_transfer_count));
275   result.Set("other_transfer_count", strict_cast<double>(other_transfer_count));
276   result.Set("read_operation_count", strict_cast<double>(read_operation_count));
277   result.Set("write_operation_count",
278              strict_cast<double>(write_operation_count));
279   result.Set("other_operation_count",
280              strict_cast<double>(other_operation_count));
281   result.Set("pagefile_pages_written",
282              strict_cast<double>(pagefile_pages_written));
283   result.Set("pagefile_pages_write_ios",
284              strict_cast<double>(pagefile_pages_write_ios));
285   result.Set("available_pages", strict_cast<double>(available_pages));
286   result.Set("pages_read", strict_cast<double>(pages_read));
287   result.Set("page_read_ios", strict_cast<double>(page_read_ios));
288 
289   return result;
290 }
291 
292 // Retrieves performance counters from the operating system.
293 // Fills in the provided |info| structure. Returns true on success.
GetSystemPerformanceInfo(SystemPerformanceInfo * info)294 BASE_EXPORT bool GetSystemPerformanceInfo(SystemPerformanceInfo* info) {
295   SYSTEM_PERFORMANCE_INFORMATION counters = {};
296   {
297     // The call to NtQuerySystemInformation might block on a lock.
298     base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
299                                                   BlockingType::MAY_BLOCK);
300     if (::NtQuerySystemInformation(::SystemPerformanceInformation, &counters,
301                                    sizeof(SYSTEM_PERFORMANCE_INFORMATION),
302                                    nullptr) != STATUS_SUCCESS) {
303       return false;
304     }
305   }
306 
307   info->idle_time = static_cast<uint64_t>(counters.IdleTime.QuadPart);
308   info->read_transfer_count =
309       static_cast<uint64_t>(counters.ReadTransferCount.QuadPart);
310   info->write_transfer_count =
311       static_cast<uint64_t>(counters.WriteTransferCount.QuadPart);
312   info->other_transfer_count =
313       static_cast<uint64_t>(counters.OtherTransferCount.QuadPart);
314   info->read_operation_count = counters.ReadOperationCount;
315   info->write_operation_count = counters.WriteOperationCount;
316   info->other_operation_count = counters.OtherOperationCount;
317   info->pagefile_pages_written = counters.PagefilePagesWritten;
318   info->pagefile_pages_write_ios = counters.PagefilePageWriteIos;
319   info->available_pages = counters.AvailablePages;
320   info->pages_read = counters.PagesRead;
321   info->page_read_ios = counters.PageReadIos;
322 
323   return true;
324 }
325 
326 }  // namespace base
327