1 // Copyright 2012 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 // This test validates that the ProcessSingleton class properly makes sure
6 // that there is only one main browser process.
8 // It is currently compiled and run on Windows and Posix(non-Mac) platforms.
9 // Mac uses system services and ProcessSingletonMac is a noop. (Maybe it still
10 // makes sense to test that the system services are giving the behavior we
17 #include "base/command_line.h"
18 #include "base/files/file_path.h"
19 #include "base/files/scoped_temp_dir.h"
20 #include "base/functional/bind.h"
21 #include "base/location.h"
22 #include "base/memory/ref_counted.h"
23 #include "base/path_service.h"
24 #include "base/process/launch.h"
25 #include "base/process/process.h"
26 #include "base/process/process_iterator.h"
27 #include "base/synchronization/waitable_event.h"
28 #include "base/task/single_thread_task_runner.h"
29 #include "base/test/test_timeouts.h"
30 #include "base/threading/thread.h"
31 #include "base/time/time.h"
32 #include "build/build_config.h"
33 #include "chrome/common/chrome_constants.h"
34 #include "chrome/common/chrome_paths.h"
35 #include "chrome/common/chrome_result_codes.h"
36 #include "chrome/common/chrome_switches.h"
37 #include "chrome/test/base/in_process_browser_test.h"
38 #include "chrome/test/base/test_launcher_utils.h"
39 #include "content/public/test/browser_test.h"
40 #include "testing/gmock/include/gmock/gmock.h"
42 using ::testing::AnyOf;
47 // This is for the code that is to be ran in multiple threads at once,
48 // to stress a race condition on first process start.
49 // We use the thread safe ref counted base class so that we can use the
50 // base::Bind to run the StartChrome methods in many threads.
51 class ChromeStarter : public base::RefCountedThreadSafe<ChromeStarter> {
53 ChromeStarter(base::TimeDelta timeout,
54 const base::FilePath& user_data_dir,
55 const base::CommandLine& initial_command_line_for_relaunch)
56 : ready_event_(base::WaitableEvent::ResetPolicy::AUTOMATIC,
57 base::WaitableEvent::InitialState::NOT_SIGNALED),
58 done_event_(base::WaitableEvent::ResetPolicy::AUTOMATIC,
59 base::WaitableEvent::InitialState::NOT_SIGNALED),
60 process_terminated_(false),
62 user_data_dir_(user_data_dir),
63 initial_command_line_for_relaunch_(initial_command_line_for_relaunch) {}
65 ChromeStarter(const ChromeStarter&) = delete;
66 ChromeStarter& operator=(const ChromeStarter&) = delete;
68 // We must reset some data members since we reuse the same ChromeStarter
69 // object and start/stop it a few times. We must start fresh! :-)
73 if (process_.IsValid())
75 process_terminated_ = false;
78 void StartChrome(base::WaitableEvent* start_event, bool first_run) {
79 base::CommandLine command_line_for_relaunch(
80 initial_command_line_for_relaunch_.GetProgram());
81 test_launcher_utils::RemoveCommandLineSwitch(
82 initial_command_line_for_relaunch_, switches::kUserDataDir,
83 &command_line_for_relaunch);
84 command_line_for_relaunch.AppendSwitchPath(switches::kUserDataDir,
88 base::CommandLine tmp_command_line = command_line_for_relaunch;
89 test_launcher_utils::RemoveCommandLineSwitch(
90 tmp_command_line, switches::kNoFirstRun, &command_line_for_relaunch);
91 command_line_for_relaunch.AppendSwitch(switches::kForceFirstRun);
94 // Try to get all threads to launch the app at the same time.
95 // So let the test know we are ready.
96 ready_event_.Signal();
97 // And then wait for the test to tell us to GO!
98 ASSERT_NE(nullptr, start_event);
101 // Here we don't wait for the app to be terminated because one of the
102 // process will stay alive while the others will be restarted. If we would
103 // wait here, we would never get a handle to the main process...
105 base::LaunchProcess(command_line_for_relaunch, base::LaunchOptions());
106 ASSERT_TRUE(process_.IsValid());
108 // We can wait on the handle here, we should get stuck on one and only
109 // one process. The test below will take care of killing that process
110 // to unstuck us once it confirms there is only one.
111 process_terminated_ =
112 process_.WaitForExitWithTimeout(timeout_, &exit_code_);
113 // Let the test know we are done.
114 done_event_.Signal();
117 // Public access to simplify the test code using them.
118 base::WaitableEvent ready_event_;
119 base::WaitableEvent done_event_;
120 base::Process process_;
121 bool process_terminated_;
122 // Process exit code. Only meaningful if |process_terminated_| is true.
126 friend class base::RefCountedThreadSafe<ChromeStarter>;
130 base::TimeDelta timeout_;
131 base::FilePath user_data_dir_;
132 base::CommandLine initial_command_line_for_relaunch_;
137 // Our test fixture that initializes and holds onto a few global vars.
138 class ProcessSingletonTest : public InProcessBrowserTest {
140 ProcessSingletonTest()
141 // We use a manual reset so that all threads wake up at once when signaled
142 // and thus we must manually reset it for each attempt.
143 : threads_waker_(base::WaitableEvent::ResetPolicy::MANUAL,
144 base::WaitableEvent::InitialState::NOT_SIGNALED) {
145 EXPECT_TRUE(temp_profile_dir_.CreateUniqueTempDir());
148 void TearDown() override {
149 InProcessBrowserTest::TearDown();
151 for (size_t i = 0; i < kNbThreads; ++i)
152 chrome_starter_threads_[i]->Stop();
155 // This method is used to make sure we kill the main browser process after
156 // all of its child processes have successfully attached to it. This was added
157 // when we realized that if we just kill the parent process right away, we
158 // sometimes end up with dangling child processes. If we Sleep for a certain
159 // amount of time, we are OK... So we introduced this method to avoid a
160 // flaky wait. Instead, we kill all descendants of the main process after we
161 // killed it, relying on the fact that we can still get the parent id of a
162 // child process, even when the parent dies.
163 void KillProcessTree(const base::Process& process) {
164 class ProcessTreeFilter : public base::ProcessFilter {
166 explicit ProcessTreeFilter(base::ProcessId parent_pid) {
167 ancestor_pids_.insert(parent_pid);
169 bool Includes(const base::ProcessEntry& entry) const override {
170 if (ancestor_pids_.find(entry.parent_pid()) != ancestor_pids_.end()) {
171 ancestor_pids_.insert(entry.pid());
178 mutable std::set<base::ProcessId> ancestor_pids_;
179 } process_tree_filter(process.Pid());
181 // Start by explicitly killing the main process we know about...
182 static const int kExitCode = 42;
183 EXPECT_TRUE(process.Terminate(kExitCode, true /* wait */));
185 // Then loop until we can't find any of its descendant.
186 // But don't try more than kNbTries times...
187 static const int kNbTries = 10;
189 base::FilePath program;
190 ASSERT_TRUE(base::PathService::Get(base::FILE_EXE, &program));
191 base::FilePath::StringType exe_name = program.BaseName().value();
192 while (base::GetProcessCount(exe_name, &process_tree_filter) > 0 &&
193 num_tries++ < kNbTries) {
194 base::KillProcesses(exe_name, kExitCode, &process_tree_filter);
196 DLOG_IF(ERROR, num_tries >= kNbTries) << "Failed to kill all processes!";
199 // Since this is a hard to reproduce problem, we make a few attempts.
200 // We stop the attempts at the first error, and when there are no errors,
201 // we don't time-out of any wait, so it executes quite fast anyway.
202 static const size_t kNbAttempts = 5;
204 // The idea is to start chrome from multiple threads all at once.
205 static const size_t kNbThreads = 5;
206 scoped_refptr<ChromeStarter> chrome_starters_[kNbThreads];
207 std::unique_ptr<base::Thread> chrome_starter_threads_[kNbThreads];
209 // The event that will get all threads to wake up simultaneously and try
210 // to start a chrome process at the same time.
211 base::WaitableEvent threads_waker_;
213 // We don't want to use the default profile, but can't use UITest's since we
214 // don't use UITest::LaunchBrowser.
215 base::ScopedTempDir temp_profile_dir_;
218 // ChromeOS hits DCHECKS on ProcessSingleton rendezvous: crbug.com/782487
219 #if BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN)
220 #define MAYBE_StartupRaceCondition DISABLED_StartupRaceCondition
222 #define MAYBE_StartupRaceCondition StartupRaceCondition
224 IN_PROC_BROWSER_TEST_F(ProcessSingletonTest, MAYBE_StartupRaceCondition) {
225 // Start the threads and create the starters.
226 for (size_t i = 0; i < kNbThreads; ++i) {
227 chrome_starter_threads_[i] =
228 std::make_unique<base::Thread>("ChromeStarter");
229 ASSERT_TRUE(chrome_starter_threads_[i]->Start());
230 chrome_starters_[i] = base::MakeRefCounted<ChromeStarter>(
231 TestTimeouts::action_max_timeout(), temp_profile_dir_.GetPath(),
232 GetCommandLineForRelaunch());
235 for (size_t attempt = 0; attempt < kNbAttempts && !HasFailure(); ++attempt) {
236 SCOPED_TRACE(testing::Message() << "Attempt: " << attempt << ".");
237 // We use a single event to get all threads to do the AppLaunch at the
239 threads_waker_.Reset();
241 // Test both with and without the first-run dialog, since they exercise
243 #if BUILDFLAG(IS_POSIX)
244 // TODO(mattm): test first run dialog singleton handling on linux too.
245 // On posix if we test the first run dialog, GracefulShutdownHandler gets
246 // the TERM signal, but since the message loop isn't running during the gtk
247 // first run dialog, the ShutdownDetector never handles it, and KillProcess
248 // has to time out (60 sec!) and SIGKILL.
249 bool first_run = false;
251 // Test for races in both regular start up and first run start up cases.
252 bool first_run = attempt % 2;
255 // Here we prime all the threads with a ChromeStarter that will wait for
256 // our signal to launch its chrome process.
257 for (size_t i = 0; i < kNbThreads; ++i) {
258 ASSERT_NE(static_cast<ChromeStarter*>(nullptr),
259 chrome_starters_[i].get());
260 chrome_starters_[i]->Reset();
262 ASSERT_TRUE(chrome_starter_threads_[i]->IsRunning());
263 ASSERT_TRUE(chrome_starter_threads_[i]->task_runner());
265 chrome_starter_threads_[i]->task_runner()->PostTask(
267 base::BindOnce(&ChromeStarter::StartChrome, chrome_starters_[i],
268 &threads_waker_, first_run));
271 // Wait for all the starters to be ready.
272 // We could replace this loop if we ever implement a WaitAll().
273 for (size_t i = 0; i < kNbThreads; ++i) {
274 SCOPED_TRACE(testing::Message() << "Waiting on thread: " << i << ".");
275 chrome_starters_[i]->ready_event_.Wait();
278 threads_waker_.Signal();
280 // As we wait for all threads to signal that they are done, we remove their
281 // index from this vector so that we get left with only the index of
282 // the thread that started the main process.
283 std::vector<size_t> pending_starters(kNbThreads);
284 for (size_t i = 0; i < kNbThreads; ++i)
285 pending_starters[i] = i;
287 // We use a local array of starter's done events we must wait on...
288 // These are collected from the starters that we have not yet been removed
289 // from the pending_starters vector.
290 base::WaitableEvent* starters_done_events[kNbThreads];
291 // At the end, "There can be only one" main browser process alive.
292 while (pending_starters.size() > 1) {
293 SCOPED_TRACE(testing::Message() << pending_starters.size() <<
295 for (size_t i = 0; i < pending_starters.size(); ++i) {
296 starters_done_events[i] =
297 &chrome_starters_[pending_starters[i]]->done_event_;
299 size_t done_index = base::WaitableEvent::WaitMany(
300 starters_done_events, pending_starters.size());
301 size_t starter_index = pending_starters[done_index];
302 // If the starter is done but has not marked itself as terminated,
303 // it is because it timed out of its WaitForExitCodeWithTimeout(). Only
304 // the last one standing should be left waiting... So we failed...
305 EXPECT_TRUE(chrome_starters_[starter_index]->process_terminated_)
306 << "There is more than one main process.";
307 if (chrome_starters_[starter_index]->process_terminated_) {
308 // Generally PROCESS_NOTIFIED would be the expected exit code. In some
309 // rare cases the ProcessSingleton race can result in PROFILE_IN_USE
310 // exit code, which we also allow, though it would be ideal if that
312 // TODO(mattm): investigate why PROFILE_IN_USE occurs sometimes.
314 chrome_starters_[starter_index]->exit_code_,
315 AnyOf(Eq(chrome::RESULT_CODE_PROFILE_IN_USE),
316 Eq(chrome::RESULT_CODE_NORMAL_EXIT_PROCESS_NOTIFIED)));
318 // But we let the last loop turn finish so that we can properly
319 // kill all remaining processes. Starting with this one...
320 if (chrome_starters_[starter_index]->process_.IsValid()) {
321 KillProcessTree(chrome_starters_[starter_index]->process_);
324 pending_starters.erase(pending_starters.begin() + done_index);
327 // "There can be only one!" :-)
328 ASSERT_EQ(static_cast<size_t>(1), pending_starters.size());
329 size_t last_index = pending_starters.front();
330 pending_starters.clear();
331 if (chrome_starters_[last_index]->process_.IsValid()) {
332 KillProcessTree(chrome_starters_[last_index]->process_);
333 chrome_starters_[last_index]->done_event_.Wait();