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
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/files/file_util.h"
14 #include "base/files/scoped_file.h"
15 #include "base/logging.h"
16 #include "base/memory/scoped_ptr.h"
17 #include "base/path_service.h"
18 #include "base/posix/eintr_wrapper.h"
19 #include "base/process/kill.h"
20 #include "base/process/launch.h"
21 #include "base/process/memory.h"
22 #include "base/process/process.h"
23 #include "base/process/process_metrics.h"
24 #include "base/strings/string_number_conversions.h"
25 #include "base/strings/utf_string_conversions.h"
26 #include "base/synchronization/waitable_event.h"
27 #include "base/test/multiprocess_test.h"
28 #include "base/test/test_timeouts.h"
29 #include "base/third_party/dynamic_annotations/dynamic_annotations.h"
30 #include "base/threading/platform_thread.h"
31 #include "base/threading/thread.h"
32 #include "build/build_config.h"
33 #include "testing/gtest/include/gtest/gtest.h"
34 #include "testing/multiprocess_func_list.h"
39 #include <sys/syscall.h>
47 #include <sys/resource.h>
48 #include <sys/socket.h>
49 #include <sys/types.h>
55 #include "base/win/windows_version.h"
57 #if defined(OS_MACOSX)
58 #include <mach/vm_param.h>
59 #include <malloc/malloc.h>
60 #include "base/mac/mac_util.h"
67 #if defined(OS_ANDROID)
68 const char kShellPath
[] = "/system/bin/sh";
69 const char kPosixShell
[] = "sh";
71 const char kShellPath
[] = "/bin/sh";
72 const char kPosixShell
[] = "bash";
75 const char kSignalFileSlow
[] = "SlowChildProcess.die";
76 const char kSignalFileKill
[] = "KilledChildProcess.die";
79 const int kExpectedStillRunningExitCode
= 0x102;
80 const int kExpectedKilledExitCode
= 1;
82 const int kExpectedStillRunningExitCode
= 0;
85 // Sleeps until file filename is created.
86 void WaitToDie(const char* filename
) {
89 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(10));
90 fp
= fopen(filename
, "r");
95 // Signals children they should die now.
96 void SignalChildren(const char* filename
) {
97 FILE* fp
= fopen(filename
, "w");
101 // Using a pipe to the child to wait for an event was considered, but
102 // there were cases in the past where pipes caused problems (other
103 // libraries closing the fds, child deadlocking). This is a simple
104 // case, so it's not worth the risk. Using wait loops is discouraged
105 // in most instances.
106 base::TerminationStatus
WaitForChildTermination(base::ProcessHandle handle
,
108 // Now we wait until the result is something other than STILL_RUNNING.
109 base::TerminationStatus status
= base::TERMINATION_STATUS_STILL_RUNNING
;
110 const base::TimeDelta kInterval
= base::TimeDelta::FromMilliseconds(20);
111 base::TimeDelta waited
;
113 status
= base::GetTerminationStatus(handle
, exit_code
);
114 base::PlatformThread::Sleep(kInterval
);
116 } while (status
== base::TERMINATION_STATUS_STILL_RUNNING
&&
117 waited
< TestTimeouts::action_max_timeout());
124 class ProcessUtilTest
: public base::MultiProcessTest
{
126 #if defined(OS_POSIX)
127 // Spawn a child process that counts how many file descriptors are open.
128 int CountOpenFDsInChild();
130 // Converts the filename to a platform specific filepath.
131 // On Android files can not be created in arbitrary directories.
132 static std::string
GetSignalFilePath(const char* filename
);
135 std::string
ProcessUtilTest::GetSignalFilePath(const char* filename
) {
136 #if !defined(OS_ANDROID)
140 PathService::Get(base::DIR_CACHE
, &tmp_dir
);
141 tmp_dir
= tmp_dir
.Append(filename
);
142 return tmp_dir
.value();
146 MULTIPROCESS_TEST_MAIN(SimpleChildProcess
) {
150 // TODO(viettrungluu): This should be in a "MultiProcessTestTest".
151 TEST_F(ProcessUtilTest
, SpawnChild
) {
152 base::Process process
= SpawnChild("SimpleChildProcess");
153 ASSERT_TRUE(process
.IsValid());
155 EXPECT_TRUE(process
.WaitForExitWithTimeout(
156 TestTimeouts::action_max_timeout(), &exit_code
));
159 MULTIPROCESS_TEST_MAIN(SlowChildProcess
) {
160 WaitToDie(ProcessUtilTest::GetSignalFilePath(kSignalFileSlow
).c_str());
164 TEST_F(ProcessUtilTest
, KillSlowChild
) {
165 const std::string signal_file
=
166 ProcessUtilTest::GetSignalFilePath(kSignalFileSlow
);
167 remove(signal_file
.c_str());
168 base::Process process
= SpawnChild("SlowChildProcess");
169 ASSERT_TRUE(process
.IsValid());
170 SignalChildren(signal_file
.c_str());
172 EXPECT_TRUE(process
.WaitForExitWithTimeout(
173 TestTimeouts::action_max_timeout(), &exit_code
));
174 remove(signal_file
.c_str());
177 // Times out on Linux and Win, flakes on other platforms, http://crbug.com/95058
178 TEST_F(ProcessUtilTest
, DISABLED_GetTerminationStatusExit
) {
179 const std::string signal_file
=
180 ProcessUtilTest::GetSignalFilePath(kSignalFileSlow
);
181 remove(signal_file
.c_str());
182 base::Process process
= SpawnChild("SlowChildProcess");
183 ASSERT_TRUE(process
.IsValid());
186 EXPECT_EQ(base::TERMINATION_STATUS_STILL_RUNNING
,
187 base::GetTerminationStatus(process
.Handle(), &exit_code
));
188 EXPECT_EQ(kExpectedStillRunningExitCode
, exit_code
);
190 SignalChildren(signal_file
.c_str());
192 base::TerminationStatus status
=
193 WaitForChildTermination(process
.Handle(), &exit_code
);
194 EXPECT_EQ(base::TERMINATION_STATUS_NORMAL_TERMINATION
, status
);
195 EXPECT_EQ(0, exit_code
);
196 remove(signal_file
.c_str());
200 // TODO(cpu): figure out how to test this in other platforms.
201 TEST_F(ProcessUtilTest
, GetProcId
) {
202 base::ProcessId id1
= base::GetProcId(GetCurrentProcess());
204 base::Process process
= SpawnChild("SimpleChildProcess");
205 ASSERT_TRUE(process
.IsValid());
206 base::ProcessId id2
= process
.Pid();
212 #if !defined(OS_MACOSX)
213 // This test is disabled on Mac, since it's flaky due to ReportCrash
214 // taking a variable amount of time to parse and load the debug and
215 // symbol data for this unit test's executable before firing the
218 // TODO(gspencer): turn this test process into a very small program
219 // with no symbols (instead of using the multiprocess testing
220 // framework) to reduce the ReportCrash overhead.
221 const char kSignalFileCrash
[] = "CrashingChildProcess.die";
223 MULTIPROCESS_TEST_MAIN(CrashingChildProcess
) {
224 WaitToDie(ProcessUtilTest::GetSignalFilePath(kSignalFileCrash
).c_str());
225 #if defined(OS_POSIX)
226 // Have to disable to signal handler for segv so we can get a crash
227 // instead of an abnormal termination through the crash dump handler.
228 ::signal(SIGSEGV
, SIG_DFL
);
230 // Make this process have a segmentation fault.
231 volatile int* oops
= NULL
;
236 // This test intentionally crashes, so we don't need to run it under
238 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
239 #define MAYBE_GetTerminationStatusCrash DISABLED_GetTerminationStatusCrash
241 #define MAYBE_GetTerminationStatusCrash GetTerminationStatusCrash
243 TEST_F(ProcessUtilTest
, MAYBE_GetTerminationStatusCrash
) {
244 const std::string signal_file
=
245 ProcessUtilTest::GetSignalFilePath(kSignalFileCrash
);
246 remove(signal_file
.c_str());
247 base::Process process
= SpawnChild("CrashingChildProcess");
248 ASSERT_TRUE(process
.IsValid());
251 EXPECT_EQ(base::TERMINATION_STATUS_STILL_RUNNING
,
252 base::GetTerminationStatus(process
.Handle(), &exit_code
));
253 EXPECT_EQ(kExpectedStillRunningExitCode
, exit_code
);
255 SignalChildren(signal_file
.c_str());
257 base::TerminationStatus status
=
258 WaitForChildTermination(process
.Handle(), &exit_code
);
259 EXPECT_EQ(base::TERMINATION_STATUS_PROCESS_CRASHED
, status
);
262 EXPECT_EQ(0xc0000005, exit_code
);
263 #elif defined(OS_POSIX)
264 int signaled
= WIFSIGNALED(exit_code
);
265 EXPECT_NE(0, signaled
);
266 int signal
= WTERMSIG(exit_code
);
267 EXPECT_EQ(SIGSEGV
, signal
);
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());
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
);
289 TEST_F(ProcessUtilTest
, GetTerminationStatusKill
) {
290 const std::string signal_file
=
291 ProcessUtilTest::GetSignalFilePath(kSignalFileKill
);
292 remove(signal_file
.c_str());
293 base::Process process
= SpawnChild("KilledChildProcess");
294 ASSERT_TRUE(process
.IsValid());
297 EXPECT_EQ(base::TERMINATION_STATUS_STILL_RUNNING
,
298 base::GetTerminationStatus(process
.Handle(), &exit_code
));
299 EXPECT_EQ(kExpectedStillRunningExitCode
, exit_code
);
301 SignalChildren(signal_file
.c_str());
303 base::TerminationStatus status
=
304 WaitForChildTermination(process
.Handle(), &exit_code
);
305 EXPECT_EQ(base::TERMINATION_STATUS_PROCESS_WAS_KILLED
, status
);
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
);
314 remove(signal_file
.c_str());
318 // TODO(estade): if possible, port this test.
319 TEST_F(ProcessUtilTest
, GetAppOutput
) {
320 // Let's create a decently long message.
322 for (int i
= 0; i
< 1025; i
++) { // 1025 so it does not end on a kilo-byte
326 // cmd.exe's echo always adds a \r\n to its output.
327 std::string
expected(message
);
330 FilePath
cmd(L
"cmd.exe");
331 base::CommandLine
cmd_line(cmd
);
332 cmd_line
.AppendArg("/c");
333 cmd_line
.AppendArg("echo " + message
+ "");
335 ASSERT_TRUE(base::GetAppOutput(cmd_line
, &output
));
336 EXPECT_EQ(expected
, output
);
338 // Let's make sure stderr is ignored.
339 base::CommandLine
other_cmd_line(cmd
);
340 other_cmd_line
.AppendArg("/c");
341 // http://msdn.microsoft.com/library/cc772622.aspx
342 cmd_line
.AppendArg("echo " + message
+ " >&2");
344 ASSERT_TRUE(base::GetAppOutput(other_cmd_line
, &output
));
345 EXPECT_EQ("", output
);
348 // TODO(estade): if possible, port this test.
349 TEST_F(ProcessUtilTest
, LaunchAsUser
) {
350 base::UserTokenHandle token
;
351 ASSERT_TRUE(OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS
, &token
));
352 base::LaunchOptions options
;
353 options
.as_user
= token
;
354 EXPECT_TRUE(base::LaunchProcess(MakeCmdLine("SimpleChildProcess"),
358 static const char kEventToTriggerHandleSwitch
[] = "event-to-trigger-handle";
360 MULTIPROCESS_TEST_MAIN(TriggerEventChildProcess
) {
361 std::string handle_value_string
=
362 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
363 kEventToTriggerHandleSwitch
);
364 CHECK(!handle_value_string
.empty());
366 uint64 handle_value_uint64
;
367 CHECK(base::StringToUint64(handle_value_string
, &handle_value_uint64
));
368 // Give ownership of the handle to |event|.
369 base::WaitableEvent
event(base::win::ScopedHandle(
370 reinterpret_cast<HANDLE
>(handle_value_uint64
)));
377 TEST_F(ProcessUtilTest
, InheritSpecifiedHandles
) {
378 // Manually create the event, so that it can be inheritable.
379 SECURITY_ATTRIBUTES security_attributes
= {};
380 security_attributes
.nLength
= static_cast<DWORD
>(sizeof(security_attributes
));
381 security_attributes
.lpSecurityDescriptor
= NULL
;
382 security_attributes
.bInheritHandle
= true;
384 // Takes ownership of the event handle.
385 base::WaitableEvent
event(base::win::ScopedHandle(
386 CreateEvent(&security_attributes
, true, false, NULL
)));
387 base::HandlesToInheritVector handles_to_inherit
;
388 handles_to_inherit
.push_back(event
.handle());
389 base::LaunchOptions options
;
390 options
.handles_to_inherit
= &handles_to_inherit
;
392 base::CommandLine cmd_line
= MakeCmdLine("TriggerEventChildProcess");
393 cmd_line
.AppendSwitchASCII(kEventToTriggerHandleSwitch
,
394 base::Uint64ToString(reinterpret_cast<uint64
>(event
.handle())));
396 // This functionality actually requires Vista or later. Make sure that it
397 // fails properly on XP.
398 if (base::win::GetVersion() < base::win::VERSION_VISTA
) {
399 EXPECT_FALSE(base::LaunchProcess(cmd_line
, options
).IsValid());
403 // Launch the process and wait for it to trigger the event.
404 ASSERT_TRUE(base::LaunchProcess(cmd_line
, options
).IsValid());
405 EXPECT_TRUE(event
.TimedWait(TestTimeouts::action_max_timeout()));
407 #endif // defined(OS_WIN)
409 #if defined(OS_POSIX)
413 // Returns the maximum number of files that a process can have open.
414 // Returns 0 on error.
415 int GetMaxFilesOpenInProcess() {
417 if (getrlimit(RLIMIT_NOFILE
, &rlim
) != 0) {
421 // rlim_t is a uint64 - clip to maxint. We do this since FD #s are ints
422 // which are all 32 bits on the supported platforms.
423 rlim_t max_int
= static_cast<rlim_t
>(std::numeric_limits
<int32
>::max());
424 if (rlim
.rlim_cur
> max_int
) {
428 return rlim
.rlim_cur
;
431 const int kChildPipe
= 20; // FD # for write end of pipe in child process.
433 #if defined(OS_MACOSX)
435 // <http://opensource.apple.com/source/xnu/xnu-2422.1.72/bsd/sys/guarded.h>
436 #if !defined(_GUARDID_T)
438 typedef __uint64_t guardid_t
;
441 // From .../MacOSX10.9.sdk/usr/include/sys/syscall.h
442 #if !defined(SYS_change_fdguard_np)
443 #define SYS_change_fdguard_np 444
446 // <http://opensource.apple.com/source/xnu/xnu-2422.1.72/bsd/sys/guarded.h>
447 #if !defined(GUARD_DUP)
448 #define GUARD_DUP (1u << 1)
451 // <http://opensource.apple.com/source/xnu/xnu-2422.1.72/bsd/kern/kern_guarded.c?txt>
453 // Atomically replaces |guard|/|guardflags| with |nguard|/|nguardflags| on |fd|.
454 int change_fdguard_np(int fd
,
455 const guardid_t
*guard
, u_int guardflags
,
456 const guardid_t
*nguard
, u_int nguardflags
,
458 return syscall(SYS_change_fdguard_np
, fd
, guard
, guardflags
,
459 nguard
, nguardflags
, fdflagsp
);
462 // Attempt to set a file-descriptor guard on |fd|. In case of success, remove
463 // it and return |true| to indicate that it can be guarded. Returning |false|
464 // means either that |fd| is guarded by some other code, or more likely EBADF.
466 // Starting with 10.9, libdispatch began setting GUARD_DUP on a file descriptor.
467 // Unfortunately, it is spun up as part of +[NSApplication initialize], which is
468 // not really something that Chromium can avoid using on OSX. See
469 // <http://crbug.com/338157>. This function allows querying whether the file
470 // descriptor is guarded before attempting to close it.
471 bool CanGuardFd(int fd
) {
472 // The syscall is first provided in 10.9/Mavericks.
473 if (!base::mac::IsOSMavericksOrLater())
476 // Saves the original flags to reset later.
477 int original_fdflags
= 0;
479 // This can be any value at all, it just has to match up between the two
481 const guardid_t kGuard
= 15;
483 // Attempt to change the guard. This can fail with EBADF if the file
484 // descriptor is bad, or EINVAL if the fd already has a guard set.
486 change_fdguard_np(fd
, NULL
, 0, &kGuard
, GUARD_DUP
, &original_fdflags
);
490 // Remove the guard. It should not be possible to fail in removing the guard
492 ret
= change_fdguard_np(fd
, &kGuard
, GUARD_DUP
, NULL
, 0, &original_fdflags
);
501 MULTIPROCESS_TEST_MAIN(ProcessUtilsLeakFDChildProcess
) {
502 // This child process counts the number of open FDs, it then writes that
503 // number out to a pipe connected to the parent.
504 int num_open_files
= 0;
505 int write_pipe
= kChildPipe
;
506 int max_files
= GetMaxFilesOpenInProcess();
507 for (int i
= STDERR_FILENO
+ 1; i
< max_files
; i
++) {
508 #if defined(OS_MACOSX)
509 // Ignore guarded or invalid file descriptors.
514 if (i
!= kChildPipe
) {
516 if ((fd
= HANDLE_EINTR(dup(i
))) != -1) {
523 int written
= HANDLE_EINTR(write(write_pipe
, &num_open_files
,
524 sizeof(num_open_files
)));
525 DCHECK_EQ(static_cast<size_t>(written
), sizeof(num_open_files
));
526 int ret
= IGNORE_EINTR(close(write_pipe
));
532 int ProcessUtilTest::CountOpenFDsInChild() {
537 base::FileHandleMappingVector fd_mapping_vec
;
538 fd_mapping_vec
.push_back(std::pair
<int, int>(fds
[1], kChildPipe
));
539 base::LaunchOptions options
;
540 options
.fds_to_remap
= &fd_mapping_vec
;
541 base::Process process
=
542 SpawnChildWithOptions("ProcessUtilsLeakFDChildProcess", options
);
543 CHECK(process
.IsValid());
544 int ret
= IGNORE_EINTR(close(fds
[1]));
547 // Read number of open files in client process from pipe;
548 int num_open_files
= -1;
550 HANDLE_EINTR(read(fds
[0], &num_open_files
, sizeof(num_open_files
)));
551 CHECK_EQ(bytes_read
, static_cast<ssize_t
>(sizeof(num_open_files
)));
553 #if defined(THREAD_SANITIZER)
554 // Compiler-based ThreadSanitizer makes this test slow.
555 base::TimeDelta timeout
= base::TimeDelta::FromSeconds(3);
557 base::TimeDelta timeout
= base::TimeDelta::FromSeconds(1);
560 CHECK(process
.WaitForExitWithTimeout(timeout
, &exit_code
));
561 ret
= IGNORE_EINTR(close(fds
[0]));
564 return num_open_files
;
567 #if defined(ADDRESS_SANITIZER) || defined(THREAD_SANITIZER)
568 // ProcessUtilTest.FDRemapping is flaky when ran under xvfb-run on Precise.
569 // The problem is 100% reproducible with both ASan and TSan.
570 // See http://crbug.com/136720.
571 #define MAYBE_FDRemapping DISABLED_FDRemapping
573 #define MAYBE_FDRemapping FDRemapping
575 TEST_F(ProcessUtilTest
, MAYBE_FDRemapping
) {
576 int fds_before
= CountOpenFDsInChild();
578 // open some dummy fds to make sure they don't propagate over to the
580 int dev_null
= open("/dev/null", O_RDONLY
);
582 socketpair(AF_UNIX
, SOCK_STREAM
, 0, sockets
);
584 int fds_after
= CountOpenFDsInChild();
586 ASSERT_EQ(fds_after
, fds_before
);
589 ret
= IGNORE_EINTR(close(sockets
[0]));
591 ret
= IGNORE_EINTR(close(sockets
[1]));
593 ret
= IGNORE_EINTR(close(dev_null
));
599 std::string
TestLaunchProcess(const std::vector
<std::string
>& args
,
600 const base::EnvironmentMap
& env_changes
,
601 const bool clear_environ
,
602 const int clone_flags
) {
603 base::FileHandleMappingVector fds_to_remap
;
606 PCHECK(pipe(fds
) == 0);
608 fds_to_remap
.push_back(std::make_pair(fds
[1], 1));
609 base::LaunchOptions options
;
611 options
.environ
= env_changes
;
612 options
.clear_environ
= clear_environ
;
613 options
.fds_to_remap
= &fds_to_remap
;
614 #if defined(OS_LINUX)
615 options
.clone_flags
= clone_flags
;
617 CHECK_EQ(0, clone_flags
);
619 EXPECT_TRUE(base::LaunchProcess(args
, options
).IsValid());
620 PCHECK(IGNORE_EINTR(close(fds
[1])) == 0);
623 const ssize_t n
= HANDLE_EINTR(read(fds
[0], buf
, sizeof(buf
)));
625 PCHECK(IGNORE_EINTR(close(fds
[0])) == 0);
627 return std::string(buf
, n
);
630 const char kLargeString
[] =
631 "0123456789012345678901234567890123456789012345678901234567890123456789"
632 "0123456789012345678901234567890123456789012345678901234567890123456789"
633 "0123456789012345678901234567890123456789012345678901234567890123456789"
634 "0123456789012345678901234567890123456789012345678901234567890123456789"
635 "0123456789012345678901234567890123456789012345678901234567890123456789"
636 "0123456789012345678901234567890123456789012345678901234567890123456789"
637 "0123456789012345678901234567890123456789012345678901234567890123456789";
641 TEST_F(ProcessUtilTest
, LaunchProcess
) {
642 base::EnvironmentMap env_changes
;
643 std::vector
<std::string
> echo_base_test
;
644 echo_base_test
.push_back(kPosixShell
);
645 echo_base_test
.push_back("-c");
646 echo_base_test
.push_back("echo $BASE_TEST");
648 std::vector
<std::string
> print_env
;
649 print_env
.push_back("/usr/bin/env");
650 const int no_clone_flags
= 0;
651 const bool no_clear_environ
= false;
653 const char kBaseTest
[] = "BASE_TEST";
655 env_changes
[kBaseTest
] = "bar";
658 echo_base_test
, env_changes
, no_clear_environ
, no_clone_flags
));
661 EXPECT_EQ(0, setenv(kBaseTest
, "testing", 1 /* override */));
662 EXPECT_EQ("testing\n",
664 echo_base_test
, env_changes
, no_clear_environ
, no_clone_flags
));
666 env_changes
[kBaseTest
] = std::string();
669 echo_base_test
, env_changes
, no_clear_environ
, no_clone_flags
));
671 env_changes
[kBaseTest
] = "foo";
674 echo_base_test
, env_changes
, no_clear_environ
, no_clone_flags
));
677 EXPECT_EQ(0, setenv(kBaseTest
, kLargeString
, 1 /* override */));
678 EXPECT_EQ(std::string(kLargeString
) + "\n",
680 echo_base_test
, env_changes
, no_clear_environ
, no_clone_flags
));
682 env_changes
[kBaseTest
] = "wibble";
683 EXPECT_EQ("wibble\n",
685 echo_base_test
, env_changes
, no_clear_environ
, no_clone_flags
));
687 #if defined(OS_LINUX)
688 // Test a non-trival value for clone_flags.
689 // Don't test on Valgrind as it has limited support for clone().
690 if (!RunningOnValgrind()) {
691 EXPECT_EQ("wibble\n", TestLaunchProcess(echo_base_test
, env_changes
,
692 no_clear_environ
, CLONE_FS
));
696 "BASE_TEST=wibble\n",
698 print_env
, env_changes
, true /* clear_environ */, no_clone_flags
));
703 print_env
, env_changes
, true /* clear_environ */, no_clone_flags
));
707 TEST_F(ProcessUtilTest
, GetAppOutput
) {
710 #if defined(OS_ANDROID)
711 std::vector
<std::string
> argv
;
712 argv
.push_back("sh"); // Instead of /bin/sh, force path search to find it.
713 argv
.push_back("-c");
715 argv
.push_back("exit 0");
716 EXPECT_TRUE(base::GetAppOutput(base::CommandLine(argv
), &output
));
717 EXPECT_STREQ("", output
.c_str());
720 EXPECT_FALSE(base::GetAppOutput(base::CommandLine(argv
), &output
));
721 EXPECT_STREQ("", output
.c_str());
723 argv
[2] = "echo foobar42";
724 EXPECT_TRUE(base::GetAppOutput(base::CommandLine(argv
), &output
));
725 EXPECT_STREQ("foobar42\n", output
.c_str());
727 EXPECT_TRUE(base::GetAppOutput(base::CommandLine(FilePath("true")),
729 EXPECT_STREQ("", output
.c_str());
731 EXPECT_FALSE(base::GetAppOutput(base::CommandLine(FilePath("false")),
734 std::vector
<std::string
> argv
;
735 argv
.push_back("/bin/echo");
736 argv
.push_back("-n");
737 argv
.push_back("foobar42");
738 EXPECT_TRUE(base::GetAppOutput(base::CommandLine(argv
), &output
));
739 EXPECT_STREQ("foobar42", output
.c_str());
740 #endif // defined(OS_ANDROID)
743 // Flakes on Android, crbug.com/375840
744 #if defined(OS_ANDROID)
745 #define MAYBE_GetAppOutputRestricted DISABLED_GetAppOutputRestricted
747 #define MAYBE_GetAppOutputRestricted GetAppOutputRestricted
749 TEST_F(ProcessUtilTest
, MAYBE_GetAppOutputRestricted
) {
750 // Unfortunately, since we can't rely on the path, we need to know where
751 // everything is. So let's use /bin/sh, which is on every POSIX system, and
753 std::vector
<std::string
> argv
;
754 argv
.push_back(std::string(kShellPath
)); // argv[0]
755 argv
.push_back("-c"); // argv[1]
757 // On success, should set |output|. We use |/bin/sh -c 'exit 0'| instead of
758 // |true| since the location of the latter may be |/bin| or |/usr/bin| (and we
759 // need absolute paths).
760 argv
.push_back("exit 0"); // argv[2]; equivalent to "true"
761 std::string output
= "abc";
762 EXPECT_TRUE(base::GetAppOutputRestricted(base::CommandLine(argv
), &output
,
764 EXPECT_STREQ("", output
.c_str());
766 argv
[2] = "exit 1"; // equivalent to "false"
768 EXPECT_FALSE(base::GetAppOutputRestricted(base::CommandLine(argv
), &output
,
770 EXPECT_STREQ("", output
.c_str());
772 // Amount of output exactly equal to space allowed.
773 argv
[2] = "echo 123456789"; // (the sh built-in doesn't take "-n")
775 EXPECT_TRUE(base::GetAppOutputRestricted(base::CommandLine(argv
), &output
,
777 EXPECT_STREQ("123456789\n", output
.c_str());
779 // Amount of output greater than space allowed.
781 EXPECT_TRUE(base::GetAppOutputRestricted(base::CommandLine(argv
), &output
,
783 EXPECT_STREQ("12345", output
.c_str());
785 // Amount of output less than space allowed.
787 EXPECT_TRUE(base::GetAppOutputRestricted(base::CommandLine(argv
), &output
,
789 EXPECT_STREQ("123456789\n", output
.c_str());
791 // Zero space allowed.
793 EXPECT_TRUE(base::GetAppOutputRestricted(base::CommandLine(argv
), &output
,
795 EXPECT_STREQ("", output
.c_str());
798 #if !defined(OS_MACOSX) && !defined(OS_OPENBSD)
799 // TODO(benwells): GetAppOutputRestricted should terminate applications
800 // with SIGPIPE when we have enough output. http://crbug.com/88502
801 TEST_F(ProcessUtilTest
, GetAppOutputRestrictedSIGPIPE
) {
802 std::vector
<std::string
> argv
;
805 argv
.push_back(std::string(kShellPath
)); // argv[0]
806 argv
.push_back("-c");
807 #if defined(OS_ANDROID)
808 argv
.push_back("while echo 12345678901234567890; do :; done");
809 EXPECT_TRUE(base::GetAppOutputRestricted(base::CommandLine(argv
), &output
,
811 EXPECT_STREQ("1234567890", output
.c_str());
813 argv
.push_back("yes");
814 EXPECT_TRUE(base::GetAppOutputRestricted(base::CommandLine(argv
), &output
,
816 EXPECT_STREQ("y\ny\ny\ny\ny\n", output
.c_str());
821 #if defined(ADDRESS_SANITIZER) && defined(OS_MACOSX) && \
822 defined(ARCH_CPU_64_BITS)
823 // Times out under AddressSanitizer on 64-bit OS X, see
824 // http://crbug.com/298197.
825 #define MAYBE_GetAppOutputRestrictedNoZombies \
826 DISABLED_GetAppOutputRestrictedNoZombies
828 #define MAYBE_GetAppOutputRestrictedNoZombies GetAppOutputRestrictedNoZombies
830 TEST_F(ProcessUtilTest
, MAYBE_GetAppOutputRestrictedNoZombies
) {
831 std::vector
<std::string
> argv
;
833 argv
.push_back(std::string(kShellPath
)); // argv[0]
834 argv
.push_back("-c"); // argv[1]
835 argv
.push_back("echo 123456789012345678901234567890"); // argv[2]
837 // Run |GetAppOutputRestricted()| 300 (> default per-user processes on Mac OS
838 // 10.5) times with an output buffer big enough to capture all output.
839 for (int i
= 0; i
< 300; i
++) {
841 EXPECT_TRUE(base::GetAppOutputRestricted(base::CommandLine(argv
), &output
,
843 EXPECT_STREQ("123456789012345678901234567890\n", output
.c_str());
846 // Ditto, but with an output buffer too small to capture all output.
847 for (int i
= 0; i
< 300; i
++) {
849 EXPECT_TRUE(base::GetAppOutputRestricted(base::CommandLine(argv
), &output
,
851 EXPECT_STREQ("1234567890", output
.c_str());
855 TEST_F(ProcessUtilTest
, GetAppOutputWithExitCode
) {
856 // Test getting output from a successful application.
857 std::vector
<std::string
> argv
;
860 argv
.push_back(std::string(kShellPath
)); // argv[0]
861 argv
.push_back("-c"); // argv[1]
862 argv
.push_back("echo foo"); // argv[2];
863 EXPECT_TRUE(base::GetAppOutputWithExitCode(base::CommandLine(argv
), &output
,
865 EXPECT_STREQ("foo\n", output
.c_str());
866 EXPECT_EQ(exit_code
, 0);
868 // Test getting output from an application which fails with a specific exit
871 argv
[2] = "echo foo; exit 2";
872 EXPECT_TRUE(base::GetAppOutputWithExitCode(base::CommandLine(argv
), &output
,
874 EXPECT_STREQ("foo\n", output
.c_str());
875 EXPECT_EQ(exit_code
, 2);
878 TEST_F(ProcessUtilTest
, GetParentProcessId
) {
879 base::ProcessId ppid
= base::GetParentProcessId(base::GetCurrentProcId());
880 EXPECT_EQ(ppid
, getppid());
883 // TODO(port): port those unit tests.
884 bool IsProcessDead(base::ProcessHandle child
) {
885 // waitpid() will actually reap the process which is exactly NOT what we
886 // want to test for. The good thing is that if it can't find the process
887 // we'll get a nice value for errno which we can test for.
888 const pid_t result
= HANDLE_EINTR(waitpid(child
, NULL
, WNOHANG
));
889 return result
== -1 && errno
== ECHILD
;
892 TEST_F(ProcessUtilTest
, DelayedTermination
) {
893 base::Process child_process
= SpawnChild("process_util_test_never_die");
894 ASSERT_TRUE(child_process
.IsValid());
895 base::EnsureProcessTerminated(child_process
.Duplicate());
897 child_process
.WaitForExitWithTimeout(base::TimeDelta::FromSeconds(5),
900 // Check that process was really killed.
901 EXPECT_TRUE(IsProcessDead(child_process
.Handle()));
904 MULTIPROCESS_TEST_MAIN(process_util_test_never_die
) {
911 TEST_F(ProcessUtilTest
, ImmediateTermination
) {
912 base::Process child_process
= SpawnChild("process_util_test_die_immediately");
913 ASSERT_TRUE(child_process
.IsValid());
914 // Give it time to die.
916 base::EnsureProcessTerminated(child_process
.Duplicate());
918 // Check that process was really killed.
919 EXPECT_TRUE(IsProcessDead(child_process
.Handle()));
922 MULTIPROCESS_TEST_MAIN(process_util_test_die_immediately
) {
926 #if !defined(OS_ANDROID)
927 const char kPipeValue
= '\xcc';
929 class ReadFromPipeDelegate
: public base::LaunchOptions::PreExecDelegate
{
931 explicit ReadFromPipeDelegate(int fd
) : fd_(fd
) {}
932 ~ReadFromPipeDelegate() override
{}
933 void RunAsyncSafe() override
{
935 RAW_CHECK(HANDLE_EINTR(read(fd_
, &c
, 1)) == 1);
936 RAW_CHECK(IGNORE_EINTR(close(fd_
)) == 0);
937 RAW_CHECK(c
== kPipeValue
);
942 DISALLOW_COPY_AND_ASSIGN(ReadFromPipeDelegate
);
945 TEST_F(ProcessUtilTest
, PreExecHook
) {
947 ASSERT_EQ(0, pipe(pipe_fds
));
949 base::ScopedFD
read_fd(pipe_fds
[0]);
950 base::ScopedFD
write_fd(pipe_fds
[1]);
951 base::FileHandleMappingVector fds_to_remap
;
952 fds_to_remap
.push_back(std::make_pair(read_fd
.get(), read_fd
.get()));
954 ReadFromPipeDelegate
read_from_pipe_delegate(read_fd
.get());
955 base::LaunchOptions options
;
956 options
.fds_to_remap
= &fds_to_remap
;
957 options
.pre_exec_delegate
= &read_from_pipe_delegate
;
958 base::Process
process(SpawnChildWithOptions("SimpleChildProcess", options
));
959 ASSERT_TRUE(process
.IsValid());
962 ASSERT_EQ(1, HANDLE_EINTR(write(write_fd
.get(), &kPipeValue
, 1)));
965 EXPECT_TRUE(process
.WaitForExit(&exit_code
));
966 EXPECT_EQ(0, exit_code
);
968 #endif // !defined(OS_ANDROID)
970 #endif // defined(OS_POSIX)
972 #if defined(OS_LINUX)
973 const int kSuccess
= 0;
975 MULTIPROCESS_TEST_MAIN(CheckPidProcess
) {
976 const pid_t kInitPid
= 1;
977 const pid_t pid
= syscall(__NR_getpid
);
978 CHECK(pid
== kInitPid
);
979 CHECK(getpid() == pid
);
983 TEST_F(ProcessUtilTest
, CloneFlags
) {
984 if (RunningOnValgrind() ||
985 !base::PathExists(FilePath("/proc/self/ns/user")) ||
986 !base::PathExists(FilePath("/proc/self/ns/pid"))) {
987 // User or PID namespaces are not supported.
991 base::LaunchOptions options
;
992 options
.clone_flags
= CLONE_NEWUSER
| CLONE_NEWPID
;
994 base::Process
process(SpawnChildWithOptions("CheckPidProcess", options
));
995 ASSERT_TRUE(process
.IsValid());
998 EXPECT_TRUE(process
.WaitForExit(&exit_code
));
999 EXPECT_EQ(kSuccess
, exit_code
);
1002 TEST(ForkWithFlagsTest
, UpdatesPidCache
) {
1003 // The libc clone function, which allows ForkWithFlags to keep the pid cache
1004 // up to date, does not work on Valgrind.
1005 if (RunningOnValgrind()) {
1009 // Warm up the libc pid cache, if there is one.
1010 ASSERT_EQ(syscall(__NR_getpid
), getpid());
1014 base::ForkWithFlags(SIGCHLD
| CLONE_CHILD_SETTID
, nullptr, &ctid
);
1016 // In child. Check both the raw getpid syscall and the libc getpid wrapper
1017 // (which may rely on a pid cache).
1018 RAW_CHECK(syscall(__NR_getpid
) == ctid
);
1019 RAW_CHECK(getpid() == ctid
);
1025 ASSERT_EQ(pid
, HANDLE_EINTR(waitpid(pid
, &status
, 0)));
1026 ASSERT_TRUE(WIFEXITED(status
));
1027 EXPECT_EQ(kSuccess
, WEXITSTATUS(status
));
1030 MULTIPROCESS_TEST_MAIN(CheckCwdProcess
) {
1031 base::FilePath expected
;
1032 CHECK(base::GetTempDir(&expected
));
1033 base::FilePath actual
;
1034 CHECK(base::GetCurrentDirectory(&actual
));
1035 CHECK(actual
== expected
);
1039 TEST_F(ProcessUtilTest
, CurrentDirectory
) {
1040 // TODO(rickyz): Add support for passing arguments to multiprocess children,
1041 // then create a special directory for this test.
1042 base::FilePath tmp_dir
;
1043 ASSERT_TRUE(base::GetTempDir(&tmp_dir
));
1045 base::LaunchOptions options
;
1046 options
.current_directory
= tmp_dir
;
1048 base::Process
process(SpawnChildWithOptions("CheckCwdProcess", options
));
1049 ASSERT_TRUE(process
.IsValid());
1052 EXPECT_TRUE(process
.WaitForExit(&exit_code
));
1053 EXPECT_EQ(kSuccess
, exit_code
);
1056 TEST_F(ProcessUtilTest
, InvalidCurrentDirectory
) {
1057 base::LaunchOptions options
;
1058 options
.current_directory
= base::FilePath("/dev/null");
1060 base::Process
process(SpawnChildWithOptions("SimpleChildProcess", options
));
1061 ASSERT_TRUE(process
.IsValid());
1063 int exit_code
= kSuccess
;
1064 EXPECT_TRUE(process
.WaitForExit(&exit_code
));
1065 EXPECT_NE(kSuccess
, exit_code
);