Explicitly add python-numpy dependency to install-build-deps.
[chromium-blink-merge.git] / base / process / process_util_unittest.cc
blobd846d1acfae2634c4aff68f1498b21eaac1b45f8
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 #include "base/mac/mac_util.h"
54 #endif
56 using base::FilePath;
58 namespace {
60 #if defined(OS_ANDROID)
61 const char kShellPath[] = "/system/bin/sh";
62 const char kPosixShell[] = "sh";
63 #else
64 const char kShellPath[] = "/bin/sh";
65 const char kPosixShell[] = "bash";
66 #endif
68 const char kSignalFileSlow[] = "SlowChildProcess.die";
69 const char kSignalFileKill[] = "KilledChildProcess.die";
71 #if defined(OS_WIN)
72 const int kExpectedStillRunningExitCode = 0x102;
73 const int kExpectedKilledExitCode = 1;
74 #else
75 const int kExpectedStillRunningExitCode = 0;
76 #endif
78 // Sleeps until file filename is created.
79 void WaitToDie(const char* filename) {
80 FILE* fp;
81 do {
82 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(10));
83 fp = fopen(filename, "r");
84 } while (!fp);
85 fclose(fp);
88 // Signals children they should die now.
89 void SignalChildren(const char* filename) {
90 FILE* fp = fopen(filename, "w");
91 fclose(fp);
94 // Using a pipe to the child to wait for an event was considered, but
95 // there were cases in the past where pipes caused problems (other
96 // libraries closing the fds, child deadlocking). This is a simple
97 // case, so it's not worth the risk. Using wait loops is discouraged
98 // in most instances.
99 base::TerminationStatus WaitForChildTermination(base::ProcessHandle handle,
100 int* exit_code) {
101 // Now we wait until the result is something other than STILL_RUNNING.
102 base::TerminationStatus status = base::TERMINATION_STATUS_STILL_RUNNING;
103 const base::TimeDelta kInterval = base::TimeDelta::FromMilliseconds(20);
104 base::TimeDelta waited;
105 do {
106 status = base::GetTerminationStatus(handle, exit_code);
107 base::PlatformThread::Sleep(kInterval);
108 waited += kInterval;
109 } while (status == base::TERMINATION_STATUS_STILL_RUNNING &&
110 waited < TestTimeouts::action_max_timeout());
112 return status;
115 } // namespace
117 class ProcessUtilTest : public base::MultiProcessTest {
118 public:
119 #if defined(OS_POSIX)
120 // Spawn a child process that counts how many file descriptors are open.
121 int CountOpenFDsInChild();
122 #endif
123 // Converts the filename to a platform specific filepath.
124 // On Android files can not be created in arbitrary directories.
125 static std::string GetSignalFilePath(const char* filename);
128 std::string ProcessUtilTest::GetSignalFilePath(const char* filename) {
129 #if !defined(OS_ANDROID)
130 return filename;
131 #else
132 FilePath tmp_dir;
133 PathService::Get(base::DIR_CACHE, &tmp_dir);
134 tmp_dir = tmp_dir.Append(filename);
135 return tmp_dir.value();
136 #endif
139 MULTIPROCESS_TEST_MAIN(SimpleChildProcess) {
140 return 0;
143 // TODO(viettrungluu): This should be in a "MultiProcessTestTest".
144 TEST_F(ProcessUtilTest, SpawnChild) {
145 base::ProcessHandle handle = SpawnChild("SimpleChildProcess");
146 ASSERT_NE(base::kNullProcessHandle, handle);
147 EXPECT_TRUE(base::WaitForSingleProcess(
148 handle, TestTimeouts::action_max_timeout()));
149 base::CloseProcessHandle(handle);
152 MULTIPROCESS_TEST_MAIN(SlowChildProcess) {
153 WaitToDie(ProcessUtilTest::GetSignalFilePath(kSignalFileSlow).c_str());
154 return 0;
157 TEST_F(ProcessUtilTest, KillSlowChild) {
158 const std::string signal_file =
159 ProcessUtilTest::GetSignalFilePath(kSignalFileSlow);
160 remove(signal_file.c_str());
161 base::ProcessHandle handle = SpawnChild("SlowChildProcess");
162 ASSERT_NE(base::kNullProcessHandle, handle);
163 SignalChildren(signal_file.c_str());
164 EXPECT_TRUE(base::WaitForSingleProcess(
165 handle, TestTimeouts::action_max_timeout()));
166 base::CloseProcessHandle(handle);
167 remove(signal_file.c_str());
170 // Times out on Linux and Win, flakes on other platforms, http://crbug.com/95058
171 TEST_F(ProcessUtilTest, DISABLED_GetTerminationStatusExit) {
172 const std::string signal_file =
173 ProcessUtilTest::GetSignalFilePath(kSignalFileSlow);
174 remove(signal_file.c_str());
175 base::ProcessHandle handle = SpawnChild("SlowChildProcess");
176 ASSERT_NE(base::kNullProcessHandle, handle);
178 int exit_code = 42;
179 EXPECT_EQ(base::TERMINATION_STATUS_STILL_RUNNING,
180 base::GetTerminationStatus(handle, &exit_code));
181 EXPECT_EQ(kExpectedStillRunningExitCode, exit_code);
183 SignalChildren(signal_file.c_str());
184 exit_code = 42;
185 base::TerminationStatus status =
186 WaitForChildTermination(handle, &exit_code);
187 EXPECT_EQ(base::TERMINATION_STATUS_NORMAL_TERMINATION, status);
188 EXPECT_EQ(0, exit_code);
189 base::CloseProcessHandle(handle);
190 remove(signal_file.c_str());
193 #if defined(OS_WIN)
194 // TODO(cpu): figure out how to test this in other platforms.
195 TEST_F(ProcessUtilTest, GetProcId) {
196 base::ProcessId id1 = base::GetProcId(GetCurrentProcess());
197 EXPECT_NE(0ul, id1);
198 base::ProcessHandle handle = SpawnChild("SimpleChildProcess");
199 ASSERT_NE(base::kNullProcessHandle, handle);
200 base::ProcessId id2 = base::GetProcId(handle);
201 EXPECT_NE(0ul, id2);
202 EXPECT_NE(id1, id2);
203 base::CloseProcessHandle(handle);
205 #endif
207 #if !defined(OS_MACOSX)
208 // This test is disabled on Mac, since it's flaky due to ReportCrash
209 // taking a variable amount of time to parse and load the debug and
210 // symbol data for this unit test's executable before firing the
211 // signal handler.
213 // TODO(gspencer): turn this test process into a very small program
214 // with no symbols (instead of using the multiprocess testing
215 // framework) to reduce the ReportCrash overhead.
216 const char kSignalFileCrash[] = "CrashingChildProcess.die";
218 MULTIPROCESS_TEST_MAIN(CrashingChildProcess) {
219 WaitToDie(ProcessUtilTest::GetSignalFilePath(kSignalFileCrash).c_str());
220 #if defined(OS_POSIX)
221 // Have to disable to signal handler for segv so we can get a crash
222 // instead of an abnormal termination through the crash dump handler.
223 ::signal(SIGSEGV, SIG_DFL);
224 #endif
225 // Make this process have a segmentation fault.
226 volatile int* oops = NULL;
227 *oops = 0xDEAD;
228 return 1;
231 // This test intentionally crashes, so we don't need to run it under
232 // AddressSanitizer.
233 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
234 #define MAYBE_GetTerminationStatusCrash DISABLED_GetTerminationStatusCrash
235 #else
236 #define MAYBE_GetTerminationStatusCrash GetTerminationStatusCrash
237 #endif
238 TEST_F(ProcessUtilTest, MAYBE_GetTerminationStatusCrash) {
239 const std::string signal_file =
240 ProcessUtilTest::GetSignalFilePath(kSignalFileCrash);
241 remove(signal_file.c_str());
242 base::ProcessHandle handle = SpawnChild("CrashingChildProcess");
243 ASSERT_NE(base::kNullProcessHandle, handle);
245 int exit_code = 42;
246 EXPECT_EQ(base::TERMINATION_STATUS_STILL_RUNNING,
247 base::GetTerminationStatus(handle, &exit_code));
248 EXPECT_EQ(kExpectedStillRunningExitCode, exit_code);
250 SignalChildren(signal_file.c_str());
251 exit_code = 42;
252 base::TerminationStatus status =
253 WaitForChildTermination(handle, &exit_code);
254 EXPECT_EQ(base::TERMINATION_STATUS_PROCESS_CRASHED, status);
256 #if defined(OS_WIN)
257 EXPECT_EQ(0xc0000005, exit_code);
258 #elif defined(OS_POSIX)
259 int signaled = WIFSIGNALED(exit_code);
260 EXPECT_NE(0, signaled);
261 int signal = WTERMSIG(exit_code);
262 EXPECT_EQ(SIGSEGV, signal);
263 #endif
264 base::CloseProcessHandle(handle);
266 // Reset signal handlers back to "normal".
267 base::debug::EnableInProcessStackDumping();
268 remove(signal_file.c_str());
270 #endif // !defined(OS_MACOSX)
272 MULTIPROCESS_TEST_MAIN(KilledChildProcess) {
273 WaitToDie(ProcessUtilTest::GetSignalFilePath(kSignalFileKill).c_str());
274 #if defined(OS_WIN)
275 // Kill ourselves.
276 HANDLE handle = ::OpenProcess(PROCESS_ALL_ACCESS, 0, ::GetCurrentProcessId());
277 ::TerminateProcess(handle, kExpectedKilledExitCode);
278 #elif defined(OS_POSIX)
279 // Send a SIGKILL to this process, just like the OOM killer would.
280 ::kill(getpid(), SIGKILL);
281 #endif
282 return 1;
285 TEST_F(ProcessUtilTest, GetTerminationStatusKill) {
286 const std::string signal_file =
287 ProcessUtilTest::GetSignalFilePath(kSignalFileKill);
288 remove(signal_file.c_str());
289 base::ProcessHandle handle = SpawnChild("KilledChildProcess");
290 ASSERT_NE(base::kNullProcessHandle, handle);
292 int exit_code = 42;
293 EXPECT_EQ(base::TERMINATION_STATUS_STILL_RUNNING,
294 base::GetTerminationStatus(handle, &exit_code));
295 EXPECT_EQ(kExpectedStillRunningExitCode, exit_code);
297 SignalChildren(signal_file.c_str());
298 exit_code = 42;
299 base::TerminationStatus status =
300 WaitForChildTermination(handle, &exit_code);
301 EXPECT_EQ(base::TERMINATION_STATUS_PROCESS_WAS_KILLED, status);
302 #if defined(OS_WIN)
303 EXPECT_EQ(kExpectedKilledExitCode, exit_code);
304 #elif defined(OS_POSIX)
305 int signaled = WIFSIGNALED(exit_code);
306 EXPECT_NE(0, signaled);
307 int signal = WTERMSIG(exit_code);
308 EXPECT_EQ(SIGKILL, signal);
309 #endif
310 base::CloseProcessHandle(handle);
311 remove(signal_file.c_str());
314 #if defined(OS_WIN)
315 // TODO(estade): if possible, port this test.
316 TEST_F(ProcessUtilTest, GetAppOutput) {
317 // Let's create a decently long message.
318 std::string message;
319 for (int i = 0; i < 1025; i++) { // 1025 so it does not end on a kilo-byte
320 // boundary.
321 message += "Hello!";
323 // cmd.exe's echo always adds a \r\n to its output.
324 std::string expected(message);
325 expected += "\r\n";
327 FilePath cmd(L"cmd.exe");
328 CommandLine cmd_line(cmd);
329 cmd_line.AppendArg("/c");
330 cmd_line.AppendArg("echo " + message + "");
331 std::string output;
332 ASSERT_TRUE(base::GetAppOutput(cmd_line, &output));
333 EXPECT_EQ(expected, output);
335 // Let's make sure stderr is ignored.
336 CommandLine other_cmd_line(cmd);
337 other_cmd_line.AppendArg("/c");
338 // http://msdn.microsoft.com/library/cc772622.aspx
339 cmd_line.AppendArg("echo " + message + " >&2");
340 output.clear();
341 ASSERT_TRUE(base::GetAppOutput(other_cmd_line, &output));
342 EXPECT_EQ("", output);
345 // TODO(estade): if possible, port this test.
346 TEST_F(ProcessUtilTest, LaunchAsUser) {
347 base::UserTokenHandle token;
348 ASSERT_TRUE(OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &token));
349 base::LaunchOptions options;
350 options.as_user = token;
351 EXPECT_TRUE(base::LaunchProcess(MakeCmdLine("SimpleChildProcess"), options,
352 NULL));
355 static const char kEventToTriggerHandleSwitch[] = "event-to-trigger-handle";
357 MULTIPROCESS_TEST_MAIN(TriggerEventChildProcess) {
358 std::string handle_value_string =
359 CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
360 kEventToTriggerHandleSwitch);
361 CHECK(!handle_value_string.empty());
363 uint64 handle_value_uint64;
364 CHECK(base::StringToUint64(handle_value_string, &handle_value_uint64));
365 // Give ownership of the handle to |event|.
366 base::WaitableEvent event(reinterpret_cast<HANDLE>(handle_value_uint64));
368 event.Signal();
370 return 0;
373 TEST_F(ProcessUtilTest, InheritSpecifiedHandles) {
374 // Manually create the event, so that it can be inheritable.
375 SECURITY_ATTRIBUTES security_attributes = {};
376 security_attributes.nLength = static_cast<DWORD>(sizeof(security_attributes));
377 security_attributes.lpSecurityDescriptor = NULL;
378 security_attributes.bInheritHandle = true;
380 // Takes ownership of the event handle.
381 base::WaitableEvent event(
382 CreateEvent(&security_attributes, true, false, NULL));
383 base::HandlesToInheritVector handles_to_inherit;
384 handles_to_inherit.push_back(event.handle());
385 base::LaunchOptions options;
386 options.handles_to_inherit = &handles_to_inherit;
388 CommandLine cmd_line = MakeCmdLine("TriggerEventChildProcess");
389 cmd_line.AppendSwitchASCII(kEventToTriggerHandleSwitch,
390 base::Uint64ToString(reinterpret_cast<uint64>(event.handle())));
392 // This functionality actually requires Vista or later. Make sure that it
393 // fails properly on XP.
394 if (base::win::GetVersion() < base::win::VERSION_VISTA) {
395 EXPECT_FALSE(base::LaunchProcess(cmd_line, options, NULL));
396 return;
399 // Launch the process and wait for it to trigger the event.
400 ASSERT_TRUE(base::LaunchProcess(cmd_line, options, NULL));
401 EXPECT_TRUE(event.TimedWait(TestTimeouts::action_max_timeout()));
403 #endif // defined(OS_WIN)
405 #if defined(OS_POSIX)
407 namespace {
409 // Returns the maximum number of files that a process can have open.
410 // Returns 0 on error.
411 int GetMaxFilesOpenInProcess() {
412 struct rlimit rlim;
413 if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
414 return 0;
417 // rlim_t is a uint64 - clip to maxint. We do this since FD #s are ints
418 // which are all 32 bits on the supported platforms.
419 rlim_t max_int = static_cast<rlim_t>(std::numeric_limits<int32>::max());
420 if (rlim.rlim_cur > max_int) {
421 return max_int;
424 return rlim.rlim_cur;
427 const int kChildPipe = 20; // FD # for write end of pipe in child process.
429 #if defined(OS_MACOSX)
431 // <http://opensource.apple.com/source/xnu/xnu-2422.1.72/bsd/sys/guarded.h>
432 #if !defined(_GUARDID_T)
433 #define _GUARDID_T
434 typedef __uint64_t guardid_t;
435 #endif // _GUARDID_T
437 // From .../MacOSX10.9.sdk/usr/include/sys/syscall.h
438 #if !defined(SYS_change_fdguard_np)
439 #define SYS_change_fdguard_np 444
440 #endif
442 // <http://opensource.apple.com/source/xnu/xnu-2422.1.72/bsd/sys/guarded.h>
443 #if !defined(GUARD_DUP)
444 #define GUARD_DUP (1u << 1)
445 #endif
447 // <http://opensource.apple.com/source/xnu/xnu-2422.1.72/bsd/kern/kern_guarded.c?txt>
449 // Atomically replaces |guard|/|guardflags| with |nguard|/|nguardflags| on |fd|.
450 int change_fdguard_np(int fd,
451 const guardid_t *guard, u_int guardflags,
452 const guardid_t *nguard, u_int nguardflags,
453 int *fdflagsp) {
454 return syscall(SYS_change_fdguard_np, fd, guard, guardflags,
455 nguard, nguardflags, fdflagsp);
458 // Attempt to set a file-descriptor guard on |fd|. In case of success, remove
459 // it and return |true| to indicate that it can be guarded. Returning |false|
460 // means either that |fd| is guarded by some other code, or more likely EBADF.
462 // Starting with 10.9, libdispatch began setting GUARD_DUP on a file descriptor.
463 // Unfortunately, it is spun up as part of +[NSApplication initialize], which is
464 // not really something that Chromium can avoid using on OSX. See
465 // <http://crbug.com/338157>. This function allows querying whether the file
466 // descriptor is guarded before attempting to close it.
467 bool CanGuardFd(int fd) {
468 // The syscall is first provided in 10.9/Mavericks.
469 if (!base::mac::IsOSMavericksOrLater())
470 return true;
472 // Saves the original flags to reset later.
473 int original_fdflags = 0;
475 // This can be any value at all, it just has to match up between the two
476 // calls.
477 const guardid_t kGuard = 15;
479 // Attempt to change the guard. This can fail with EBADF if the file
480 // descriptor is bad, or EINVAL if the fd already has a guard set.
481 int ret =
482 change_fdguard_np(fd, NULL, 0, &kGuard, GUARD_DUP, &original_fdflags);
483 if (ret == -1)
484 return false;
486 // Remove the guard. It should not be possible to fail in removing the guard
487 // just added.
488 ret = change_fdguard_np(fd, &kGuard, GUARD_DUP, NULL, 0, &original_fdflags);
489 DPCHECK(ret == 0);
491 return true;
493 #endif // OS_MACOSX
495 } // namespace
497 MULTIPROCESS_TEST_MAIN(ProcessUtilsLeakFDChildProcess) {
498 // This child process counts the number of open FDs, it then writes that
499 // number out to a pipe connected to the parent.
500 int num_open_files = 0;
501 int write_pipe = kChildPipe;
502 int max_files = GetMaxFilesOpenInProcess();
503 for (int i = STDERR_FILENO + 1; i < max_files; i++) {
504 #if defined(OS_MACOSX)
505 // Ignore guarded or invalid file descriptors.
506 if (!CanGuardFd(i))
507 continue;
508 #endif
510 if (i != kChildPipe) {
511 int fd;
512 if ((fd = HANDLE_EINTR(dup(i))) != -1) {
513 close(fd);
514 num_open_files += 1;
519 int written = HANDLE_EINTR(write(write_pipe, &num_open_files,
520 sizeof(num_open_files)));
521 DCHECK_EQ(static_cast<size_t>(written), sizeof(num_open_files));
522 int ret = IGNORE_EINTR(close(write_pipe));
523 DPCHECK(ret == 0);
525 return 0;
528 int ProcessUtilTest::CountOpenFDsInChild() {
529 int fds[2];
530 if (pipe(fds) < 0)
531 NOTREACHED();
533 base::FileHandleMappingVector fd_mapping_vec;
534 fd_mapping_vec.push_back(std::pair<int, int>(fds[1], kChildPipe));
535 base::LaunchOptions options;
536 options.fds_to_remap = &fd_mapping_vec;
537 base::ProcessHandle handle =
538 SpawnChildWithOptions("ProcessUtilsLeakFDChildProcess", options);
539 CHECK(handle);
540 int ret = IGNORE_EINTR(close(fds[1]));
541 DPCHECK(ret == 0);
543 // Read number of open files in client process from pipe;
544 int num_open_files = -1;
545 ssize_t bytes_read =
546 HANDLE_EINTR(read(fds[0], &num_open_files, sizeof(num_open_files)));
547 CHECK_EQ(bytes_read, static_cast<ssize_t>(sizeof(num_open_files)));
549 #if defined(THREAD_SANITIZER)
550 // Compiler-based ThreadSanitizer makes this test slow.
551 CHECK(base::WaitForSingleProcess(handle, base::TimeDelta::FromSeconds(3)));
552 #else
553 CHECK(base::WaitForSingleProcess(handle, base::TimeDelta::FromSeconds(1)));
554 #endif
555 base::CloseProcessHandle(handle);
556 ret = IGNORE_EINTR(close(fds[0]));
557 DPCHECK(ret == 0);
559 return num_open_files;
562 #if defined(ADDRESS_SANITIZER) || defined(THREAD_SANITIZER)
563 // ProcessUtilTest.FDRemapping is flaky when ran under xvfb-run on Precise.
564 // The problem is 100% reproducible with both ASan and TSan.
565 // See http://crbug.com/136720.
566 #define MAYBE_FDRemapping DISABLED_FDRemapping
567 #else
568 #define MAYBE_FDRemapping FDRemapping
569 #endif
570 TEST_F(ProcessUtilTest, MAYBE_FDRemapping) {
571 int fds_before = CountOpenFDsInChild();
573 // open some dummy fds to make sure they don't propagate over to the
574 // child process.
575 int dev_null = open("/dev/null", O_RDONLY);
576 int sockets[2];
577 socketpair(AF_UNIX, SOCK_STREAM, 0, sockets);
579 int fds_after = CountOpenFDsInChild();
581 ASSERT_EQ(fds_after, fds_before);
583 int ret;
584 ret = IGNORE_EINTR(close(sockets[0]));
585 DPCHECK(ret == 0);
586 ret = IGNORE_EINTR(close(sockets[1]));
587 DPCHECK(ret == 0);
588 ret = IGNORE_EINTR(close(dev_null));
589 DPCHECK(ret == 0);
592 namespace {
594 std::string TestLaunchProcess(const std::vector<std::string>& args,
595 const base::EnvironmentMap& env_changes,
596 const bool clear_environ,
597 const int clone_flags) {
598 base::FileHandleMappingVector fds_to_remap;
600 int fds[2];
601 PCHECK(pipe(fds) == 0);
603 fds_to_remap.push_back(std::make_pair(fds[1], 1));
604 base::LaunchOptions options;
605 options.wait = true;
606 options.environ = env_changes;
607 options.clear_environ = clear_environ;
608 options.fds_to_remap = &fds_to_remap;
609 #if defined(OS_LINUX)
610 options.clone_flags = clone_flags;
611 #else
612 CHECK_EQ(0, clone_flags);
613 #endif // OS_LINUX
614 EXPECT_TRUE(base::LaunchProcess(args, options, NULL));
615 PCHECK(IGNORE_EINTR(close(fds[1])) == 0);
617 char buf[512];
618 const ssize_t n = HANDLE_EINTR(read(fds[0], buf, sizeof(buf)));
620 PCHECK(IGNORE_EINTR(close(fds[0])) == 0);
622 return std::string(buf, n);
625 const char kLargeString[] =
626 "0123456789012345678901234567890123456789012345678901234567890123456789"
627 "0123456789012345678901234567890123456789012345678901234567890123456789"
628 "0123456789012345678901234567890123456789012345678901234567890123456789"
629 "0123456789012345678901234567890123456789012345678901234567890123456789"
630 "0123456789012345678901234567890123456789012345678901234567890123456789"
631 "0123456789012345678901234567890123456789012345678901234567890123456789"
632 "0123456789012345678901234567890123456789012345678901234567890123456789";
634 } // namespace
636 TEST_F(ProcessUtilTest, LaunchProcess) {
637 base::EnvironmentMap env_changes;
638 std::vector<std::string> echo_base_test;
639 echo_base_test.push_back(kPosixShell);
640 echo_base_test.push_back("-c");
641 echo_base_test.push_back("echo $BASE_TEST");
643 std::vector<std::string> print_env;
644 print_env.push_back("/usr/bin/env");
645 const int no_clone_flags = 0;
646 const bool no_clear_environ = false;
648 const char kBaseTest[] = "BASE_TEST";
650 env_changes[kBaseTest] = "bar";
651 EXPECT_EQ("bar\n",
652 TestLaunchProcess(
653 echo_base_test, env_changes, no_clear_environ, no_clone_flags));
654 env_changes.clear();
656 EXPECT_EQ(0, setenv(kBaseTest, "testing", 1 /* override */));
657 EXPECT_EQ("testing\n",
658 TestLaunchProcess(
659 echo_base_test, env_changes, no_clear_environ, no_clone_flags));
661 env_changes[kBaseTest] = std::string();
662 EXPECT_EQ("\n",
663 TestLaunchProcess(
664 echo_base_test, env_changes, no_clear_environ, no_clone_flags));
666 env_changes[kBaseTest] = "foo";
667 EXPECT_EQ("foo\n",
668 TestLaunchProcess(
669 echo_base_test, env_changes, no_clear_environ, no_clone_flags));
671 env_changes.clear();
672 EXPECT_EQ(0, setenv(kBaseTest, kLargeString, 1 /* override */));
673 EXPECT_EQ(std::string(kLargeString) + "\n",
674 TestLaunchProcess(
675 echo_base_test, env_changes, no_clear_environ, no_clone_flags));
677 env_changes[kBaseTest] = "wibble";
678 EXPECT_EQ("wibble\n",
679 TestLaunchProcess(
680 echo_base_test, env_changes, no_clear_environ, no_clone_flags));
682 #if defined(OS_LINUX)
683 // Test a non-trival value for clone_flags.
684 // Don't test on Valgrind as it has limited support for clone().
685 if (!RunningOnValgrind()) {
686 EXPECT_EQ(
687 "wibble\n",
688 TestLaunchProcess(
689 echo_base_test, env_changes, no_clear_environ, CLONE_FS | SIGCHLD));
692 EXPECT_EQ(
693 "BASE_TEST=wibble\n",
694 TestLaunchProcess(
695 print_env, env_changes, true /* clear_environ */, no_clone_flags));
696 env_changes.clear();
697 EXPECT_EQ(
699 TestLaunchProcess(
700 print_env, env_changes, true /* clear_environ */, no_clone_flags));
701 #endif
704 TEST_F(ProcessUtilTest, GetAppOutput) {
705 std::string output;
707 #if defined(OS_ANDROID)
708 std::vector<std::string> argv;
709 argv.push_back("sh"); // Instead of /bin/sh, force path search to find it.
710 argv.push_back("-c");
712 argv.push_back("exit 0");
713 EXPECT_TRUE(base::GetAppOutput(CommandLine(argv), &output));
714 EXPECT_STREQ("", output.c_str());
716 argv[2] = "exit 1";
717 EXPECT_FALSE(base::GetAppOutput(CommandLine(argv), &output));
718 EXPECT_STREQ("", output.c_str());
720 argv[2] = "echo foobar42";
721 EXPECT_TRUE(base::GetAppOutput(CommandLine(argv), &output));
722 EXPECT_STREQ("foobar42\n", output.c_str());
723 #else
724 EXPECT_TRUE(base::GetAppOutput(CommandLine(FilePath("true")), &output));
725 EXPECT_STREQ("", output.c_str());
727 EXPECT_FALSE(base::GetAppOutput(CommandLine(FilePath("false")), &output));
729 std::vector<std::string> argv;
730 argv.push_back("/bin/echo");
731 argv.push_back("-n");
732 argv.push_back("foobar42");
733 EXPECT_TRUE(base::GetAppOutput(CommandLine(argv), &output));
734 EXPECT_STREQ("foobar42", output.c_str());
735 #endif // defined(OS_ANDROID)
738 // Flakes on Android, crbug.com/375840
739 #if defined(OS_ANDROID)
740 #define MAYBE_GetAppOutputRestricted DISABLED_GetAppOutputRestricted
741 #else
742 #define MAYBE_GetAppOutputRestricted GetAppOutputRestricted
743 #endif
744 TEST_F(ProcessUtilTest, MAYBE_GetAppOutputRestricted) {
745 // Unfortunately, since we can't rely on the path, we need to know where
746 // everything is. So let's use /bin/sh, which is on every POSIX system, and
747 // its built-ins.
748 std::vector<std::string> argv;
749 argv.push_back(std::string(kShellPath)); // argv[0]
750 argv.push_back("-c"); // argv[1]
752 // On success, should set |output|. We use |/bin/sh -c 'exit 0'| instead of
753 // |true| since the location of the latter may be |/bin| or |/usr/bin| (and we
754 // need absolute paths).
755 argv.push_back("exit 0"); // argv[2]; equivalent to "true"
756 std::string output = "abc";
757 EXPECT_TRUE(base::GetAppOutputRestricted(CommandLine(argv), &output, 100));
758 EXPECT_STREQ("", output.c_str());
760 argv[2] = "exit 1"; // equivalent to "false"
761 output = "before";
762 EXPECT_FALSE(base::GetAppOutputRestricted(CommandLine(argv),
763 &output, 100));
764 EXPECT_STREQ("", output.c_str());
766 // Amount of output exactly equal to space allowed.
767 argv[2] = "echo 123456789"; // (the sh built-in doesn't take "-n")
768 output.clear();
769 EXPECT_TRUE(base::GetAppOutputRestricted(CommandLine(argv), &output, 10));
770 EXPECT_STREQ("123456789\n", output.c_str());
772 // Amount of output greater than space allowed.
773 output.clear();
774 EXPECT_TRUE(base::GetAppOutputRestricted(CommandLine(argv), &output, 5));
775 EXPECT_STREQ("12345", output.c_str());
777 // Amount of output less than space allowed.
778 output.clear();
779 EXPECT_TRUE(base::GetAppOutputRestricted(CommandLine(argv), &output, 15));
780 EXPECT_STREQ("123456789\n", output.c_str());
782 // Zero space allowed.
783 output = "abc";
784 EXPECT_TRUE(base::GetAppOutputRestricted(CommandLine(argv), &output, 0));
785 EXPECT_STREQ("", output.c_str());
788 #if !defined(OS_MACOSX) && !defined(OS_OPENBSD)
789 // TODO(benwells): GetAppOutputRestricted should terminate applications
790 // with SIGPIPE when we have enough output. http://crbug.com/88502
791 TEST_F(ProcessUtilTest, GetAppOutputRestrictedSIGPIPE) {
792 std::vector<std::string> argv;
793 std::string output;
795 argv.push_back(std::string(kShellPath)); // argv[0]
796 argv.push_back("-c");
797 #if defined(OS_ANDROID)
798 argv.push_back("while echo 12345678901234567890; do :; done");
799 EXPECT_TRUE(base::GetAppOutputRestricted(CommandLine(argv), &output, 10));
800 EXPECT_STREQ("1234567890", output.c_str());
801 #else
802 argv.push_back("yes");
803 EXPECT_TRUE(base::GetAppOutputRestricted(CommandLine(argv), &output, 10));
804 EXPECT_STREQ("y\ny\ny\ny\ny\n", output.c_str());
805 #endif
807 #endif
809 #if defined(ADDRESS_SANITIZER) && defined(OS_MACOSX) && \
810 defined(ARCH_CPU_64_BITS)
811 // Times out under AddressSanitizer on 64-bit OS X, see
812 // http://crbug.com/298197.
813 #define MAYBE_GetAppOutputRestrictedNoZombies \
814 DISABLED_GetAppOutputRestrictedNoZombies
815 #else
816 #define MAYBE_GetAppOutputRestrictedNoZombies GetAppOutputRestrictedNoZombies
817 #endif
818 TEST_F(ProcessUtilTest, MAYBE_GetAppOutputRestrictedNoZombies) {
819 std::vector<std::string> argv;
821 argv.push_back(std::string(kShellPath)); // argv[0]
822 argv.push_back("-c"); // argv[1]
823 argv.push_back("echo 123456789012345678901234567890"); // argv[2]
825 // Run |GetAppOutputRestricted()| 300 (> default per-user processes on Mac OS
826 // 10.5) times with an output buffer big enough to capture all output.
827 for (int i = 0; i < 300; i++) {
828 std::string output;
829 EXPECT_TRUE(base::GetAppOutputRestricted(CommandLine(argv), &output, 100));
830 EXPECT_STREQ("123456789012345678901234567890\n", output.c_str());
833 // Ditto, but with an output buffer too small to capture all output.
834 for (int i = 0; i < 300; i++) {
835 std::string output;
836 EXPECT_TRUE(base::GetAppOutputRestricted(CommandLine(argv), &output, 10));
837 EXPECT_STREQ("1234567890", output.c_str());
841 TEST_F(ProcessUtilTest, GetAppOutputWithExitCode) {
842 // Test getting output from a successful application.
843 std::vector<std::string> argv;
844 std::string output;
845 int exit_code;
846 argv.push_back(std::string(kShellPath)); // argv[0]
847 argv.push_back("-c"); // argv[1]
848 argv.push_back("echo foo"); // argv[2];
849 EXPECT_TRUE(base::GetAppOutputWithExitCode(CommandLine(argv), &output,
850 &exit_code));
851 EXPECT_STREQ("foo\n", output.c_str());
852 EXPECT_EQ(exit_code, 0);
854 // Test getting output from an application which fails with a specific exit
855 // code.
856 output.clear();
857 argv[2] = "echo foo; exit 2";
858 EXPECT_TRUE(base::GetAppOutputWithExitCode(CommandLine(argv), &output,
859 &exit_code));
860 EXPECT_STREQ("foo\n", output.c_str());
861 EXPECT_EQ(exit_code, 2);
864 TEST_F(ProcessUtilTest, GetParentProcessId) {
865 base::ProcessId ppid = base::GetParentProcessId(base::GetCurrentProcId());
866 EXPECT_EQ(ppid, getppid());
869 // TODO(port): port those unit tests.
870 bool IsProcessDead(base::ProcessHandle child) {
871 // waitpid() will actually reap the process which is exactly NOT what we
872 // want to test for. The good thing is that if it can't find the process
873 // we'll get a nice value for errno which we can test for.
874 const pid_t result = HANDLE_EINTR(waitpid(child, NULL, WNOHANG));
875 return result == -1 && errno == ECHILD;
878 TEST_F(ProcessUtilTest, DelayedTermination) {
879 base::ProcessHandle child_process = SpawnChild("process_util_test_never_die");
880 ASSERT_TRUE(child_process);
881 base::EnsureProcessTerminated(child_process);
882 base::WaitForSingleProcess(child_process, base::TimeDelta::FromSeconds(5));
884 // Check that process was really killed.
885 EXPECT_TRUE(IsProcessDead(child_process));
886 base::CloseProcessHandle(child_process);
889 MULTIPROCESS_TEST_MAIN(process_util_test_never_die) {
890 while (1) {
891 sleep(500);
893 return 0;
896 TEST_F(ProcessUtilTest, ImmediateTermination) {
897 base::ProcessHandle child_process =
898 SpawnChild("process_util_test_die_immediately");
899 ASSERT_TRUE(child_process);
900 // Give it time to die.
901 sleep(2);
902 base::EnsureProcessTerminated(child_process);
904 // Check that process was really killed.
905 EXPECT_TRUE(IsProcessDead(child_process));
906 base::CloseProcessHandle(child_process);
909 MULTIPROCESS_TEST_MAIN(process_util_test_die_immediately) {
910 return 0;
913 #endif // defined(OS_POSIX)