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());
154 EXPECT_TRUE(base::WaitForSingleProcess(process
.Handle(),
155 TestTimeouts::action_max_timeout()));
158 MULTIPROCESS_TEST_MAIN(SlowChildProcess
) {
159 WaitToDie(ProcessUtilTest::GetSignalFilePath(kSignalFileSlow
).c_str());
163 TEST_F(ProcessUtilTest
, KillSlowChild
) {
164 const std::string signal_file
=
165 ProcessUtilTest::GetSignalFilePath(kSignalFileSlow
);
166 remove(signal_file
.c_str());
167 base::Process process
= SpawnChild("SlowChildProcess");
168 ASSERT_TRUE(process
.IsValid());
169 SignalChildren(signal_file
.c_str());
170 EXPECT_TRUE(base::WaitForSingleProcess(process
.Handle(),
171 TestTimeouts::action_max_timeout()));
172 remove(signal_file
.c_str());
175 // Times out on Linux and Win, flakes on other platforms, http://crbug.com/95058
176 TEST_F(ProcessUtilTest
, DISABLED_GetTerminationStatusExit
) {
177 const std::string signal_file
=
178 ProcessUtilTest::GetSignalFilePath(kSignalFileSlow
);
179 remove(signal_file
.c_str());
180 base::Process process
= SpawnChild("SlowChildProcess");
181 ASSERT_TRUE(process
.IsValid());
184 EXPECT_EQ(base::TERMINATION_STATUS_STILL_RUNNING
,
185 base::GetTerminationStatus(process
.Handle(), &exit_code
));
186 EXPECT_EQ(kExpectedStillRunningExitCode
, exit_code
);
188 SignalChildren(signal_file
.c_str());
190 base::TerminationStatus status
=
191 WaitForChildTermination(process
.Handle(), &exit_code
);
192 EXPECT_EQ(base::TERMINATION_STATUS_NORMAL_TERMINATION
, status
);
193 EXPECT_EQ(0, exit_code
);
194 remove(signal_file
.c_str());
198 // TODO(cpu): figure out how to test this in other platforms.
199 TEST_F(ProcessUtilTest
, GetProcId
) {
200 base::ProcessId id1
= base::GetProcId(GetCurrentProcess());
202 base::Process process
= SpawnChild("SimpleChildProcess");
203 ASSERT_TRUE(process
.IsValid());
204 base::ProcessId id2
= process
.pid();
210 #if !defined(OS_MACOSX)
211 // This test is disabled on Mac, since it's flaky due to ReportCrash
212 // taking a variable amount of time to parse and load the debug and
213 // symbol data for this unit test's executable before firing the
216 // TODO(gspencer): turn this test process into a very small program
217 // with no symbols (instead of using the multiprocess testing
218 // framework) to reduce the ReportCrash overhead.
219 const char kSignalFileCrash
[] = "CrashingChildProcess.die";
221 MULTIPROCESS_TEST_MAIN(CrashingChildProcess
) {
222 WaitToDie(ProcessUtilTest::GetSignalFilePath(kSignalFileCrash
).c_str());
223 #if defined(OS_POSIX)
224 // Have to disable to signal handler for segv so we can get a crash
225 // instead of an abnormal termination through the crash dump handler.
226 ::signal(SIGSEGV
, SIG_DFL
);
228 // Make this process have a segmentation fault.
229 volatile int* oops
= NULL
;
234 // This test intentionally crashes, so we don't need to run it under
236 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
237 #define MAYBE_GetTerminationStatusCrash DISABLED_GetTerminationStatusCrash
239 #define MAYBE_GetTerminationStatusCrash GetTerminationStatusCrash
241 TEST_F(ProcessUtilTest
, MAYBE_GetTerminationStatusCrash
) {
242 const std::string signal_file
=
243 ProcessUtilTest::GetSignalFilePath(kSignalFileCrash
);
244 remove(signal_file
.c_str());
245 base::Process process
= SpawnChild("CrashingChildProcess");
246 ASSERT_TRUE(process
.IsValid());
249 EXPECT_EQ(base::TERMINATION_STATUS_STILL_RUNNING
,
250 base::GetTerminationStatus(process
.Handle(), &exit_code
));
251 EXPECT_EQ(kExpectedStillRunningExitCode
, exit_code
);
253 SignalChildren(signal_file
.c_str());
255 base::TerminationStatus status
=
256 WaitForChildTermination(process
.Handle(), &exit_code
);
257 EXPECT_EQ(base::TERMINATION_STATUS_PROCESS_CRASHED
, status
);
260 EXPECT_EQ(0xc0000005, exit_code
);
261 #elif defined(OS_POSIX)
262 int signaled
= WIFSIGNALED(exit_code
);
263 EXPECT_NE(0, signaled
);
264 int signal
= WTERMSIG(exit_code
);
265 EXPECT_EQ(SIGSEGV
, signal
);
268 // Reset signal handlers back to "normal".
269 base::debug::EnableInProcessStackDumping();
270 remove(signal_file
.c_str());
272 #endif // !defined(OS_MACOSX)
274 MULTIPROCESS_TEST_MAIN(KilledChildProcess
) {
275 WaitToDie(ProcessUtilTest::GetSignalFilePath(kSignalFileKill
).c_str());
278 HANDLE handle
= ::OpenProcess(PROCESS_ALL_ACCESS
, 0, ::GetCurrentProcessId());
279 ::TerminateProcess(handle
, kExpectedKilledExitCode
);
280 #elif defined(OS_POSIX)
281 // Send a SIGKILL to this process, just like the OOM killer would.
282 ::kill(getpid(), SIGKILL
);
287 TEST_F(ProcessUtilTest
, GetTerminationStatusKill
) {
288 const std::string signal_file
=
289 ProcessUtilTest::GetSignalFilePath(kSignalFileKill
);
290 remove(signal_file
.c_str());
291 base::Process process
= SpawnChild("KilledChildProcess");
292 ASSERT_TRUE(process
.IsValid());
295 EXPECT_EQ(base::TERMINATION_STATUS_STILL_RUNNING
,
296 base::GetTerminationStatus(process
.Handle(), &exit_code
));
297 EXPECT_EQ(kExpectedStillRunningExitCode
, exit_code
);
299 SignalChildren(signal_file
.c_str());
301 base::TerminationStatus status
=
302 WaitForChildTermination(process
.Handle(), &exit_code
);
303 EXPECT_EQ(base::TERMINATION_STATUS_PROCESS_WAS_KILLED
, status
);
305 EXPECT_EQ(kExpectedKilledExitCode
, exit_code
);
306 #elif defined(OS_POSIX)
307 int signaled
= WIFSIGNALED(exit_code
);
308 EXPECT_NE(0, signaled
);
309 int signal
= WTERMSIG(exit_code
);
310 EXPECT_EQ(SIGKILL
, signal
);
312 remove(signal_file
.c_str());
316 // TODO(estade): if possible, port this test.
317 TEST_F(ProcessUtilTest
, GetAppOutput
) {
318 // Let's create a decently long message.
320 for (int i
= 0; i
< 1025; i
++) { // 1025 so it does not end on a kilo-byte
324 // cmd.exe's echo always adds a \r\n to its output.
325 std::string
expected(message
);
328 FilePath
cmd(L
"cmd.exe");
329 base::CommandLine
cmd_line(cmd
);
330 cmd_line
.AppendArg("/c");
331 cmd_line
.AppendArg("echo " + message
+ "");
333 ASSERT_TRUE(base::GetAppOutput(cmd_line
, &output
));
334 EXPECT_EQ(expected
, output
);
336 // Let's make sure stderr is ignored.
337 base::CommandLine
other_cmd_line(cmd
);
338 other_cmd_line
.AppendArg("/c");
339 // http://msdn.microsoft.com/library/cc772622.aspx
340 cmd_line
.AppendArg("echo " + message
+ " >&2");
342 ASSERT_TRUE(base::GetAppOutput(other_cmd_line
, &output
));
343 EXPECT_EQ("", output
);
346 // TODO(estade): if possible, port this test.
347 TEST_F(ProcessUtilTest
, LaunchAsUser
) {
348 base::UserTokenHandle token
;
349 ASSERT_TRUE(OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS
, &token
));
350 base::LaunchOptions options
;
351 options
.as_user
= token
;
352 EXPECT_TRUE(base::LaunchProcess(MakeCmdLine("SimpleChildProcess"),
356 static const char kEventToTriggerHandleSwitch
[] = "event-to-trigger-handle";
358 MULTIPROCESS_TEST_MAIN(TriggerEventChildProcess
) {
359 std::string handle_value_string
=
360 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
361 kEventToTriggerHandleSwitch
);
362 CHECK(!handle_value_string
.empty());
364 uint64 handle_value_uint64
;
365 CHECK(base::StringToUint64(handle_value_string
, &handle_value_uint64
));
366 // Give ownership of the handle to |event|.
367 base::WaitableEvent
event(base::win::ScopedHandle(
368 reinterpret_cast<HANDLE
>(handle_value_uint64
)));
375 TEST_F(ProcessUtilTest
, InheritSpecifiedHandles
) {
376 // Manually create the event, so that it can be inheritable.
377 SECURITY_ATTRIBUTES security_attributes
= {};
378 security_attributes
.nLength
= static_cast<DWORD
>(sizeof(security_attributes
));
379 security_attributes
.lpSecurityDescriptor
= NULL
;
380 security_attributes
.bInheritHandle
= true;
382 // Takes ownership of the event handle.
383 base::WaitableEvent
event(base::win::ScopedHandle(
384 CreateEvent(&security_attributes
, true, false, NULL
)));
385 base::HandlesToInheritVector handles_to_inherit
;
386 handles_to_inherit
.push_back(event
.handle());
387 base::LaunchOptions options
;
388 options
.handles_to_inherit
= &handles_to_inherit
;
390 base::CommandLine cmd_line
= MakeCmdLine("TriggerEventChildProcess");
391 cmd_line
.AppendSwitchASCII(kEventToTriggerHandleSwitch
,
392 base::Uint64ToString(reinterpret_cast<uint64
>(event
.handle())));
394 // This functionality actually requires Vista or later. Make sure that it
395 // fails properly on XP.
396 if (base::win::GetVersion() < base::win::VERSION_VISTA
) {
397 EXPECT_FALSE(base::LaunchProcess(cmd_line
, options
).IsValid());
401 // Launch the process and wait for it to trigger the event.
402 ASSERT_TRUE(base::LaunchProcess(cmd_line
, options
).IsValid());
403 EXPECT_TRUE(event
.TimedWait(TestTimeouts::action_max_timeout()));
405 #endif // defined(OS_WIN)
407 #if defined(OS_POSIX)
411 // Returns the maximum number of files that a process can have open.
412 // Returns 0 on error.
413 int GetMaxFilesOpenInProcess() {
415 if (getrlimit(RLIMIT_NOFILE
, &rlim
) != 0) {
419 // rlim_t is a uint64 - clip to maxint. We do this since FD #s are ints
420 // which are all 32 bits on the supported platforms.
421 rlim_t max_int
= static_cast<rlim_t
>(std::numeric_limits
<int32
>::max());
422 if (rlim
.rlim_cur
> max_int
) {
426 return rlim
.rlim_cur
;
429 const int kChildPipe
= 20; // FD # for write end of pipe in child process.
431 #if defined(OS_MACOSX)
433 // <http://opensource.apple.com/source/xnu/xnu-2422.1.72/bsd/sys/guarded.h>
434 #if !defined(_GUARDID_T)
436 typedef __uint64_t guardid_t
;
439 // From .../MacOSX10.9.sdk/usr/include/sys/syscall.h
440 #if !defined(SYS_change_fdguard_np)
441 #define SYS_change_fdguard_np 444
444 // <http://opensource.apple.com/source/xnu/xnu-2422.1.72/bsd/sys/guarded.h>
445 #if !defined(GUARD_DUP)
446 #define GUARD_DUP (1u << 1)
449 // <http://opensource.apple.com/source/xnu/xnu-2422.1.72/bsd/kern/kern_guarded.c?txt>
451 // Atomically replaces |guard|/|guardflags| with |nguard|/|nguardflags| on |fd|.
452 int change_fdguard_np(int fd
,
453 const guardid_t
*guard
, u_int guardflags
,
454 const guardid_t
*nguard
, u_int nguardflags
,
456 return syscall(SYS_change_fdguard_np
, fd
, guard
, guardflags
,
457 nguard
, nguardflags
, fdflagsp
);
460 // Attempt to set a file-descriptor guard on |fd|. In case of success, remove
461 // it and return |true| to indicate that it can be guarded. Returning |false|
462 // means either that |fd| is guarded by some other code, or more likely EBADF.
464 // Starting with 10.9, libdispatch began setting GUARD_DUP on a file descriptor.
465 // Unfortunately, it is spun up as part of +[NSApplication initialize], which is
466 // not really something that Chromium can avoid using on OSX. See
467 // <http://crbug.com/338157>. This function allows querying whether the file
468 // descriptor is guarded before attempting to close it.
469 bool CanGuardFd(int fd
) {
470 // The syscall is first provided in 10.9/Mavericks.
471 if (!base::mac::IsOSMavericksOrLater())
474 // Saves the original flags to reset later.
475 int original_fdflags
= 0;
477 // This can be any value at all, it just has to match up between the two
479 const guardid_t kGuard
= 15;
481 // Attempt to change the guard. This can fail with EBADF if the file
482 // descriptor is bad, or EINVAL if the fd already has a guard set.
484 change_fdguard_np(fd
, NULL
, 0, &kGuard
, GUARD_DUP
, &original_fdflags
);
488 // Remove the guard. It should not be possible to fail in removing the guard
490 ret
= change_fdguard_np(fd
, &kGuard
, GUARD_DUP
, NULL
, 0, &original_fdflags
);
499 MULTIPROCESS_TEST_MAIN(ProcessUtilsLeakFDChildProcess
) {
500 // This child process counts the number of open FDs, it then writes that
501 // number out to a pipe connected to the parent.
502 int num_open_files
= 0;
503 int write_pipe
= kChildPipe
;
504 int max_files
= GetMaxFilesOpenInProcess();
505 for (int i
= STDERR_FILENO
+ 1; i
< max_files
; i
++) {
506 #if defined(OS_MACOSX)
507 // Ignore guarded or invalid file descriptors.
512 if (i
!= kChildPipe
) {
514 if ((fd
= HANDLE_EINTR(dup(i
))) != -1) {
521 int written
= HANDLE_EINTR(write(write_pipe
, &num_open_files
,
522 sizeof(num_open_files
)));
523 DCHECK_EQ(static_cast<size_t>(written
), sizeof(num_open_files
));
524 int ret
= IGNORE_EINTR(close(write_pipe
));
530 int ProcessUtilTest::CountOpenFDsInChild() {
535 base::FileHandleMappingVector fd_mapping_vec
;
536 fd_mapping_vec
.push_back(std::pair
<int, int>(fds
[1], kChildPipe
));
537 base::LaunchOptions options
;
538 options
.fds_to_remap
= &fd_mapping_vec
;
539 base::Process process
=
540 SpawnChildWithOptions("ProcessUtilsLeakFDChildProcess", options
);
541 CHECK(process
.IsValid());
542 int ret
= IGNORE_EINTR(close(fds
[1]));
545 // Read number of open files in client process from pipe;
546 int num_open_files
= -1;
548 HANDLE_EINTR(read(fds
[0], &num_open_files
, sizeof(num_open_files
)));
549 CHECK_EQ(bytes_read
, static_cast<ssize_t
>(sizeof(num_open_files
)));
551 #if defined(THREAD_SANITIZER)
552 // Compiler-based ThreadSanitizer makes this test slow.
553 CHECK(base::WaitForSingleProcess(process
.Handle(),
554 base::TimeDelta::FromSeconds(3)));
556 CHECK(base::WaitForSingleProcess(process
.Handle(),
557 base::TimeDelta::FromSeconds(1)));
559 ret
= IGNORE_EINTR(close(fds
[0]));
562 return num_open_files
;
565 #if defined(ADDRESS_SANITIZER) || defined(THREAD_SANITIZER)
566 // ProcessUtilTest.FDRemapping is flaky when ran under xvfb-run on Precise.
567 // The problem is 100% reproducible with both ASan and TSan.
568 // See http://crbug.com/136720.
569 #define MAYBE_FDRemapping DISABLED_FDRemapping
571 #define MAYBE_FDRemapping FDRemapping
573 TEST_F(ProcessUtilTest
, MAYBE_FDRemapping
) {
574 int fds_before
= CountOpenFDsInChild();
576 // open some dummy fds to make sure they don't propagate over to the
578 int dev_null
= open("/dev/null", O_RDONLY
);
580 socketpair(AF_UNIX
, SOCK_STREAM
, 0, sockets
);
582 int fds_after
= CountOpenFDsInChild();
584 ASSERT_EQ(fds_after
, fds_before
);
587 ret
= IGNORE_EINTR(close(sockets
[0]));
589 ret
= IGNORE_EINTR(close(sockets
[1]));
591 ret
= IGNORE_EINTR(close(dev_null
));
597 std::string
TestLaunchProcess(const std::vector
<std::string
>& args
,
598 const base::EnvironmentMap
& env_changes
,
599 const bool clear_environ
,
600 const int clone_flags
) {
601 base::FileHandleMappingVector fds_to_remap
;
604 PCHECK(pipe(fds
) == 0);
606 fds_to_remap
.push_back(std::make_pair(fds
[1], 1));
607 base::LaunchOptions options
;
609 options
.environ
= env_changes
;
610 options
.clear_environ
= clear_environ
;
611 options
.fds_to_remap
= &fds_to_remap
;
612 #if defined(OS_LINUX)
613 options
.clone_flags
= clone_flags
;
615 CHECK_EQ(0, clone_flags
);
617 EXPECT_TRUE(base::LaunchProcess(args
, options
).IsValid());
618 PCHECK(IGNORE_EINTR(close(fds
[1])) == 0);
621 const ssize_t n
= HANDLE_EINTR(read(fds
[0], buf
, sizeof(buf
)));
623 PCHECK(IGNORE_EINTR(close(fds
[0])) == 0);
625 return std::string(buf
, n
);
628 const char kLargeString
[] =
629 "0123456789012345678901234567890123456789012345678901234567890123456789"
630 "0123456789012345678901234567890123456789012345678901234567890123456789"
631 "0123456789012345678901234567890123456789012345678901234567890123456789"
632 "0123456789012345678901234567890123456789012345678901234567890123456789"
633 "0123456789012345678901234567890123456789012345678901234567890123456789"
634 "0123456789012345678901234567890123456789012345678901234567890123456789"
635 "0123456789012345678901234567890123456789012345678901234567890123456789";
639 TEST_F(ProcessUtilTest
, LaunchProcess
) {
640 base::EnvironmentMap env_changes
;
641 std::vector
<std::string
> echo_base_test
;
642 echo_base_test
.push_back(kPosixShell
);
643 echo_base_test
.push_back("-c");
644 echo_base_test
.push_back("echo $BASE_TEST");
646 std::vector
<std::string
> print_env
;
647 print_env
.push_back("/usr/bin/env");
648 const int no_clone_flags
= 0;
649 const bool no_clear_environ
= false;
651 const char kBaseTest
[] = "BASE_TEST";
653 env_changes
[kBaseTest
] = "bar";
656 echo_base_test
, env_changes
, no_clear_environ
, no_clone_flags
));
659 EXPECT_EQ(0, setenv(kBaseTest
, "testing", 1 /* override */));
660 EXPECT_EQ("testing\n",
662 echo_base_test
, env_changes
, no_clear_environ
, no_clone_flags
));
664 env_changes
[kBaseTest
] = std::string();
667 echo_base_test
, env_changes
, no_clear_environ
, no_clone_flags
));
669 env_changes
[kBaseTest
] = "foo";
672 echo_base_test
, env_changes
, no_clear_environ
, no_clone_flags
));
675 EXPECT_EQ(0, setenv(kBaseTest
, kLargeString
, 1 /* override */));
676 EXPECT_EQ(std::string(kLargeString
) + "\n",
678 echo_base_test
, env_changes
, no_clear_environ
, no_clone_flags
));
680 env_changes
[kBaseTest
] = "wibble";
681 EXPECT_EQ("wibble\n",
683 echo_base_test
, env_changes
, no_clear_environ
, no_clone_flags
));
685 #if defined(OS_LINUX)
686 // Test a non-trival value for clone_flags.
687 // Don't test on Valgrind as it has limited support for clone().
688 if (!RunningOnValgrind()) {
689 EXPECT_EQ("wibble\n", TestLaunchProcess(echo_base_test
, env_changes
,
690 no_clear_environ
, CLONE_FS
));
694 "BASE_TEST=wibble\n",
696 print_env
, env_changes
, true /* clear_environ */, no_clone_flags
));
701 print_env
, env_changes
, true /* clear_environ */, no_clone_flags
));
705 TEST_F(ProcessUtilTest
, GetAppOutput
) {
708 #if defined(OS_ANDROID)
709 std::vector
<std::string
> argv
;
710 argv
.push_back("sh"); // Instead of /bin/sh, force path search to find it.
711 argv
.push_back("-c");
713 argv
.push_back("exit 0");
714 EXPECT_TRUE(base::GetAppOutput(base::CommandLine(argv
), &output
));
715 EXPECT_STREQ("", output
.c_str());
718 EXPECT_FALSE(base::GetAppOutput(base::CommandLine(argv
), &output
));
719 EXPECT_STREQ("", output
.c_str());
721 argv
[2] = "echo foobar42";
722 EXPECT_TRUE(base::GetAppOutput(base::CommandLine(argv
), &output
));
723 EXPECT_STREQ("foobar42\n", output
.c_str());
725 EXPECT_TRUE(base::GetAppOutput(base::CommandLine(FilePath("true")),
727 EXPECT_STREQ("", output
.c_str());
729 EXPECT_FALSE(base::GetAppOutput(base::CommandLine(FilePath("false")),
732 std::vector
<std::string
> argv
;
733 argv
.push_back("/bin/echo");
734 argv
.push_back("-n");
735 argv
.push_back("foobar42");
736 EXPECT_TRUE(base::GetAppOutput(base::CommandLine(argv
), &output
));
737 EXPECT_STREQ("foobar42", output
.c_str());
738 #endif // defined(OS_ANDROID)
741 // Flakes on Android, crbug.com/375840
742 #if defined(OS_ANDROID)
743 #define MAYBE_GetAppOutputRestricted DISABLED_GetAppOutputRestricted
745 #define MAYBE_GetAppOutputRestricted GetAppOutputRestricted
747 TEST_F(ProcessUtilTest
, MAYBE_GetAppOutputRestricted
) {
748 // Unfortunately, since we can't rely on the path, we need to know where
749 // everything is. So let's use /bin/sh, which is on every POSIX system, and
751 std::vector
<std::string
> argv
;
752 argv
.push_back(std::string(kShellPath
)); // argv[0]
753 argv
.push_back("-c"); // argv[1]
755 // On success, should set |output|. We use |/bin/sh -c 'exit 0'| instead of
756 // |true| since the location of the latter may be |/bin| or |/usr/bin| (and we
757 // need absolute paths).
758 argv
.push_back("exit 0"); // argv[2]; equivalent to "true"
759 std::string output
= "abc";
760 EXPECT_TRUE(base::GetAppOutputRestricted(base::CommandLine(argv
), &output
,
762 EXPECT_STREQ("", output
.c_str());
764 argv
[2] = "exit 1"; // equivalent to "false"
766 EXPECT_FALSE(base::GetAppOutputRestricted(base::CommandLine(argv
), &output
,
768 EXPECT_STREQ("", output
.c_str());
770 // Amount of output exactly equal to space allowed.
771 argv
[2] = "echo 123456789"; // (the sh built-in doesn't take "-n")
773 EXPECT_TRUE(base::GetAppOutputRestricted(base::CommandLine(argv
), &output
,
775 EXPECT_STREQ("123456789\n", output
.c_str());
777 // Amount of output greater than space allowed.
779 EXPECT_TRUE(base::GetAppOutputRestricted(base::CommandLine(argv
), &output
,
781 EXPECT_STREQ("12345", output
.c_str());
783 // Amount of output less than space allowed.
785 EXPECT_TRUE(base::GetAppOutputRestricted(base::CommandLine(argv
), &output
,
787 EXPECT_STREQ("123456789\n", output
.c_str());
789 // Zero space allowed.
791 EXPECT_TRUE(base::GetAppOutputRestricted(base::CommandLine(argv
), &output
,
793 EXPECT_STREQ("", output
.c_str());
796 #if !defined(OS_MACOSX) && !defined(OS_OPENBSD)
797 // TODO(benwells): GetAppOutputRestricted should terminate applications
798 // with SIGPIPE when we have enough output. http://crbug.com/88502
799 TEST_F(ProcessUtilTest
, GetAppOutputRestrictedSIGPIPE
) {
800 std::vector
<std::string
> argv
;
803 argv
.push_back(std::string(kShellPath
)); // argv[0]
804 argv
.push_back("-c");
805 #if defined(OS_ANDROID)
806 argv
.push_back("while echo 12345678901234567890; do :; done");
807 EXPECT_TRUE(base::GetAppOutputRestricted(base::CommandLine(argv
), &output
,
809 EXPECT_STREQ("1234567890", output
.c_str());
811 argv
.push_back("yes");
812 EXPECT_TRUE(base::GetAppOutputRestricted(base::CommandLine(argv
), &output
,
814 EXPECT_STREQ("y\ny\ny\ny\ny\n", output
.c_str());
819 #if defined(ADDRESS_SANITIZER) && defined(OS_MACOSX) && \
820 defined(ARCH_CPU_64_BITS)
821 // Times out under AddressSanitizer on 64-bit OS X, see
822 // http://crbug.com/298197.
823 #define MAYBE_GetAppOutputRestrictedNoZombies \
824 DISABLED_GetAppOutputRestrictedNoZombies
826 #define MAYBE_GetAppOutputRestrictedNoZombies GetAppOutputRestrictedNoZombies
828 TEST_F(ProcessUtilTest
, MAYBE_GetAppOutputRestrictedNoZombies
) {
829 std::vector
<std::string
> argv
;
831 argv
.push_back(std::string(kShellPath
)); // argv[0]
832 argv
.push_back("-c"); // argv[1]
833 argv
.push_back("echo 123456789012345678901234567890"); // argv[2]
835 // Run |GetAppOutputRestricted()| 300 (> default per-user processes on Mac OS
836 // 10.5) times with an output buffer big enough to capture all output.
837 for (int i
= 0; i
< 300; i
++) {
839 EXPECT_TRUE(base::GetAppOutputRestricted(base::CommandLine(argv
), &output
,
841 EXPECT_STREQ("123456789012345678901234567890\n", output
.c_str());
844 // Ditto, but with an output buffer too small to capture all output.
845 for (int i
= 0; i
< 300; i
++) {
847 EXPECT_TRUE(base::GetAppOutputRestricted(base::CommandLine(argv
), &output
,
849 EXPECT_STREQ("1234567890", output
.c_str());
853 TEST_F(ProcessUtilTest
, GetAppOutputWithExitCode
) {
854 // Test getting output from a successful application.
855 std::vector
<std::string
> argv
;
858 argv
.push_back(std::string(kShellPath
)); // argv[0]
859 argv
.push_back("-c"); // argv[1]
860 argv
.push_back("echo foo"); // argv[2];
861 EXPECT_TRUE(base::GetAppOutputWithExitCode(base::CommandLine(argv
), &output
,
863 EXPECT_STREQ("foo\n", output
.c_str());
864 EXPECT_EQ(exit_code
, 0);
866 // Test getting output from an application which fails with a specific exit
869 argv
[2] = "echo foo; exit 2";
870 EXPECT_TRUE(base::GetAppOutputWithExitCode(base::CommandLine(argv
), &output
,
872 EXPECT_STREQ("foo\n", output
.c_str());
873 EXPECT_EQ(exit_code
, 2);
876 TEST_F(ProcessUtilTest
, GetParentProcessId
) {
877 base::ProcessId ppid
= base::GetParentProcessId(base::GetCurrentProcId());
878 EXPECT_EQ(ppid
, getppid());
881 // TODO(port): port those unit tests.
882 bool IsProcessDead(base::ProcessHandle child
) {
883 // waitpid() will actually reap the process which is exactly NOT what we
884 // want to test for. The good thing is that if it can't find the process
885 // we'll get a nice value for errno which we can test for.
886 const pid_t result
= HANDLE_EINTR(waitpid(child
, NULL
, WNOHANG
));
887 return result
== -1 && errno
== ECHILD
;
890 TEST_F(ProcessUtilTest
, DelayedTermination
) {
891 base::Process child_process
= SpawnChild("process_util_test_never_die");
892 ASSERT_TRUE(child_process
.IsValid());
893 base::EnsureProcessTerminated(child_process
.Duplicate());
894 base::WaitForSingleProcess(child_process
.Handle(),
895 base::TimeDelta::FromSeconds(5));
897 // Check that process was really killed.
898 EXPECT_TRUE(IsProcessDead(child_process
.Handle()));
901 MULTIPROCESS_TEST_MAIN(process_util_test_never_die
) {
908 TEST_F(ProcessUtilTest
, ImmediateTermination
) {
909 base::Process child_process
= SpawnChild("process_util_test_die_immediately");
910 ASSERT_TRUE(child_process
.IsValid());
911 // Give it time to die.
913 base::EnsureProcessTerminated(child_process
.Duplicate());
915 // Check that process was really killed.
916 EXPECT_TRUE(IsProcessDead(child_process
.Handle()));
919 MULTIPROCESS_TEST_MAIN(process_util_test_die_immediately
) {
923 #if !defined(OS_ANDROID)
924 const char kPipeValue
= '\xcc';
926 class ReadFromPipeDelegate
: public base::LaunchOptions::PreExecDelegate
{
928 explicit ReadFromPipeDelegate(int fd
) : fd_(fd
) {}
929 ~ReadFromPipeDelegate() override
{}
930 void RunAsyncSafe() override
{
932 RAW_CHECK(HANDLE_EINTR(read(fd_
, &c
, 1)) == 1);
933 RAW_CHECK(IGNORE_EINTR(close(fd_
)) == 0);
934 RAW_CHECK(c
== kPipeValue
);
939 DISALLOW_COPY_AND_ASSIGN(ReadFromPipeDelegate
);
942 TEST_F(ProcessUtilTest
, PreExecHook
) {
944 ASSERT_EQ(0, pipe(pipe_fds
));
946 base::ScopedFD
read_fd(pipe_fds
[0]);
947 base::ScopedFD
write_fd(pipe_fds
[1]);
948 base::FileHandleMappingVector fds_to_remap
;
949 fds_to_remap
.push_back(std::make_pair(read_fd
.get(), read_fd
.get()));
951 ReadFromPipeDelegate
read_from_pipe_delegate(read_fd
.get());
952 base::LaunchOptions options
;
953 options
.fds_to_remap
= &fds_to_remap
;
954 options
.pre_exec_delegate
= &read_from_pipe_delegate
;
955 base::Process
process(SpawnChildWithOptions("SimpleChildProcess", options
));
956 ASSERT_TRUE(process
.IsValid());
959 ASSERT_EQ(1, HANDLE_EINTR(write(write_fd
.get(), &kPipeValue
, 1)));
962 EXPECT_TRUE(process
.WaitForExit(&exit_code
));
963 EXPECT_EQ(0, exit_code
);
965 #endif // !defined(OS_ANDROID)
967 #endif // defined(OS_POSIX)
969 #if defined(OS_LINUX)
970 const int kSuccess
= 0;
972 MULTIPROCESS_TEST_MAIN(CheckPidProcess
) {
973 const pid_t kInitPid
= 1;
974 const pid_t pid
= syscall(__NR_getpid
);
975 CHECK(pid
== kInitPid
);
976 CHECK(getpid() == pid
);
980 TEST_F(ProcessUtilTest
, CloneFlags
) {
981 if (RunningOnValgrind() ||
982 !base::PathExists(FilePath("/proc/self/ns/user")) ||
983 !base::PathExists(FilePath("/proc/self/ns/pid"))) {
984 // User or PID namespaces are not supported.
988 base::LaunchOptions options
;
989 options
.clone_flags
= CLONE_NEWUSER
| CLONE_NEWPID
;
991 base::Process
process(SpawnChildWithOptions("CheckPidProcess", options
));
992 ASSERT_TRUE(process
.IsValid());
995 EXPECT_TRUE(process
.WaitForExit(&exit_code
));
996 EXPECT_EQ(kSuccess
, exit_code
);
999 TEST(ForkWithFlagsTest
, UpdatesPidCache
) {
1000 // The libc clone function, which allows ForkWithFlags to keep the pid cache
1001 // up to date, does not work on Valgrind.
1002 if (RunningOnValgrind()) {
1006 // Warm up the libc pid cache, if there is one.
1007 ASSERT_EQ(syscall(__NR_getpid
), getpid());
1011 base::ForkWithFlags(SIGCHLD
| CLONE_CHILD_SETTID
, nullptr, &ctid
);
1013 // In child. Check both the raw getpid syscall and the libc getpid wrapper
1014 // (which may rely on a pid cache).
1015 RAW_CHECK(syscall(__NR_getpid
) == ctid
);
1016 RAW_CHECK(getpid() == ctid
);
1022 ASSERT_EQ(pid
, HANDLE_EINTR(waitpid(pid
, &status
, 0)));
1023 ASSERT_TRUE(WIFEXITED(status
));
1024 EXPECT_EQ(kSuccess
, WEXITSTATUS(status
));