Roll src/third_party/skia a5783ae:7628967
[chromium-blink-merge.git] / components / browser_watcher / watcher_metrics_provider_win.cc
blob76352b8b36a4e7731509c27d5c1ea21646dfb25f
1 // Copyright (c) 2014 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.
5 #include "components/browser_watcher/watcher_metrics_provider_win.h"
7 #include <limits>
8 #include <vector>
10 #include "base/metrics/sparse_histogram.h"
11 #include "base/process/process.h"
12 #include "base/strings/string_number_conversions.h"
13 #include "base/strings/string_piece.h"
14 #include "base/strings/utf_string_conversions.h"
15 #include "base/win/registry.h"
17 namespace browser_watcher {
19 namespace {
21 // Process ID APIs on Windows talk in DWORDs, whereas for string formatting
22 // and parsing, this code uses int. In practice there are no process IDs with
23 // the high bit set on Windows, so there's no danger of overflow if this is
24 // done consistently.
25 static_assert(sizeof(DWORD) == sizeof(int),
26 "process ids are expected to be no larger than int");
28 // This function does soft matching on the PID recorded in the key only.
29 // Due to PID reuse, the possibility exists that the process that's now live
30 // with the given PID is not the same process the data was recorded for.
31 // This doesn't matter for the purpose, as eventually the data will be
32 // scavenged and reported.
33 bool IsDeadProcess(base::StringPiece16 key_or_value_name) {
34 // Truncate the input string to the first occurrence of '-', if one exists.
35 size_t num_end = key_or_value_name.find(L'-');
36 if (num_end != base::StringPiece16::npos)
37 key_or_value_name = key_or_value_name.substr(0, num_end);
39 // Convert to the numeric PID.
40 int pid = 0;
41 if (!base::StringToInt(key_or_value_name, &pid) || pid == 0)
42 return true;
44 // This is a very inexpensive check for the common case of our own PID.
45 if (static_cast<base::ProcessId>(pid) == base::GetCurrentProcId())
46 return false;
48 // The process is not our own - see whether a process with this PID exists.
49 // This is more expensive than the above check, but should also be very rare,
50 // as this only happens more than once for a given PID if a user is running
51 // multiple Chrome instances concurrently.
52 base::Process process =
53 base::Process::Open(static_cast<base::ProcessId>(pid));
54 if (process.IsValid()) {
55 // The fact that it was possible to open the process says it's live.
56 return false;
59 return true;
62 void RecordExitCodes(const base::string16& registry_path) {
63 base::win::RegKey regkey(HKEY_CURRENT_USER,
64 registry_path.c_str(),
65 KEY_QUERY_VALUE | KEY_SET_VALUE);
66 if (!regkey.Valid())
67 return;
69 size_t num = regkey.GetValueCount();
70 if (num == 0)
71 return;
72 std::vector<base::string16> to_delete;
74 // Record the exit codes in a sparse stability histogram, as the range of
75 // values used to report failures is large.
76 base::HistogramBase* exit_code_histogram =
77 base::SparseHistogram::FactoryGet(
78 WatcherMetricsProviderWin::kBrowserExitCodeHistogramName,
79 base::HistogramBase::kUmaStabilityHistogramFlag);
81 for (size_t i = 0; i < num; ++i) {
82 base::string16 name;
83 if (regkey.GetValueNameAt(static_cast<int>(i), &name) == ERROR_SUCCESS) {
84 DWORD exit_code = 0;
85 if (regkey.ReadValueDW(name.c_str(), &exit_code) == ERROR_SUCCESS) {
86 // Do not report exit codes for processes that are still live,
87 // notably for our own process.
88 if (exit_code != STILL_ACTIVE || IsDeadProcess(name)) {
89 to_delete.push_back(name);
90 exit_code_histogram->Add(exit_code);
96 // Delete the values reported above.
97 for (size_t i = 0; i < to_delete.size(); ++i)
98 regkey.DeleteValue(to_delete[i].c_str());
101 void ReadSingleExitFunnel(
102 base::win::RegKey* parent_key, const base::char16* name,
103 std::vector<std::pair<base::string16, int64>>* events_out) {
104 DCHECK(parent_key);
105 DCHECK(name);
106 DCHECK(events_out);
108 base::win::RegKey regkey(parent_key->Handle(), name, KEY_READ | KEY_WRITE);
109 if (!regkey.Valid())
110 return;
112 // Exit early if no work to do.
113 size_t num = regkey.GetValueCount();
114 if (num == 0)
115 return;
117 // Enumerate the recorded events for this process for processing.
118 std::vector<std::pair<base::string16, int64>> events;
119 for (size_t i = 0; i < num; ++i) {
120 base::string16 event_name;
121 LONG res = regkey.GetValueNameAt(static_cast<int>(i), &event_name);
122 if (res == ERROR_SUCCESS) {
123 int64 event_time = 0;
124 res = regkey.ReadInt64(event_name.c_str(), &event_time);
125 if (res == ERROR_SUCCESS)
126 events.push_back(std::make_pair(event_name, event_time));
130 // Attempt to delete the values before reporting anything.
131 // Exit if this fails to make sure there is no double-reporting on e.g.
132 // permission problems or other corruption.
133 for (size_t i = 0; i < events.size(); ++i) {
134 const base::string16& event_name = events[i].first;
135 LONG res = regkey.DeleteValue(event_name.c_str());
136 if (res != ERROR_SUCCESS) {
137 LOG(ERROR) << "Failed to delete value " << event_name;
138 return;
142 events_out->swap(events);
145 void MaybeRecordSingleExitFunnel(base::win::RegKey* parent_key,
146 const base::char16* name,
147 bool report) {
148 std::vector<std::pair<base::string16, int64>> events;
149 ReadSingleExitFunnel(parent_key, name, &events);
150 if (!report)
151 return;
153 // Find the earliest event time.
154 int64 min_time = std::numeric_limits<int64>::max();
155 for (size_t i = 0; i < events.size(); ++i)
156 min_time = std::min(min_time, events[i].second);
158 // Record the exit funnel event times in a sparse stability histogram.
159 for (size_t i = 0; i < events.size(); ++i) {
160 std::string histogram_name(
161 WatcherMetricsProviderWin::kExitFunnelHistogramPrefix);
162 histogram_name.append(base::WideToUTF8(events[i].first));
163 base::TimeDelta event_time =
164 base::Time::FromInternalValue(events[i].second) -
165 base::Time::FromInternalValue(min_time);
166 base::HistogramBase* histogram =
167 base::SparseHistogram::FactoryGet(
168 histogram_name.c_str(),
169 base::HistogramBase::kUmaStabilityHistogramFlag);
171 // Record the time rounded up to the nearest millisecond.
172 histogram->Add(event_time.InMillisecondsRoundedUp());
176 void MaybeRecordExitFunnels(const base::string16& registry_path, bool report) {
177 base::win::RegistryKeyIterator it(HKEY_CURRENT_USER, registry_path.c_str());
178 if (!it.Valid())
179 return;
181 // Exit early if no work to do.
182 if (it.SubkeyCount() == 0)
183 return;
185 // Open the key we use for deletion preemptively to prevent reporting
186 // multiple times on permission problems.
187 base::win::RegKey key(HKEY_CURRENT_USER,
188 registry_path.c_str(),
189 KEY_QUERY_VALUE);
190 if (!key.Valid()) {
191 LOG(ERROR) << "Failed to open " << registry_path << " for writing.";
192 return;
195 std::vector<base::string16> to_delete;
196 for (; it.Valid(); ++it) {
197 // Defer reporting on still-live processes.
198 if (IsDeadProcess(it.Name())) {
199 MaybeRecordSingleExitFunnel(&key, it.Name(), report);
200 to_delete.push_back(it.Name());
204 for (size_t i = 0; i < to_delete.size(); ++i) {
205 LONG res = key.DeleteEmptyKey(to_delete[i].c_str());
206 if (res != ERROR_SUCCESS)
207 LOG(ERROR) << "Failed to delete key " << to_delete[i];
211 } // namespace
213 const char WatcherMetricsProviderWin::kBrowserExitCodeHistogramName[] =
214 "Stability.BrowserExitCodes";
215 const char WatcherMetricsProviderWin::kExitFunnelHistogramPrefix[] =
216 "Stability.ExitFunnel.";
218 WatcherMetricsProviderWin::WatcherMetricsProviderWin(
219 const base::char16* registry_path, bool report_exit_funnels) :
220 registry_path_(registry_path),
221 report_exit_funnels_(report_exit_funnels) {
224 WatcherMetricsProviderWin::~WatcherMetricsProviderWin() {
227 void WatcherMetricsProviderWin::ProvideStabilityMetrics(
228 metrics::SystemProfileProto* /* system_profile_proto */) {
229 // Note that if there are multiple instances of Chrome running in the same
230 // user account, there's a small race that will double-report the exit codes
231 // from both/multiple instances. This ought to be vanishingly rare and will
232 // only manifest as low-level "random" noise. To work around this it would be
233 // necessary to implement some form of global locking, which is not worth it
234 // here.
235 RecordExitCodes(registry_path_);
236 MaybeRecordExitFunnels(registry_path_, report_exit_funnels_);
239 } // namespace browser_watcher