1 // Copyright (c) 2012 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 // 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/bind.h"
18 #include "base/command_line.h"
19 #include "base/files/file_path.h"
20 #include "base/files/scoped_temp_dir.h"
21 #include "base/location.h"
22 #include "base/macros.h"
23 #include "base/memory/ref_counted.h"
24 #include "base/path_service.h"
25 #include "base/process/launch.h"
26 #include "base/process/process.h"
27 #include "base/process/process_iterator.h"
28 #include "base/single_thread_task_runner.h"
29 #include "base/synchronization/waitable_event.h"
30 #include "base/test/test_timeouts.h"
31 #include "base/threading/thread.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 // We must reset some data members since we reuse the same ChromeStarter
66 // object and start/stop it a few times. We must start fresh! :-)
70 if (process_.IsValid())
72 process_terminated_ = false;
75 void StartChrome(base::WaitableEvent* start_event, bool first_run) {
76 base::CommandLine command_line_for_relaunch(
77 initial_command_line_for_relaunch_.GetProgram());
78 test_launcher_utils::RemoveCommandLineSwitch(
79 initial_command_line_for_relaunch_, switches::kUserDataDir,
80 &command_line_for_relaunch);
81 command_line_for_relaunch.AppendSwitchPath(switches::kUserDataDir,
85 base::CommandLine tmp_command_line = command_line_for_relaunch;
86 test_launcher_utils::RemoveCommandLineSwitch(
87 tmp_command_line, switches::kNoFirstRun, &command_line_for_relaunch);
88 command_line_for_relaunch.AppendSwitch(switches::kForceFirstRun);
91 // Try to get all threads to launch the app at the same time.
92 // So let the test know we are ready.
93 ready_event_.Signal();
94 // And then wait for the test to tell us to GO!
95 ASSERT_NE(nullptr, start_event);
98 // Here we don't wait for the app to be terminated because one of the
99 // process will stay alive while the others will be restarted. If we would
100 // wait here, we would never get a handle to the main process...
102 base::LaunchProcess(command_line_for_relaunch, base::LaunchOptions());
103 ASSERT_TRUE(process_.IsValid());
105 // We can wait on the handle here, we should get stuck on one and only
106 // one process. The test below will take care of killing that process
107 // to unstuck us once it confirms there is only one.
108 process_terminated_ =
109 process_.WaitForExitWithTimeout(timeout_, &exit_code_);
110 // Let the test know we are done.
111 done_event_.Signal();
114 // Public access to simplify the test code using them.
115 base::WaitableEvent ready_event_;
116 base::WaitableEvent done_event_;
117 base::Process process_;
118 bool process_terminated_;
119 // Process exit code. Only meaningful if |process_terminated_| is true.
123 friend class base::RefCountedThreadSafe<ChromeStarter>;
127 base::TimeDelta timeout_;
128 base::FilePath user_data_dir_;
129 base::CommandLine initial_command_line_for_relaunch_;
131 DISALLOW_COPY_AND_ASSIGN(ChromeStarter);
136 // Our test fixture that initializes and holds onto a few global vars.
137 class ProcessSingletonTest : public InProcessBrowserTest {
139 ProcessSingletonTest()
140 // We use a manual reset so that all threads wake up at once when signaled
141 // and thus we must manually reset it for each attempt.
142 : threads_waker_(base::WaitableEvent::ResetPolicy::MANUAL,
143 base::WaitableEvent::InitialState::NOT_SIGNALED) {
144 EXPECT_TRUE(temp_profile_dir_.CreateUniqueTempDir());
147 void TearDown() override {
148 InProcessBrowserTest::TearDown();
150 for (size_t i = 0; i < kNbThreads; ++i)
151 chrome_starter_threads_[i]->Stop();
154 // This method is used to make sure we kill the main browser process after
155 // all of its child processes have successfully attached to it. This was added
156 // when we realized that if we just kill the parent process right away, we
157 // sometimes end up with dangling child processes. If we Sleep for a certain
158 // amount of time, we are OK... So we introduced this method to avoid a
159 // flaky wait. Instead, we kill all descendants of the main process after we
160 // killed it, relying on the fact that we can still get the parent id of a
161 // child process, even when the parent dies.
162 void KillProcessTree(const base::Process& process) {
163 class ProcessTreeFilter : public base::ProcessFilter {
165 explicit ProcessTreeFilter(base::ProcessId parent_pid) {
166 ancestor_pids_.insert(parent_pid);
168 bool Includes(const base::ProcessEntry& entry) const override {
169 if (ancestor_pids_.find(entry.parent_pid()) != ancestor_pids_.end()) {
170 ancestor_pids_.insert(entry.pid());
177 mutable std::set<base::ProcessId> ancestor_pids_;
178 } process_tree_filter(process.Pid());
180 // Start by explicitly killing the main process we know about...
181 static const int kExitCode = 42;
182 EXPECT_TRUE(process.Terminate(kExitCode, true /* wait */));
184 // Then loop until we can't find any of its descendant.
185 // But don't try more than kNbTries times...
186 static const int kNbTries = 10;
188 base::FilePath program;
189 ASSERT_TRUE(base::PathService::Get(base::FILE_EXE, &program));
190 base::FilePath::StringType exe_name = program.BaseName().value();
191 while (base::GetProcessCount(exe_name, &process_tree_filter) > 0 &&
192 num_tries++ < kNbTries) {
193 base::KillProcesses(exe_name, kExitCode, &process_tree_filter);
195 DLOG_IF(ERROR, num_tries >= kNbTries) << "Failed to kill all processes!";
198 // Since this is a hard to reproduce problem, we make a few attempts.
199 // We stop the attempts at the first error, and when there are no errors,
200 // we don't time-out of any wait, so it executes quite fast anyway.
201 static const size_t kNbAttempts = 5;
203 // The idea is to start chrome from multiple threads all at once.
204 static const size_t kNbThreads = 5;
205 scoped_refptr<ChromeStarter> chrome_starters_[kNbThreads];
206 std::unique_ptr<base::Thread> chrome_starter_threads_[kNbThreads];
208 // The event that will get all threads to wake up simultaneously and try
209 // to start a chrome process at the same time.
210 base::WaitableEvent threads_waker_;
212 // We don't want to use the default profile, but can't use UITest's since we
213 // don't use UITest::LaunchBrowser.
214 base::ScopedTempDir temp_profile_dir_;
217 // ChromeOS hits DCHECKS on ProcessSingleton rendezvous: crbug.com/782487
218 #if defined(OS_CHROMEOS) || defined(OS_LINUX) || defined(OS_WIN)
219 #define MAYBE_StartupRaceCondition DISABLED_StartupRaceCondition
221 #define MAYBE_StartupRaceCondition StartupRaceCondition
223 IN_PROC_BROWSER_TEST_F(ProcessSingletonTest, MAYBE_StartupRaceCondition) {
224 // Start the threads and create the starters.
225 for (size_t i = 0; i < kNbThreads; ++i) {
226 chrome_starter_threads_[i] =
227 std::make_unique<base::Thread>("ChromeStarter");
228 ASSERT_TRUE(chrome_starter_threads_[i]->Start());
229 chrome_starters_[i] = base::MakeRefCounted<ChromeStarter>(
230 TestTimeouts::action_max_timeout(), temp_profile_dir_.GetPath(),
231 GetCommandLineForRelaunch());
234 for (size_t attempt = 0; attempt < kNbAttempts && !HasFailure(); ++attempt) {
235 SCOPED_TRACE(testing::Message() << "Attempt: " << attempt << ".");
236 // We use a single event to get all threads to do the AppLaunch at the
238 threads_waker_.Reset();
240 // Test both with and without the first-run dialog, since they exercise
242 #if defined(OS_POSIX)
243 // TODO(mattm): test first run dialog singleton handling on linux too.
244 // On posix if we test the first run dialog, GracefulShutdownHandler gets
245 // the TERM signal, but since the message loop isn't running during the gtk
246 // first run dialog, the ShutdownDetector never handles it, and KillProcess
247 // has to time out (60 sec!) and SIGKILL.
248 bool first_run = false;
250 // Test for races in both regular start up and first run start up cases.
251 bool first_run = attempt % 2;
254 // Here we prime all the threads with a ChromeStarter that will wait for
255 // our signal to launch its chrome process.
256 for (size_t i = 0; i < kNbThreads; ++i) {
257 ASSERT_NE(static_cast<ChromeStarter*>(NULL), chrome_starters_[i].get());
258 chrome_starters_[i]->Reset();
260 ASSERT_TRUE(chrome_starter_threads_[i]->IsRunning());
261 ASSERT_TRUE(chrome_starter_threads_[i]->task_runner());
263 chrome_starter_threads_[i]->task_runner()->PostTask(
265 base::BindOnce(&ChromeStarter::StartChrome, chrome_starters_[i],
266 &threads_waker_, first_run));
269 // Wait for all the starters to be ready.
270 // We could replace this loop if we ever implement a WaitAll().
271 for (size_t i = 0; i < kNbThreads; ++i) {
272 SCOPED_TRACE(testing::Message() << "Waiting on thread: " << i << ".");
273 chrome_starters_[i]->ready_event_.Wait();
276 threads_waker_.Signal();
278 // As we wait for all threads to signal that they are done, we remove their
279 // index from this vector so that we get left with only the index of
280 // the thread that started the main process.
281 std::vector<size_t> pending_starters(kNbThreads);
282 for (size_t i = 0; i < kNbThreads; ++i)
283 pending_starters[i] = i;
285 // We use a local array of starter's done events we must wait on...
286 // These are collected from the starters that we have not yet been removed
287 // from the pending_starters vector.
288 base::WaitableEvent* starters_done_events[kNbThreads];
289 // At the end, "There can be only one" main browser process alive.
290 while (pending_starters.size() > 1) {
291 SCOPED_TRACE(testing::Message() << pending_starters.size() <<
293 for (size_t i = 0; i < pending_starters.size(); ++i) {
294 starters_done_events[i] =
295 &chrome_starters_[pending_starters[i]]->done_event_;
297 size_t done_index = base::WaitableEvent::WaitMany(
298 starters_done_events, pending_starters.size());
299 size_t starter_index = pending_starters[done_index];
300 // If the starter is done but has not marked itself as terminated,
301 // it is because it timed out of its WaitForExitCodeWithTimeout(). Only
302 // the last one standing should be left waiting... So we failed...
303 EXPECT_TRUE(chrome_starters_[starter_index]->process_terminated_)
304 << "There is more than one main process.";
305 if (chrome_starters_[starter_index]->process_terminated_) {
306 // Generally PROCESS_NOTIFIED would be the expected exit code. In some
307 // rare cases the ProcessSingleton race can result in PROFILE_IN_USE
308 // exit code, which we also allow, though it would be ideal if that
310 // TODO(mattm): investigate why PROFILE_IN_USE occurs sometimes.
312 chrome_starters_[starter_index]->exit_code_,
313 AnyOf(Eq(chrome::RESULT_CODE_PROFILE_IN_USE),
314 Eq(chrome::RESULT_CODE_NORMAL_EXIT_PROCESS_NOTIFIED)));
316 // But we let the last loop turn finish so that we can properly
317 // kill all remaining processes. Starting with this one...
318 if (chrome_starters_[starter_index]->process_.IsValid()) {
319 KillProcessTree(chrome_starters_[starter_index]->process_);
322 pending_starters.erase(pending_starters.begin() + done_index);
325 // "There can be only one!" :-)
326 ASSERT_EQ(static_cast<size_t>(1), pending_starters.size());
327 size_t last_index = pending_starters.front();
328 pending_starters.clear();
329 if (chrome_starters_[last_index]->process_.IsValid()) {
330 KillProcessTree(chrome_starters_[last_index]->process_);
331 chrome_starters_[last_index]->done_event_.Wait();