1 // Copyright 2014 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.
5 #include "chrome/app/exit_code_watcher_win.h"
11 #include "base/check.h"
12 #include "base/functional/bind.h"
13 #include "base/message_loop/message_pump_type.h"
14 #include "base/metrics/histogram_base.h"
15 #include "base/metrics/sparse_histogram.h"
16 #include "base/process/process.h"
17 #include "base/process/process_handle.h"
18 #include "base/task/sequenced_task_runner.h"
19 #include "base/threading/thread.h"
20 #include "base/win/scoped_handle.h"
24 constexpr char kBrowserExitCodeHistogramName[] = "Stability.BrowserExitCodes";
26 bool WriteProcessExitCode(int exit_code) {
27 if (exit_code != STILL_ACTIVE) {
28 // Record the exit codes in a sparse stability histogram, as the range of
29 // values used to report failures is large.
30 base::HistogramBase* exit_code_histogram =
31 base::SparseHistogram::FactoryGet(
32 kBrowserExitCodeHistogramName,
33 base::HistogramBase::kUmaStabilityHistogramFlag);
34 exit_code_histogram->Add(exit_code);
42 ExitCodeWatcher::ExitCodeWatcher()
43 : background_thread_("ExitCodeWatcherThread"),
44 exit_code_(STILL_ACTIVE),
45 stop_watching_handle_(::CreateEvent(nullptr, TRUE, FALSE, nullptr)) {
46 DCHECK(stop_watching_handle_.IsValid());
49 ExitCodeWatcher::~ExitCodeWatcher() = default;
51 bool ExitCodeWatcher::Initialize(base::Process process) {
52 if (!process.IsValid()) {
56 DWORD process_pid = process.Pid();
57 if (process_pid == 0) {
61 FILETIME creation_time = {};
63 if (!::GetProcessTimes(process.Handle(), &creation_time, &dummy, &dummy,
68 // Success, take ownership of the process.
69 process_ = std::move(process);
73 bool ExitCodeWatcher::StartWatching() {
74 if (!background_thread_.StartWithOptions(
75 base::Thread::Options(base::MessagePumpType::IO, 0))) {
79 // Unretained is safe because `this` owns the thread.
80 if (!background_thread_.task_runner()->PostTask(
81 FROM_HERE, base::BindOnce(&ExitCodeWatcher::WaitForExit,
82 base::Unretained(this)))) {
83 background_thread_.Stop();
90 void ExitCodeWatcher::StopWatching() {
91 if (stop_watching_handle_.IsValid()) {
92 ::SetEvent(stop_watching_handle_.Get());
96 void ExitCodeWatcher::WaitForExit() {
97 base::Process::WaitExitStatus wait_result =
98 process_.WaitForExitOrEvent(stop_watching_handle_, &exit_code_);
99 if (wait_result == base::Process::WaitExitStatus::PROCESS_EXITED) {
100 WriteProcessExitCode(exit_code_);