blob: 3e7dc42ac3e55f0ef32304a2bd1da1197ab36c64 [file] [log] [blame]
[email protected]697c7422012-04-11 16:27:011// Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]bbef41f02010-03-04 16:16:192// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5// This test validates that the ProcessSingleton class properly makes sure
6// that there is only one main browser process.
7//
[email protected]bf4878d2010-06-16 20:12:018// 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
11// want?)
[email protected]bbef41f02010-03-04 16:16:1912
avib896c712015-12-26 02:10:4313#include <stddef.h>
14
dchengc0e39d572016-04-19 06:15:1715#include <memory>
16
[email protected]0b05881d32011-11-17 00:44:0117#include "base/bind.h"
[email protected]77caa662012-04-23 15:40:4618#include "base/command_line.h"
[email protected]57999812013-02-24 05:40:5219#include "base/files/file_path.h"
[email protected]ea1a3f62012-11-16 20:34:2320#include "base/files/scoped_temp_dir.h"
skyostil02598352015-06-12 12:37:2521#include "base/location.h"
avib896c712015-12-26 02:10:4322#include "base/macros.h"
[email protected]3b63f8f42011-03-28 01:54:1523#include "base/memory/ref_counted.h"
[email protected]bf4878d2010-06-16 20:12:0124#include "base/path_service.h"
[email protected]d09a4ce1c2013-07-24 17:37:0225#include "base/process/launch.h"
rvargas0f950b52015-01-05 20:37:3826#include "base/process/process.h"
[email protected]d09a4ce1c2013-07-24 17:37:0227#include "base/process/process_iterator.h"
skyostil02598352015-06-12 12:37:2528#include "base/single_thread_task_runner.h"
[email protected]44f9c952011-01-02 06:05:3929#include "base/synchronization/waitable_event.h"
[email protected]e0785902011-05-19 23:34:1730#include "base/test/test_timeouts.h"
31#include "base/threading/thread.h"
avib896c712015-12-26 02:10:4332#include "build/build_config.h"
[email protected]bbef41f02010-03-04 16:16:1933#include "chrome/common/chrome_constants.h"
[email protected]e0785902011-05-19 23:34:1734#include "chrome/common/chrome_paths.h"
[email protected]bf4878d2010-06-16 20:12:0135#include "chrome/common/chrome_switches.h"
[email protected]77caa662012-04-23 15:40:4636#include "chrome/test/base/in_process_browser_test.h"
[email protected]ea1a3f62012-11-16 20:34:2337#include "chrome/test/base/test_launcher_utils.h"
[email protected]bbef41f02010-03-04 16:16:1938
39namespace {
40
41// This is for the code that is to be ran in multiple threads at once,
42// to stress a race condition on first process start.
43// We use the thread safe ref counted base class so that we can use the
[email protected]0b05881d32011-11-17 00:44:0144// base::Bind to run the StartChrome methods in many threads.
[email protected]bbef41f02010-03-04 16:16:1945class ChromeStarter : public base::RefCountedThreadSafe<ChromeStarter> {
46 public:
[email protected]650b2d52013-02-10 03:41:4547 ChromeStarter(base::TimeDelta timeout, const base::FilePath& user_data_dir)
gabd955d78d2016-06-04 13:15:3848 : ready_event_(base::WaitableEvent::ResetPolicy::AUTOMATIC,
49 base::WaitableEvent::InitialState::NOT_SIGNALED),
50 done_event_(base::WaitableEvent::ResetPolicy::AUTOMATIC,
51 base::WaitableEvent::InitialState::NOT_SIGNALED),
[email protected]0e60b642010-03-30 10:21:2752 process_terminated_(false),
[email protected]8270c6fe2012-07-09 19:59:2153 timeout_(timeout),
gabd955d78d2016-06-04 13:15:3854 user_data_dir_(user_data_dir) {}
[email protected]bbef41f02010-03-04 16:16:1955
56 // We must reset some data members since we reuse the same ChromeStarter
57 // object and start/stop it a few times. We must start fresh! :-)
58 void Reset() {
59 ready_event_.Reset();
60 done_event_.Reset();
rvargas0f950b52015-01-05 20:37:3861 if (process_.IsValid())
62 process_.Close();
[email protected]bbef41f02010-03-04 16:16:1963 process_terminated_ = false;
64 }
65
[email protected]bf4878d2010-06-16 20:12:0166 void StartChrome(base::WaitableEvent* start_event, bool first_run) {
67 // TODO(mattm): maybe stuff should be refactored to use
68 // UITest::LaunchBrowserHelper somehow?
[email protected]650b2d52013-02-10 03:41:4569 base::FilePath program;
[email protected]77caa662012-04-23 15:40:4670 ASSERT_TRUE(PathService::Get(base::FILE_EXE, &program));
avi556c05022014-12-22 23:31:4371 base::CommandLine command_line(program);
[email protected]1a30a2f32010-10-06 02:03:0472 command_line.AppendSwitchPath(switches::kUserDataDir, user_data_dir_);
[email protected]bf4878d2010-06-16 20:12:0173
74 if (first_run)
[email protected]3f002a32013-01-02 17:52:3875 command_line.AppendSwitch(switches::kForceFirstRun);
[email protected]bf4878d2010-06-16 20:12:0176 else
77 command_line.AppendSwitch(switches::kNoFirstRun);
[email protected]bbef41f02010-03-04 16:16:1978
[email protected]1a30a2f32010-10-06 02:03:0479 // Add the normal test-mode switches, except for the ones we're adding
80 // ourselves.
avi556c05022014-12-22 23:31:4381 base::CommandLine standard_switches(base::CommandLine::NO_PROGRAM);
[email protected]1a30a2f32010-10-06 02:03:0482 test_launcher_utils::PrepareBrowserCommandLineForTests(&standard_switches);
avi556c05022014-12-22 23:31:4383 const base::CommandLine::SwitchMap& switch_map =
84 standard_switches.GetSwitches();
85 for (base::CommandLine::SwitchMap::const_iterator i = switch_map.begin();
[email protected]1a30a2f32010-10-06 02:03:0486 i != switch_map.end(); ++i) {
87 const std::string& switch_name = i->first;
88 if (switch_name == switches::kUserDataDir ||
[email protected]3f002a32013-01-02 17:52:3889 switch_name == switches::kForceFirstRun ||
[email protected]1a30a2f32010-10-06 02:03:0490 switch_name == switches::kNoFirstRun)
91 continue;
92
93 command_line.AppendSwitchNative(switch_name, i->second);
94 }
95
[email protected]bbef41f02010-03-04 16:16:1996 // Try to get all threads to launch the app at the same time.
97 // So let the test know we are ready.
98 ready_event_.Signal();
99 // And then wait for the test to tell us to GO!
100 ASSERT_NE(static_cast<base::WaitableEvent*>(NULL), start_event);
[email protected]866cf332011-10-12 03:09:42101 start_event->Wait();
[email protected]bbef41f02010-03-04 16:16:19102
103 // Here we don't wait for the app to be terminated because one of the
104 // process will stay alive while the others will be restarted. If we would
105 // wait here, we would never get a handle to the main process...
rvargas0f950b52015-01-05 20:37:38106 process_ = base::LaunchProcess(command_line, base::LaunchOptions());
107 ASSERT_TRUE(process_.IsValid());
[email protected]bbef41f02010-03-04 16:16:19108
109 // We can wait on the handle here, we should get stuck on one and only
110 // one process. The test below will take care of killing that process
111 // to unstuck us once it confirms there is only one.
rvargas2f70a152015-02-24 00:28:11112 int exit_code;
113 process_terminated_ = process_.WaitForExitWithTimeout(timeout_, &exit_code);
[email protected]bbef41f02010-03-04 16:16:19114 // Let the test know we are done.
115 done_event_.Signal();
116 }
117
118 // Public access to simplify the test code using them.
119 base::WaitableEvent ready_event_;
120 base::WaitableEvent done_event_;
rvargas0f950b52015-01-05 20:37:38121 base::Process process_;
[email protected]bbef41f02010-03-04 16:16:19122 bool process_terminated_;
123
124 private:
125 friend class base::RefCountedThreadSafe<ChromeStarter>;
[email protected]0e60b642010-03-30 10:21:27126
rvargas0f950b52015-01-05 20:37:38127 ~ChromeStarter() {}
[email protected]0e60b642010-03-30 10:21:27128
[email protected]8270c6fe2012-07-09 19:59:21129 base::TimeDelta timeout_;
[email protected]650b2d52013-02-10 03:41:45130 base::FilePath user_data_dir_;
[email protected]0e60b642010-03-30 10:21:27131
[email protected]bbef41f02010-03-04 16:16:19132 DISALLOW_COPY_AND_ASSIGN(ChromeStarter);
133};
134
[email protected]77caa662012-04-23 15:40:46135} // namespace
136
[email protected]bbef41f02010-03-04 16:16:19137// Our test fixture that initializes and holds onto a few global vars.
[email protected]77caa662012-04-23 15:40:46138class ProcessSingletonTest : public InProcessBrowserTest {
[email protected]bbef41f02010-03-04 16:16:19139 public:
[email protected]bf4878d2010-06-16 20:12:01140 ProcessSingletonTest()
[email protected]bbef41f02010-03-04 16:16:19141 // 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.
gabd955d78d2016-06-04 13:15:38143 : threads_waker_(base::WaitableEvent::ResetPolicy::MANUAL,
144 base::WaitableEvent::InitialState::NOT_SIGNALED) {
[email protected]2d57f5d2011-01-13 14:20:12145 EXPECT_TRUE(temp_profile_dir_.CreateUniqueTempDir());
[email protected]bbef41f02010-03-04 16:16:19146 }
147
dchenge1bc7982014-10-30 00:32:40148 void SetUp() override {
pvalenzuela6ef14722015-07-28 20:02:41149 InProcessBrowserTest::SetUp();
[email protected]bbef41f02010-03-04 16:16:19150 // Start the threads and create the starters.
151 for (size_t i = 0; i < kNbThreads; ++i) {
152 chrome_starter_threads_[i].reset(new base::Thread("ChromeStarter"));
153 ASSERT_TRUE(chrome_starter_threads_[i]->Start());
[email protected]d64295932011-01-19 22:37:31154 chrome_starters_[i] = new ChromeStarter(
vabr8023d872016-09-15 08:12:22155 TestTimeouts::action_max_timeout(), temp_profile_dir_.GetPath());
[email protected]bbef41f02010-03-04 16:16:19156 }
157 }
158
dchenge1bc7982014-10-30 00:32:40159 void TearDown() override {
[email protected]bbef41f02010-03-04 16:16:19160 // Stop the threads.
161 for (size_t i = 0; i < kNbThreads; ++i)
162 chrome_starter_threads_[i]->Stop();
163 }
164
165 // This method is used to make sure we kill the main browser process after
166 // all of its child processes have successfully attached to it. This was added
167 // when we realized that if we just kill the parent process right away, we
168 // sometimes end up with dangling child processes. If we Sleep for a certain
169 // amount of time, we are OK... So we introduced this method to avoid a
170 // flaky wait. Instead, we kill all descendants of the main process after we
171 // killed it, relying on the fact that we can still get the parent id of a
172 // child process, even when the parent dies.
rvargas486b2f562015-03-18 01:36:33173 void KillProcessTree(const base::Process& process) {
[email protected]bbef41f02010-03-04 16:16:19174 class ProcessTreeFilter : public base::ProcessFilter {
175 public:
176 explicit ProcessTreeFilter(base::ProcessId parent_pid) {
177 ancestor_pids_.insert(parent_pid);
178 }
dchenge1bc7982014-10-30 00:32:40179 bool Includes(const base::ProcessEntry& entry) const override {
[email protected]b6128aa2010-04-29 17:44:42180 if (ancestor_pids_.find(entry.parent_pid()) != ancestor_pids_.end()) {
181 ancestor_pids_.insert(entry.pid());
[email protected]bbef41f02010-03-04 16:16:19182 return true;
183 } else {
184 return false;
185 }
186 }
187 private:
188 mutable std::set<base::ProcessId> ancestor_pids_;
rvargas486b2f562015-03-18 01:36:33189 } process_tree_filter(process.Pid());
[email protected]bbef41f02010-03-04 16:16:19190
191 // Start by explicitly killing the main process we know about...
192 static const int kExitCode = 42;
rvargas486b2f562015-03-18 01:36:33193 EXPECT_TRUE(process.Terminate(kExitCode, true /* wait */));
[email protected]bbef41f02010-03-04 16:16:19194
195 // Then loop until we can't find any of its descendant.
196 // But don't try more than kNbTries times...
197 static const int kNbTries = 10;
198 int num_tries = 0;
[email protected]650b2d52013-02-10 03:41:45199 base::FilePath program;
[email protected]77caa662012-04-23 15:40:46200 ASSERT_TRUE(PathService::Get(base::FILE_EXE, &program));
[email protected]650b2d52013-02-10 03:41:45201 base::FilePath::StringType exe_name = program.BaseName().value();
[email protected]77caa662012-04-23 15:40:46202 while (base::GetProcessCount(exe_name, &process_tree_filter) > 0 &&
203 num_tries++ < kNbTries) {
204 base::KillProcesses(exe_name, kExitCode, &process_tree_filter);
[email protected]bbef41f02010-03-04 16:16:19205 }
206 DLOG_IF(ERROR, num_tries >= kNbTries) << "Failed to kill all processes!";
207 }
208
209 // Since this is a hard to reproduce problem, we make a few attempts.
210 // We stop the attempts at the first error, and when there are no errors,
211 // we don't time-out of any wait, so it executes quite fast anyway.
212 static const size_t kNbAttempts = 5;
213
214 // The idea is to start chrome from multiple threads all at once.
215 static const size_t kNbThreads = 5;
216 scoped_refptr<ChromeStarter> chrome_starters_[kNbThreads];
dcheng4af48582016-04-19 00:29:35217 std::unique_ptr<base::Thread> chrome_starter_threads_[kNbThreads];
[email protected]bbef41f02010-03-04 16:16:19218
219 // The event that will get all threads to wake up simultaneously and try
220 // to start a chrome process at the same time.
221 base::WaitableEvent threads_waker_;
[email protected]1a30a2f32010-10-06 02:03:04222
223 // We don't want to use the default profile, but can't use UITest's since we
224 // don't use UITest::LaunchBrowser.
[email protected]ea1a3f62012-11-16 20:34:23225 base::ScopedTempDir temp_profile_dir_;
[email protected]bbef41f02010-03-04 16:16:19226};
227
pvalenzuela6ef14722015-07-28 20:02:41228// Disabled on all platforms after code rot due to http://crbug.com/513534.
229// Originally disabled on some platforms due to http://crbug.com/58219.
230IN_PROC_BROWSER_TEST_F(ProcessSingletonTest, DISABLED_StartupRaceCondition) {
[email protected]bbef41f02010-03-04 16:16:19231 // We use this to stop the attempts loop on the first failure.
232 bool failed = false;
233 for (size_t attempt = 0; attempt < kNbAttempts && !failed; ++attempt) {
234 SCOPED_TRACE(testing::Message() << "Attempt: " << attempt << ".");
235 // We use a single event to get all threads to do the AppLaunch at the same
236 // time...
237 threads_waker_.Reset();
238
[email protected]bf4878d2010-06-16 20:12:01239 // Test both with and without the first-run dialog, since they exercise
240 // different paths.
241#if defined(OS_POSIX)
242 // TODO(mattm): test first run dialog singleton handling on linux too.
243 // On posix if we test the first run dialog, GracefulShutdownHandler gets
244 // the TERM signal, but since the message loop isn't running during the gtk
245 // first run dialog, the ShutdownDetector never handles it, and KillProcess
246 // has to time out (60 sec!) and SIGKILL.
247 bool first_run = false;
248#else
249 // Test for races in both regular start up and first run start up cases.
250 bool first_run = attempt % 2;
251#endif
252
[email protected]bbef41f02010-03-04 16:16:19253 // Here we prime all the threads with a ChromeStarter that will wait for
254 // our signal to launch its chrome process.
255 for (size_t i = 0; i < kNbThreads; ++i) {
256 ASSERT_NE(static_cast<ChromeStarter*>(NULL), chrome_starters_[i].get());
257 chrome_starters_[i]->Reset();
258
259 ASSERT_TRUE(chrome_starter_threads_[i]->IsRunning());
[email protected]b3a25092013-05-28 22:08:16260 ASSERT_NE(static_cast<base::MessageLoop*>(NULL),
[email protected]bbef41f02010-03-04 16:16:19261 chrome_starter_threads_[i]->message_loop());
262
skyostil02598352015-06-12 12:37:25263 chrome_starter_threads_[i]->task_runner()->PostTask(
264 FROM_HERE,
tzik07cace42016-09-01 04:21:25265 base::Bind(&ChromeStarter::StartChrome, chrome_starters_[i],
skyostil02598352015-06-12 12:37:25266 &threads_waker_, first_run));
[email protected]bbef41f02010-03-04 16:16:19267 }
268
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 << ".");
[email protected]866cf332011-10-12 03:09:42273 chrome_starters_[i]->ready_event_.Wait();
[email protected]bbef41f02010-03-04 16:16:19274 }
275 // GO!
276 threads_waker_.Signal();
277
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;
284
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() <<
292 " starters left.");
293 for (size_t i = 0; i < pending_starters.size(); ++i) {
294 starters_done_events[i] =
295 &chrome_starters_[pending_starters[i]]->done_event_;
296 }
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,
rvargas2f70a152015-02-24 00:28:11301 // it is because it timed out of its WaitForExitCodeWithTimeout(). Only
302 // the last one standing should be left waiting... So we failed...
[email protected]bbef41f02010-03-04 16:16:19303 EXPECT_TRUE(chrome_starters_[starter_index]->process_terminated_ ||
304 failed) << "There is more than one main process.";
305 if (!chrome_starters_[starter_index]->process_terminated_) {
306 // This will stop the "for kNbAttempts" loop.
307 failed = true;
308 // But we let the last loop turn finish so that we can properly
309 // kill all remaining processes. Starting with this one...
rvargas0f950b52015-01-05 20:37:38310 if (chrome_starters_[starter_index]->process_.IsValid()) {
rvargas486b2f562015-03-18 01:36:33311 KillProcessTree(chrome_starters_[starter_index]->process_);
[email protected]bbef41f02010-03-04 16:16:19312 }
313 }
314 pending_starters.erase(pending_starters.begin() + done_index);
315 }
316
317 // "There can be only one!" :-)
318 ASSERT_EQ(static_cast<size_t>(1), pending_starters.size());
319 size_t last_index = pending_starters.front();
[email protected]697c7422012-04-11 16:27:01320 pending_starters.clear();
rvargas0f950b52015-01-05 20:37:38321 if (chrome_starters_[last_index]->process_.IsValid()) {
rvargas486b2f562015-03-18 01:36:33322 KillProcessTree(chrome_starters_[last_index]->process_);
[email protected]bbef41f02010-03-04 16:16:19323 chrome_starters_[last_index]->done_event_.Wait();
324 }
325 }
326}