Add a FrameHostMsg_BeginNavigation IPC
[chromium-blink-merge.git] / base / process / process_util_unittest.cc
blob20623a60e18a6cfba0bbe86721ceb718cde91d84
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 #define _CRT_SECURE_NO_WARNINGS
7 #include <limits>
9 #include "base/command_line.h"
10 #include "base/debug/alias.h"
11 #include "base/debug/stack_trace.h"
12 #include "base/files/file_path.h"
13 #include "base/logging.h"
14 #include "base/memory/scoped_ptr.h"
15 #include "base/path_service.h"
16 #include "base/posix/eintr_wrapper.h"
17 #include "base/process/kill.h"
18 #include "base/process/launch.h"
19 #include "base/process/memory.h"
20 #include "base/process/process.h"
21 #include "base/process/process_metrics.h"
22 #include "base/strings/string_number_conversions.h"
23 #include "base/strings/utf_string_conversions.h"
24 #include "base/synchronization/waitable_event.h"
25 #include "base/test/multiprocess_test.h"
26 #include "base/test/test_timeouts.h"
27 #include "base/third_party/dynamic_annotations/dynamic_annotations.h"
28 #include "base/threading/platform_thread.h"
29 #include "base/threading/thread.h"
30 #include "testing/gtest/include/gtest/gtest.h"
31 #include "testing/multiprocess_func_list.h"
33 #if defined(OS_LINUX)
34 #include <malloc.h>
35 #include <sched.h>
36 #endif
37 #if defined(OS_POSIX)
38 #include <dlfcn.h>
39 #include <errno.h>
40 #include <fcntl.h>
41 #include <signal.h>
42 #include <sys/resource.h>
43 #include <sys/socket.h>
44 #include <sys/wait.h>
45 #endif
46 #if defined(OS_WIN)
47 #include <windows.h>
48 #include "base/win/windows_version.h"
49 #endif
50 #if defined(OS_MACOSX)
51 #include <mach/vm_param.h>
52 #include <malloc/malloc.h>
53 #endif
55 using base::FilePath;
57 namespace {
59 #if defined(OS_ANDROID)
60 const char kShellPath[] = "/system/bin/sh";
61 const char kPosixShell[] = "sh";
62 #else
63 const char kShellPath[] = "/bin/sh";
64 const char kPosixShell[] = "bash";
65 #endif
67 const char kSignalFileSlow[] = "SlowChildProcess.die";
68 const char kSignalFileKill[] = "KilledChildProcess.die";
70 #if defined(OS_WIN)
71 const int kExpectedStillRunningExitCode = 0x102;
72 const int kExpectedKilledExitCode = 1;
73 #else
74 const int kExpectedStillRunningExitCode = 0;
75 #endif
77 // Sleeps until file filename is created.
78 void WaitToDie(const char* filename) {
79 FILE* fp;
80 do {
81 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(10));
82 fp = fopen(filename, "r");
83 } while (!fp);
84 fclose(fp);
87 // Signals children they should die now.
88 void SignalChildren(const char* filename) {
89 FILE* fp = fopen(filename, "w");
90 fclose(fp);
93 // Using a pipe to the child to wait for an event was considered, but
94 // there were cases in the past where pipes caused problems (other
95 // libraries closing the fds, child deadlocking). This is a simple
96 // case, so it's not worth the risk. Using wait loops is discouraged
97 // in most instances.
98 base::TerminationStatus WaitForChildTermination(base::ProcessHandle handle,
99 int* exit_code) {
100 // Now we wait until the result is something other than STILL_RUNNING.
101 base::TerminationStatus status = base::TERMINATION_STATUS_STILL_RUNNING;
102 const base::TimeDelta kInterval = base::TimeDelta::FromMilliseconds(20);
103 base::TimeDelta waited;
104 do {
105 status = base::GetTerminationStatus(handle, exit_code);
106 base::PlatformThread::Sleep(kInterval);
107 waited += kInterval;
108 } while (status == base::TERMINATION_STATUS_STILL_RUNNING &&
109 // Waiting for more time for process termination on android devices.
110 #if defined(OS_ANDROID)
111 waited < TestTimeouts::large_test_timeout());
112 #else
113 waited < TestTimeouts::action_max_timeout());
114 #endif
116 return status;
119 } // namespace
121 class ProcessUtilTest : public base::MultiProcessTest {
122 public:
123 #if defined(OS_POSIX)
124 // Spawn a child process that counts how many file descriptors are open.
125 int CountOpenFDsInChild();
126 #endif
127 // Converts the filename to a platform specific filepath.
128 // On Android files can not be created in arbitrary directories.
129 static std::string GetSignalFilePath(const char* filename);
132 std::string ProcessUtilTest::GetSignalFilePath(const char* filename) {
133 #if !defined(OS_ANDROID)
134 return filename;
135 #else
136 FilePath tmp_dir;
137 PathService::Get(base::DIR_CACHE, &tmp_dir);
138 tmp_dir = tmp_dir.Append(filename);
139 return tmp_dir.value();
140 #endif
143 MULTIPROCESS_TEST_MAIN(SimpleChildProcess) {
144 return 0;
147 // TODO(viettrungluu): This should be in a "MultiProcessTestTest".
148 TEST_F(ProcessUtilTest, SpawnChild) {
149 base::ProcessHandle handle = SpawnChild("SimpleChildProcess");
150 ASSERT_NE(base::kNullProcessHandle, handle);
151 EXPECT_TRUE(base::WaitForSingleProcess(
152 handle, TestTimeouts::action_max_timeout()));
153 base::CloseProcessHandle(handle);
156 MULTIPROCESS_TEST_MAIN(SlowChildProcess) {
157 WaitToDie(ProcessUtilTest::GetSignalFilePath(kSignalFileSlow).c_str());
158 return 0;
161 TEST_F(ProcessUtilTest, KillSlowChild) {
162 const std::string signal_file =
163 ProcessUtilTest::GetSignalFilePath(kSignalFileSlow);
164 remove(signal_file.c_str());
165 base::ProcessHandle handle = SpawnChild("SlowChildProcess");
166 ASSERT_NE(base::kNullProcessHandle, handle);
167 SignalChildren(signal_file.c_str());
168 EXPECT_TRUE(base::WaitForSingleProcess(
169 handle, TestTimeouts::action_max_timeout()));
170 base::CloseProcessHandle(handle);
171 remove(signal_file.c_str());
174 // Times out on Linux and Win, flakes on other platforms, http://crbug.com/95058
175 TEST_F(ProcessUtilTest, DISABLED_GetTerminationStatusExit) {
176 const std::string signal_file =
177 ProcessUtilTest::GetSignalFilePath(kSignalFileSlow);
178 remove(signal_file.c_str());
179 base::ProcessHandle handle = SpawnChild("SlowChildProcess");
180 ASSERT_NE(base::kNullProcessHandle, handle);
182 int exit_code = 42;
183 EXPECT_EQ(base::TERMINATION_STATUS_STILL_RUNNING,
184 base::GetTerminationStatus(handle, &exit_code));
185 EXPECT_EQ(kExpectedStillRunningExitCode, exit_code);
187 SignalChildren(signal_file.c_str());
188 exit_code = 42;
189 base::TerminationStatus status =
190 WaitForChildTermination(handle, &exit_code);
191 EXPECT_EQ(base::TERMINATION_STATUS_NORMAL_TERMINATION, status);
192 EXPECT_EQ(0, exit_code);
193 base::CloseProcessHandle(handle);
194 remove(signal_file.c_str());
197 #if defined(OS_WIN)
198 // TODO(cpu): figure out how to test this in other platforms.
199 TEST_F(ProcessUtilTest, GetProcId) {
200 base::ProcessId id1 = base::GetProcId(GetCurrentProcess());
201 EXPECT_NE(0ul, id1);
202 base::ProcessHandle handle = SpawnChild("SimpleChildProcess");
203 ASSERT_NE(base::kNullProcessHandle, handle);
204 base::ProcessId id2 = base::GetProcId(handle);
205 EXPECT_NE(0ul, id2);
206 EXPECT_NE(id1, id2);
207 base::CloseProcessHandle(handle);
209 #endif
211 #if !defined(OS_MACOSX)
212 // This test is disabled on Mac, since it's flaky due to ReportCrash
213 // taking a variable amount of time to parse and load the debug and
214 // symbol data for this unit test's executable before firing the
215 // signal handler.
217 // TODO(gspencer): turn this test process into a very small program
218 // with no symbols (instead of using the multiprocess testing
219 // framework) to reduce the ReportCrash overhead.
220 const char kSignalFileCrash[] = "CrashingChildProcess.die";
222 MULTIPROCESS_TEST_MAIN(CrashingChildProcess) {
223 WaitToDie(ProcessUtilTest::GetSignalFilePath(kSignalFileCrash).c_str());
224 #if defined(OS_POSIX)
225 // Have to disable to signal handler for segv so we can get a crash
226 // instead of an abnormal termination through the crash dump handler.
227 ::signal(SIGSEGV, SIG_DFL);
228 #endif
229 // Make this process have a segmentation fault.
230 volatile int* oops = NULL;
231 *oops = 0xDEAD;
232 return 1;
235 // This test intentionally crashes, so we don't need to run it under
236 // AddressSanitizer.
237 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
238 #define MAYBE_GetTerminationStatusCrash DISABLED_GetTerminationStatusCrash
239 #else
240 #define MAYBE_GetTerminationStatusCrash GetTerminationStatusCrash
241 #endif
242 TEST_F(ProcessUtilTest, MAYBE_GetTerminationStatusCrash) {
243 const std::string signal_file =
244 ProcessUtilTest::GetSignalFilePath(kSignalFileCrash);
245 remove(signal_file.c_str());
246 base::ProcessHandle handle = SpawnChild("CrashingChildProcess");
247 ASSERT_NE(base::kNullProcessHandle, handle);
249 int exit_code = 42;
250 EXPECT_EQ(base::TERMINATION_STATUS_STILL_RUNNING,
251 base::GetTerminationStatus(handle, &exit_code));
252 EXPECT_EQ(kExpectedStillRunningExitCode, exit_code);
254 SignalChildren(signal_file.c_str());
255 exit_code = 42;
256 base::TerminationStatus status =
257 WaitForChildTermination(handle, &exit_code);
258 EXPECT_EQ(base::TERMINATION_STATUS_PROCESS_CRASHED, status);
260 #if defined(OS_WIN)
261 EXPECT_EQ(0xc0000005, exit_code);
262 #elif defined(OS_POSIX)
263 int signaled = WIFSIGNALED(exit_code);
264 EXPECT_NE(0, signaled);
265 int signal = WTERMSIG(exit_code);
266 EXPECT_EQ(SIGSEGV, signal);
267 #endif
268 base::CloseProcessHandle(handle);
270 // Reset signal handlers back to "normal".
271 base::debug::EnableInProcessStackDumping();
272 remove(signal_file.c_str());
274 #endif // !defined(OS_MACOSX)
276 MULTIPROCESS_TEST_MAIN(KilledChildProcess) {
277 WaitToDie(ProcessUtilTest::GetSignalFilePath(kSignalFileKill).c_str());
278 #if defined(OS_WIN)
279 // Kill ourselves.
280 HANDLE handle = ::OpenProcess(PROCESS_ALL_ACCESS, 0, ::GetCurrentProcessId());
281 ::TerminateProcess(handle, kExpectedKilledExitCode);
282 #elif defined(OS_POSIX)
283 // Send a SIGKILL to this process, just like the OOM killer would.
284 ::kill(getpid(), SIGKILL);
285 #endif
286 return 1;
289 TEST_F(ProcessUtilTest, GetTerminationStatusKill) {
290 const std::string signal_file =
291 ProcessUtilTest::GetSignalFilePath(kSignalFileKill);
292 remove(signal_file.c_str());
293 base::ProcessHandle handle = SpawnChild("KilledChildProcess");
294 ASSERT_NE(base::kNullProcessHandle, handle);
296 int exit_code = 42;
297 EXPECT_EQ(base::TERMINATION_STATUS_STILL_RUNNING,
298 base::GetTerminationStatus(handle, &exit_code));
299 EXPECT_EQ(kExpectedStillRunningExitCode, exit_code);
301 SignalChildren(signal_file.c_str());
302 exit_code = 42;
303 base::TerminationStatus status =
304 WaitForChildTermination(handle, &exit_code);
305 EXPECT_EQ(base::TERMINATION_STATUS_PROCESS_WAS_KILLED, status);
306 #if defined(OS_WIN)
307 EXPECT_EQ(kExpectedKilledExitCode, exit_code);
308 #elif defined(OS_POSIX)
309 int signaled = WIFSIGNALED(exit_code);
310 EXPECT_NE(0, signaled);
311 int signal = WTERMSIG(exit_code);
312 EXPECT_EQ(SIGKILL, signal);
313 #endif
314 base::CloseProcessHandle(handle);
315 remove(signal_file.c_str());
318 // Ensure that the priority of a process is restored correctly after
319 // backgrounding and restoring.
320 // Note: a platform may not be willing or able to lower the priority of
321 // a process. The calls to SetProcessBackground should be noops then.
322 TEST_F(ProcessUtilTest, SetProcessBackgrounded) {
323 base::ProcessHandle handle = SpawnChild("SimpleChildProcess");
324 base::Process process(handle);
325 int old_priority = process.GetPriority();
326 #if defined(OS_WIN)
327 EXPECT_TRUE(process.SetProcessBackgrounded(true));
328 EXPECT_TRUE(process.IsProcessBackgrounded());
329 EXPECT_TRUE(process.SetProcessBackgrounded(false));
330 EXPECT_FALSE(process.IsProcessBackgrounded());
331 #else
332 process.SetProcessBackgrounded(true);
333 process.SetProcessBackgrounded(false);
334 #endif
335 int new_priority = process.GetPriority();
336 EXPECT_EQ(old_priority, new_priority);
339 // Same as SetProcessBackgrounded but to this very process. It uses
340 // a different code path at least for Windows.
341 TEST_F(ProcessUtilTest, SetProcessBackgroundedSelf) {
342 base::Process process(base::Process::Current().handle());
343 int old_priority = process.GetPriority();
344 #if defined(OS_WIN)
345 EXPECT_TRUE(process.SetProcessBackgrounded(true));
346 EXPECT_TRUE(process.IsProcessBackgrounded());
347 EXPECT_TRUE(process.SetProcessBackgrounded(false));
348 EXPECT_FALSE(process.IsProcessBackgrounded());
349 #else
350 process.SetProcessBackgrounded(true);
351 process.SetProcessBackgrounded(false);
352 #endif
353 int new_priority = process.GetPriority();
354 EXPECT_EQ(old_priority, new_priority);
357 #if defined(OS_WIN)
358 // TODO(estade): if possible, port this test.
359 TEST_F(ProcessUtilTest, GetAppOutput) {
360 // Let's create a decently long message.
361 std::string message;
362 for (int i = 0; i < 1025; i++) { // 1025 so it does not end on a kilo-byte
363 // boundary.
364 message += "Hello!";
366 // cmd.exe's echo always adds a \r\n to its output.
367 std::string expected(message);
368 expected += "\r\n";
370 FilePath cmd(L"cmd.exe");
371 CommandLine cmd_line(cmd);
372 cmd_line.AppendArg("/c");
373 cmd_line.AppendArg("echo " + message + "");
374 std::string output;
375 ASSERT_TRUE(base::GetAppOutput(cmd_line, &output));
376 EXPECT_EQ(expected, output);
378 // Let's make sure stderr is ignored.
379 CommandLine other_cmd_line(cmd);
380 other_cmd_line.AppendArg("/c");
381 // http://msdn.microsoft.com/library/cc772622.aspx
382 cmd_line.AppendArg("echo " + message + " >&2");
383 output.clear();
384 ASSERT_TRUE(base::GetAppOutput(other_cmd_line, &output));
385 EXPECT_EQ("", output);
388 // TODO(estade): if possible, port this test.
389 TEST_F(ProcessUtilTest, LaunchAsUser) {
390 base::UserTokenHandle token;
391 ASSERT_TRUE(OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &token));
392 base::LaunchOptions options;
393 options.as_user = token;
394 EXPECT_TRUE(base::LaunchProcess(MakeCmdLine("SimpleChildProcess"), options,
395 NULL));
398 static const char kEventToTriggerHandleSwitch[] = "event-to-trigger-handle";
400 MULTIPROCESS_TEST_MAIN(TriggerEventChildProcess) {
401 std::string handle_value_string =
402 CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
403 kEventToTriggerHandleSwitch);
404 CHECK(!handle_value_string.empty());
406 uint64 handle_value_uint64;
407 CHECK(base::StringToUint64(handle_value_string, &handle_value_uint64));
408 // Give ownership of the handle to |event|.
409 base::WaitableEvent event(reinterpret_cast<HANDLE>(handle_value_uint64));
411 event.Signal();
413 return 0;
416 TEST_F(ProcessUtilTest, InheritSpecifiedHandles) {
417 // Manually create the event, so that it can be inheritable.
418 SECURITY_ATTRIBUTES security_attributes = {};
419 security_attributes.nLength = static_cast<DWORD>(sizeof(security_attributes));
420 security_attributes.lpSecurityDescriptor = NULL;
421 security_attributes.bInheritHandle = true;
423 // Takes ownership of the event handle.
424 base::WaitableEvent event(
425 CreateEvent(&security_attributes, true, false, NULL));
426 base::HandlesToInheritVector handles_to_inherit;
427 handles_to_inherit.push_back(event.handle());
428 base::LaunchOptions options;
429 options.handles_to_inherit = &handles_to_inherit;
431 CommandLine cmd_line = MakeCmdLine("TriggerEventChildProcess");
432 cmd_line.AppendSwitchASCII(kEventToTriggerHandleSwitch,
433 base::Uint64ToString(reinterpret_cast<uint64>(event.handle())));
435 // This functionality actually requires Vista or later. Make sure that it
436 // fails properly on XP.
437 if (base::win::GetVersion() < base::win::VERSION_VISTA) {
438 EXPECT_FALSE(base::LaunchProcess(cmd_line, options, NULL));
439 return;
442 // Launch the process and wait for it to trigger the event.
443 ASSERT_TRUE(base::LaunchProcess(cmd_line, options, NULL));
444 EXPECT_TRUE(event.TimedWait(TestTimeouts::action_max_timeout()));
446 #endif // defined(OS_WIN)
448 #if defined(OS_POSIX)
450 namespace {
452 // Returns the maximum number of files that a process can have open.
453 // Returns 0 on error.
454 int GetMaxFilesOpenInProcess() {
455 struct rlimit rlim;
456 if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
457 return 0;
460 // rlim_t is a uint64 - clip to maxint. We do this since FD #s are ints
461 // which are all 32 bits on the supported platforms.
462 rlim_t max_int = static_cast<rlim_t>(std::numeric_limits<int32>::max());
463 if (rlim.rlim_cur > max_int) {
464 return max_int;
467 return rlim.rlim_cur;
470 const int kChildPipe = 20; // FD # for write end of pipe in child process.
472 } // namespace
474 MULTIPROCESS_TEST_MAIN(ProcessUtilsLeakFDChildProcess) {
475 // This child process counts the number of open FDs, it then writes that
476 // number out to a pipe connected to the parent.
477 int num_open_files = 0;
478 int write_pipe = kChildPipe;
479 int max_files = GetMaxFilesOpenInProcess();
480 for (int i = STDERR_FILENO + 1; i < max_files; i++) {
481 if (i != kChildPipe) {
482 int fd;
483 if ((fd = HANDLE_EINTR(dup(i))) != -1) {
484 close(fd);
485 num_open_files += 1;
490 int written = HANDLE_EINTR(write(write_pipe, &num_open_files,
491 sizeof(num_open_files)));
492 DCHECK_EQ(static_cast<size_t>(written), sizeof(num_open_files));
493 int ret = IGNORE_EINTR(close(write_pipe));
494 DPCHECK(ret == 0);
496 return 0;
499 int ProcessUtilTest::CountOpenFDsInChild() {
500 int fds[2];
501 if (pipe(fds) < 0)
502 NOTREACHED();
504 base::FileHandleMappingVector fd_mapping_vec;
505 fd_mapping_vec.push_back(std::pair<int, int>(fds[1], kChildPipe));
506 base::LaunchOptions options;
507 options.fds_to_remap = &fd_mapping_vec;
508 base::ProcessHandle handle =
509 SpawnChildWithOptions("ProcessUtilsLeakFDChildProcess", options);
510 CHECK(handle);
511 int ret = IGNORE_EINTR(close(fds[1]));
512 DPCHECK(ret == 0);
514 // Read number of open files in client process from pipe;
515 int num_open_files = -1;
516 ssize_t bytes_read =
517 HANDLE_EINTR(read(fds[0], &num_open_files, sizeof(num_open_files)));
518 CHECK_EQ(bytes_read, static_cast<ssize_t>(sizeof(num_open_files)));
520 #if defined(THREAD_SANITIZER)
521 // Compiler-based ThreadSanitizer makes this test slow.
522 CHECK(base::WaitForSingleProcess(handle, base::TimeDelta::FromSeconds(3)));
523 #else
524 CHECK(base::WaitForSingleProcess(handle, base::TimeDelta::FromSeconds(1)));
525 #endif
526 base::CloseProcessHandle(handle);
527 ret = IGNORE_EINTR(close(fds[0]));
528 DPCHECK(ret == 0);
530 return num_open_files;
533 #if defined(ADDRESS_SANITIZER) || defined(THREAD_SANITIZER)
534 // ProcessUtilTest.FDRemapping is flaky when ran under xvfb-run on Precise.
535 // The problem is 100% reproducible with both ASan and TSan.
536 // See http://crbug.com/136720.
537 #define MAYBE_FDRemapping DISABLED_FDRemapping
538 #else
539 #define MAYBE_FDRemapping FDRemapping
540 #endif
541 TEST_F(ProcessUtilTest, MAYBE_FDRemapping) {
542 int fds_before = CountOpenFDsInChild();
544 // open some dummy fds to make sure they don't propagate over to the
545 // child process.
546 int dev_null = open("/dev/null", O_RDONLY);
547 int sockets[2];
548 socketpair(AF_UNIX, SOCK_STREAM, 0, sockets);
550 int fds_after = CountOpenFDsInChild();
552 ASSERT_EQ(fds_after, fds_before);
554 int ret;
555 ret = IGNORE_EINTR(close(sockets[0]));
556 DPCHECK(ret == 0);
557 ret = IGNORE_EINTR(close(sockets[1]));
558 DPCHECK(ret == 0);
559 ret = IGNORE_EINTR(close(dev_null));
560 DPCHECK(ret == 0);
563 namespace {
565 std::string TestLaunchProcess(const std::vector<std::string>& args,
566 const base::EnvironmentMap& env_changes,
567 const bool clear_environ,
568 const int clone_flags) {
569 base::FileHandleMappingVector fds_to_remap;
571 int fds[2];
572 PCHECK(pipe(fds) == 0);
574 fds_to_remap.push_back(std::make_pair(fds[1], 1));
575 base::LaunchOptions options;
576 options.wait = true;
577 options.environ = env_changes;
578 options.clear_environ = clear_environ;
579 options.fds_to_remap = &fds_to_remap;
580 #if defined(OS_LINUX)
581 options.clone_flags = clone_flags;
582 #else
583 CHECK_EQ(0, clone_flags);
584 #endif // OS_LINUX
585 EXPECT_TRUE(base::LaunchProcess(args, options, NULL));
586 PCHECK(IGNORE_EINTR(close(fds[1])) == 0);
588 char buf[512];
589 const ssize_t n = HANDLE_EINTR(read(fds[0], buf, sizeof(buf)));
591 PCHECK(IGNORE_EINTR(close(fds[0])) == 0);
593 return std::string(buf, n);
596 const char kLargeString[] =
597 "0123456789012345678901234567890123456789012345678901234567890123456789"
598 "0123456789012345678901234567890123456789012345678901234567890123456789"
599 "0123456789012345678901234567890123456789012345678901234567890123456789"
600 "0123456789012345678901234567890123456789012345678901234567890123456789"
601 "0123456789012345678901234567890123456789012345678901234567890123456789"
602 "0123456789012345678901234567890123456789012345678901234567890123456789"
603 "0123456789012345678901234567890123456789012345678901234567890123456789";
605 } // namespace
607 TEST_F(ProcessUtilTest, LaunchProcess) {
608 base::EnvironmentMap env_changes;
609 std::vector<std::string> echo_base_test;
610 echo_base_test.push_back(kPosixShell);
611 echo_base_test.push_back("-c");
612 echo_base_test.push_back("echo $BASE_TEST");
614 std::vector<std::string> print_env;
615 print_env.push_back("/usr/bin/env");
616 const int no_clone_flags = 0;
617 const bool no_clear_environ = false;
619 const char kBaseTest[] = "BASE_TEST";
621 env_changes[kBaseTest] = "bar";
622 EXPECT_EQ("bar\n",
623 TestLaunchProcess(
624 echo_base_test, env_changes, no_clear_environ, no_clone_flags));
625 env_changes.clear();
627 EXPECT_EQ(0, setenv(kBaseTest, "testing", 1 /* override */));
628 EXPECT_EQ("testing\n",
629 TestLaunchProcess(
630 echo_base_test, env_changes, no_clear_environ, no_clone_flags));
632 env_changes[kBaseTest] = std::string();
633 EXPECT_EQ("\n",
634 TestLaunchProcess(
635 echo_base_test, env_changes, no_clear_environ, no_clone_flags));
637 env_changes[kBaseTest] = "foo";
638 EXPECT_EQ("foo\n",
639 TestLaunchProcess(
640 echo_base_test, env_changes, no_clear_environ, no_clone_flags));
642 env_changes.clear();
643 EXPECT_EQ(0, setenv(kBaseTest, kLargeString, 1 /* override */));
644 EXPECT_EQ(std::string(kLargeString) + "\n",
645 TestLaunchProcess(
646 echo_base_test, env_changes, no_clear_environ, no_clone_flags));
648 env_changes[kBaseTest] = "wibble";
649 EXPECT_EQ("wibble\n",
650 TestLaunchProcess(
651 echo_base_test, env_changes, no_clear_environ, no_clone_flags));
653 #if defined(OS_LINUX)
654 // Test a non-trival value for clone_flags.
655 // Don't test on Valgrind as it has limited support for clone().
656 if (!RunningOnValgrind()) {
657 EXPECT_EQ(
658 "wibble\n",
659 TestLaunchProcess(
660 echo_base_test, env_changes, no_clear_environ, CLONE_FS | SIGCHLD));
663 EXPECT_EQ(
664 "BASE_TEST=wibble\n",
665 TestLaunchProcess(
666 print_env, env_changes, true /* clear_environ */, no_clone_flags));
667 env_changes.clear();
668 EXPECT_EQ(
670 TestLaunchProcess(
671 print_env, env_changes, true /* clear_environ */, no_clone_flags));
672 #endif
675 TEST_F(ProcessUtilTest, GetAppOutput) {
676 std::string output;
678 #if defined(OS_ANDROID)
679 std::vector<std::string> argv;
680 argv.push_back("sh"); // Instead of /bin/sh, force path search to find it.
681 argv.push_back("-c");
683 argv.push_back("exit 0");
684 EXPECT_TRUE(base::GetAppOutput(CommandLine(argv), &output));
685 EXPECT_STREQ("", output.c_str());
687 argv[2] = "exit 1";
688 EXPECT_FALSE(base::GetAppOutput(CommandLine(argv), &output));
689 EXPECT_STREQ("", output.c_str());
691 argv[2] = "echo foobar42";
692 EXPECT_TRUE(base::GetAppOutput(CommandLine(argv), &output));
693 EXPECT_STREQ("foobar42\n", output.c_str());
694 #else
695 EXPECT_TRUE(base::GetAppOutput(CommandLine(FilePath("true")), &output));
696 EXPECT_STREQ("", output.c_str());
698 EXPECT_FALSE(base::GetAppOutput(CommandLine(FilePath("false")), &output));
700 std::vector<std::string> argv;
701 argv.push_back("/bin/echo");
702 argv.push_back("-n");
703 argv.push_back("foobar42");
704 EXPECT_TRUE(base::GetAppOutput(CommandLine(argv), &output));
705 EXPECT_STREQ("foobar42", output.c_str());
706 #endif // defined(OS_ANDROID)
709 // Flakes on Android, crbug.com/375840
710 #if defined(OS_ANDROID)
711 #define MAYBE_GetAppOutputRestricted DISABLED_GetAppOutputRestricted
712 #else
713 #define MAYBE_GetAppOutputRestricted GetAppOutputRestricted
714 #endif
715 TEST_F(ProcessUtilTest, MAYBE_GetAppOutputRestricted) {
716 // Unfortunately, since we can't rely on the path, we need to know where
717 // everything is. So let's use /bin/sh, which is on every POSIX system, and
718 // its built-ins.
719 std::vector<std::string> argv;
720 argv.push_back(std::string(kShellPath)); // argv[0]
721 argv.push_back("-c"); // argv[1]
723 // On success, should set |output|. We use |/bin/sh -c 'exit 0'| instead of
724 // |true| since the location of the latter may be |/bin| or |/usr/bin| (and we
725 // need absolute paths).
726 argv.push_back("exit 0"); // argv[2]; equivalent to "true"
727 std::string output = "abc";
728 EXPECT_TRUE(base::GetAppOutputRestricted(CommandLine(argv), &output, 100));
729 EXPECT_STREQ("", output.c_str());
731 argv[2] = "exit 1"; // equivalent to "false"
732 output = "before";
733 EXPECT_FALSE(base::GetAppOutputRestricted(CommandLine(argv),
734 &output, 100));
735 EXPECT_STREQ("", output.c_str());
737 // Amount of output exactly equal to space allowed.
738 argv[2] = "echo 123456789"; // (the sh built-in doesn't take "-n")
739 output.clear();
740 EXPECT_TRUE(base::GetAppOutputRestricted(CommandLine(argv), &output, 10));
741 EXPECT_STREQ("123456789\n", output.c_str());
743 // Amount of output greater than space allowed.
744 output.clear();
745 EXPECT_TRUE(base::GetAppOutputRestricted(CommandLine(argv), &output, 5));
746 EXPECT_STREQ("12345", output.c_str());
748 // Amount of output less than space allowed.
749 output.clear();
750 EXPECT_TRUE(base::GetAppOutputRestricted(CommandLine(argv), &output, 15));
751 EXPECT_STREQ("123456789\n", output.c_str());
753 // Zero space allowed.
754 output = "abc";
755 EXPECT_TRUE(base::GetAppOutputRestricted(CommandLine(argv), &output, 0));
756 EXPECT_STREQ("", output.c_str());
759 #if !defined(OS_MACOSX) && !defined(OS_OPENBSD)
760 // TODO(benwells): GetAppOutputRestricted should terminate applications
761 // with SIGPIPE when we have enough output. http://crbug.com/88502
762 TEST_F(ProcessUtilTest, GetAppOutputRestrictedSIGPIPE) {
763 std::vector<std::string> argv;
764 std::string output;
766 argv.push_back(std::string(kShellPath)); // argv[0]
767 argv.push_back("-c");
768 #if defined(OS_ANDROID)
769 argv.push_back("while echo 12345678901234567890; do :; done");
770 EXPECT_TRUE(base::GetAppOutputRestricted(CommandLine(argv), &output, 10));
771 EXPECT_STREQ("1234567890", output.c_str());
772 #else
773 argv.push_back("yes");
774 EXPECT_TRUE(base::GetAppOutputRestricted(CommandLine(argv), &output, 10));
775 EXPECT_STREQ("y\ny\ny\ny\ny\n", output.c_str());
776 #endif
778 #endif
780 #if defined(ADDRESS_SANITIZER) && defined(OS_MACOSX) && \
781 defined(ARCH_CPU_64_BITS)
782 // Times out under AddressSanitizer on 64-bit OS X, see
783 // http://crbug.com/298197.
784 #define MAYBE_GetAppOutputRestrictedNoZombies \
785 DISABLED_GetAppOutputRestrictedNoZombies
786 #else
787 #define MAYBE_GetAppOutputRestrictedNoZombies GetAppOutputRestrictedNoZombies
788 #endif
789 TEST_F(ProcessUtilTest, MAYBE_GetAppOutputRestrictedNoZombies) {
790 std::vector<std::string> argv;
792 argv.push_back(std::string(kShellPath)); // argv[0]
793 argv.push_back("-c"); // argv[1]
794 argv.push_back("echo 123456789012345678901234567890"); // argv[2]
796 // Run |GetAppOutputRestricted()| 300 (> default per-user processes on Mac OS
797 // 10.5) times with an output buffer big enough to capture all output.
798 for (int i = 0; i < 300; i++) {
799 std::string output;
800 EXPECT_TRUE(base::GetAppOutputRestricted(CommandLine(argv), &output, 100));
801 EXPECT_STREQ("123456789012345678901234567890\n", output.c_str());
804 // Ditto, but with an output buffer too small to capture all output.
805 for (int i = 0; i < 300; i++) {
806 std::string output;
807 EXPECT_TRUE(base::GetAppOutputRestricted(CommandLine(argv), &output, 10));
808 EXPECT_STREQ("1234567890", output.c_str());
812 TEST_F(ProcessUtilTest, GetAppOutputWithExitCode) {
813 // Test getting output from a successful application.
814 std::vector<std::string> argv;
815 std::string output;
816 int exit_code;
817 argv.push_back(std::string(kShellPath)); // argv[0]
818 argv.push_back("-c"); // argv[1]
819 argv.push_back("echo foo"); // argv[2];
820 EXPECT_TRUE(base::GetAppOutputWithExitCode(CommandLine(argv), &output,
821 &exit_code));
822 EXPECT_STREQ("foo\n", output.c_str());
823 EXPECT_EQ(exit_code, 0);
825 // Test getting output from an application which fails with a specific exit
826 // code.
827 output.clear();
828 argv[2] = "echo foo; exit 2";
829 EXPECT_TRUE(base::GetAppOutputWithExitCode(CommandLine(argv), &output,
830 &exit_code));
831 EXPECT_STREQ("foo\n", output.c_str());
832 EXPECT_EQ(exit_code, 2);
835 TEST_F(ProcessUtilTest, GetParentProcessId) {
836 base::ProcessId ppid = base::GetParentProcessId(base::GetCurrentProcId());
837 EXPECT_EQ(ppid, getppid());
840 // TODO(port): port those unit tests.
841 bool IsProcessDead(base::ProcessHandle child) {
842 // waitpid() will actually reap the process which is exactly NOT what we
843 // want to test for. The good thing is that if it can't find the process
844 // we'll get a nice value for errno which we can test for.
845 const pid_t result = HANDLE_EINTR(waitpid(child, NULL, WNOHANG));
846 return result == -1 && errno == ECHILD;
849 TEST_F(ProcessUtilTest, DelayedTermination) {
850 base::ProcessHandle child_process = SpawnChild("process_util_test_never_die");
851 ASSERT_TRUE(child_process);
852 base::EnsureProcessTerminated(child_process);
853 base::WaitForSingleProcess(child_process, base::TimeDelta::FromSeconds(5));
855 // Check that process was really killed.
856 EXPECT_TRUE(IsProcessDead(child_process));
857 base::CloseProcessHandle(child_process);
860 MULTIPROCESS_TEST_MAIN(process_util_test_never_die) {
861 while (1) {
862 sleep(500);
864 return 0;
867 TEST_F(ProcessUtilTest, ImmediateTermination) {
868 base::ProcessHandle child_process =
869 SpawnChild("process_util_test_die_immediately");
870 ASSERT_TRUE(child_process);
871 // Give it time to die.
872 sleep(2);
873 base::EnsureProcessTerminated(child_process);
875 // Check that process was really killed.
876 EXPECT_TRUE(IsProcessDead(child_process));
877 base::CloseProcessHandle(child_process);
880 MULTIPROCESS_TEST_MAIN(process_util_test_die_immediately) {
881 return 0;
884 #endif // defined(OS_POSIX)