Plugin Power Saver: Record PPS UMAs only for users with PPS enabled.
[chromium-blink-merge.git] / base / process / process_util_unittest.cc
blob11d8874a52ab9576cd9ec5b1f2d08c9808655ac5
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/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"
36 #if defined(OS_LINUX)
37 #include <malloc.h>
38 #include <sched.h>
39 #include <sys/syscall.h>
40 #endif
41 #if defined(OS_POSIX)
42 #include <dlfcn.h>
43 #include <errno.h>
44 #include <fcntl.h>
45 #include <sched.h>
46 #include <signal.h>
47 #include <sys/resource.h>
48 #include <sys/socket.h>
49 #include <sys/types.h>
50 #include <sys/wait.h>
51 #include <unistd.h>
52 #endif
53 #if defined(OS_WIN)
54 #include <windows.h>
55 #include "base/win/windows_version.h"
56 #endif
57 #if defined(OS_MACOSX)
58 #include <mach/vm_param.h>
59 #include <malloc/malloc.h>
60 #include "base/mac/mac_util.h"
61 #endif
63 using base::FilePath;
65 namespace {
67 #if defined(OS_ANDROID)
68 const char kShellPath[] = "/system/bin/sh";
69 const char kPosixShell[] = "sh";
70 #else
71 const char kShellPath[] = "/bin/sh";
72 const char kPosixShell[] = "bash";
73 #endif
75 const char kSignalFileSlow[] = "SlowChildProcess.die";
76 const char kSignalFileKill[] = "KilledChildProcess.die";
78 #if defined(OS_WIN)
79 const int kExpectedStillRunningExitCode = 0x102;
80 const int kExpectedKilledExitCode = 1;
81 #else
82 const int kExpectedStillRunningExitCode = 0;
83 #endif
85 // Sleeps until file filename is created.
86 void WaitToDie(const char* filename) {
87 FILE* fp;
88 do {
89 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(10));
90 fp = fopen(filename, "r");
91 } while (!fp);
92 fclose(fp);
95 // Signals children they should die now.
96 void SignalChildren(const char* filename) {
97 FILE* fp = fopen(filename, "w");
98 fclose(fp);
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,
107 int* exit_code) {
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;
112 do {
113 status = base::GetTerminationStatus(handle, exit_code);
114 base::PlatformThread::Sleep(kInterval);
115 waited += kInterval;
116 } while (status == base::TERMINATION_STATUS_STILL_RUNNING &&
117 waited < TestTimeouts::action_max_timeout());
119 return status;
122 } // namespace
124 class ProcessUtilTest : public base::MultiProcessTest {
125 public:
126 #if defined(OS_POSIX)
127 // Spawn a child process that counts how many file descriptors are open.
128 int CountOpenFDsInChild();
129 #endif
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)
137 return filename;
138 #else
139 FilePath tmp_dir;
140 PathService::Get(base::DIR_CACHE, &tmp_dir);
141 tmp_dir = tmp_dir.Append(filename);
142 return tmp_dir.value();
143 #endif
146 MULTIPROCESS_TEST_MAIN(SimpleChildProcess) {
147 return 0;
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 int exit_code;
155 EXPECT_TRUE(process.WaitForExitWithTimeout(
156 TestTimeouts::action_max_timeout(), &exit_code));
159 MULTIPROCESS_TEST_MAIN(SlowChildProcess) {
160 WaitToDie(ProcessUtilTest::GetSignalFilePath(kSignalFileSlow).c_str());
161 return 0;
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());
171 int exit_code;
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());
185 int exit_code = 42;
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());
191 exit_code = 42;
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());
199 #if defined(OS_WIN)
200 // TODO(cpu): figure out how to test this in other platforms.
201 TEST_F(ProcessUtilTest, GetProcId) {
202 base::ProcessId id1 = base::GetProcId(GetCurrentProcess());
203 EXPECT_NE(0ul, id1);
204 base::Process process = SpawnChild("SimpleChildProcess");
205 ASSERT_TRUE(process.IsValid());
206 base::ProcessId id2 = process.Pid();
207 EXPECT_NE(0ul, id2);
208 EXPECT_NE(id1, id2);
210 #endif
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
216 // signal handler.
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);
229 #endif
230 // Make this process have a segmentation fault.
231 volatile int* oops = NULL;
232 *oops = 0xDEAD;
233 return 1;
236 // This test intentionally crashes, so we don't need to run it under
237 // AddressSanitizer.
238 #if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
239 #define MAYBE_GetTerminationStatusCrash DISABLED_GetTerminationStatusCrash
240 #else
241 #define MAYBE_GetTerminationStatusCrash GetTerminationStatusCrash
242 #endif
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());
250 int exit_code = 42;
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());
256 exit_code = 42;
257 base::TerminationStatus status =
258 WaitForChildTermination(process.Handle(), &exit_code);
259 EXPECT_EQ(base::TERMINATION_STATUS_PROCESS_CRASHED, status);
261 #if defined(OS_WIN)
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);
268 #endif
270 // Reset signal handlers back to "normal".
271 base::debug::EnableInProcessStackDumping();
272 remove(signal_file.c_str());
274 #endif // !defined(OS_MACOSX)
276 MULTIPROCESS_TEST_MAIN(KilledChildProcess) {
277 WaitToDie(ProcessUtilTest::GetSignalFilePath(kSignalFileKill).c_str());
278 #if defined(OS_WIN)
279 // Kill ourselves.
280 HANDLE handle = ::OpenProcess(PROCESS_ALL_ACCESS, 0, ::GetCurrentProcessId());
281 ::TerminateProcess(handle, kExpectedKilledExitCode);
282 #elif defined(OS_POSIX)
283 // Send a SIGKILL to this process, just like the OOM killer would.
284 ::kill(getpid(), SIGKILL);
285 #endif
286 return 1;
289 TEST_F(ProcessUtilTest, GetTerminationStatusKill) {
290 const std::string signal_file =
291 ProcessUtilTest::GetSignalFilePath(kSignalFileKill);
292 remove(signal_file.c_str());
293 base::Process process = SpawnChild("KilledChildProcess");
294 ASSERT_TRUE(process.IsValid());
296 int exit_code = 42;
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());
302 exit_code = 42;
303 base::TerminationStatus status =
304 WaitForChildTermination(process.Handle(), &exit_code);
305 EXPECT_EQ(base::TERMINATION_STATUS_PROCESS_WAS_KILLED, status);
306 #if defined(OS_WIN)
307 EXPECT_EQ(kExpectedKilledExitCode, exit_code);
308 #elif defined(OS_POSIX)
309 int signaled = WIFSIGNALED(exit_code);
310 EXPECT_NE(0, signaled);
311 int signal = WTERMSIG(exit_code);
312 EXPECT_EQ(SIGKILL, signal);
313 #endif
314 remove(signal_file.c_str());
317 #if defined(OS_WIN)
318 // TODO(estade): if possible, port this test.
319 TEST_F(ProcessUtilTest, GetAppOutput) {
320 // Let's create a decently long message.
321 std::string message;
322 for (int i = 0; i < 1025; i++) { // 1025 so it does not end on a kilo-byte
323 // boundary.
324 message += "Hello!";
326 // cmd.exe's echo always adds a \r\n to its output.
327 std::string expected(message);
328 expected += "\r\n";
330 FilePath cmd(L"cmd.exe");
331 base::CommandLine cmd_line(cmd);
332 cmd_line.AppendArg("/c");
333 cmd_line.AppendArg("echo " + message + "");
334 std::string output;
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");
343 output.clear();
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"),
355 options).IsValid());
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)));
372 event.Signal();
374 return 0;
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());
400 return;
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)
411 namespace {
413 // Returns the maximum number of files that a process can have open.
414 // Returns 0 on error.
415 int GetMaxFilesOpenInProcess() {
416 struct rlimit rlim;
417 if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
418 return 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) {
425 return 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)
437 #define _GUARDID_T
438 typedef __uint64_t guardid_t;
439 #endif // _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
444 #endif
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)
449 #endif
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,
457 int *fdflagsp) {
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())
474 return true;
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
480 // calls.
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.
485 int ret =
486 change_fdguard_np(fd, NULL, 0, &kGuard, GUARD_DUP, &original_fdflags);
487 if (ret == -1)
488 return false;
490 // Remove the guard. It should not be possible to fail in removing the guard
491 // just added.
492 ret = change_fdguard_np(fd, &kGuard, GUARD_DUP, NULL, 0, &original_fdflags);
493 DPCHECK(ret == 0);
495 return true;
497 #endif // OS_MACOSX
499 } // namespace
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.
510 if (!CanGuardFd(i))
511 continue;
512 #endif
514 if (i != kChildPipe) {
515 int fd;
516 if ((fd = HANDLE_EINTR(dup(i))) != -1) {
517 close(fd);
518 num_open_files += 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));
527 DPCHECK(ret == 0);
529 return 0;
532 int ProcessUtilTest::CountOpenFDsInChild() {
533 int fds[2];
534 if (pipe(fds) < 0)
535 NOTREACHED();
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]));
545 DPCHECK(ret == 0);
547 // Read number of open files in client process from pipe;
548 int num_open_files = -1;
549 ssize_t bytes_read =
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);
556 #else
557 base::TimeDelta timeout = base::TimeDelta::FromSeconds(1);
558 #endif
559 int exit_code;
560 CHECK(process.WaitForExitWithTimeout(timeout, &exit_code));
561 ret = IGNORE_EINTR(close(fds[0]));
562 DPCHECK(ret == 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
572 #else
573 #define MAYBE_FDRemapping FDRemapping
574 #endif
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
579 // child process.
580 int dev_null = open("/dev/null", O_RDONLY);
581 int sockets[2];
582 socketpair(AF_UNIX, SOCK_STREAM, 0, sockets);
584 int fds_after = CountOpenFDsInChild();
586 ASSERT_EQ(fds_after, fds_before);
588 int ret;
589 ret = IGNORE_EINTR(close(sockets[0]));
590 DPCHECK(ret == 0);
591 ret = IGNORE_EINTR(close(sockets[1]));
592 DPCHECK(ret == 0);
593 ret = IGNORE_EINTR(close(dev_null));
594 DPCHECK(ret == 0);
597 namespace {
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;
605 int fds[2];
606 PCHECK(pipe(fds) == 0);
608 fds_to_remap.push_back(std::make_pair(fds[1], 1));
609 base::LaunchOptions options;
610 options.wait = true;
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;
616 #else
617 CHECK_EQ(0, clone_flags);
618 #endif // OS_LINUX
619 EXPECT_TRUE(base::LaunchProcess(args, options).IsValid());
620 PCHECK(IGNORE_EINTR(close(fds[1])) == 0);
622 char buf[512];
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";
639 } // namespace
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";
656 EXPECT_EQ("bar\n",
657 TestLaunchProcess(
658 echo_base_test, env_changes, no_clear_environ, no_clone_flags));
659 env_changes.clear();
661 EXPECT_EQ(0, setenv(kBaseTest, "testing", 1 /* override */));
662 EXPECT_EQ("testing\n",
663 TestLaunchProcess(
664 echo_base_test, env_changes, no_clear_environ, no_clone_flags));
666 env_changes[kBaseTest] = std::string();
667 EXPECT_EQ("\n",
668 TestLaunchProcess(
669 echo_base_test, env_changes, no_clear_environ, no_clone_flags));
671 env_changes[kBaseTest] = "foo";
672 EXPECT_EQ("foo\n",
673 TestLaunchProcess(
674 echo_base_test, env_changes, no_clear_environ, no_clone_flags));
676 env_changes.clear();
677 EXPECT_EQ(0, setenv(kBaseTest, kLargeString, 1 /* override */));
678 EXPECT_EQ(std::string(kLargeString) + "\n",
679 TestLaunchProcess(
680 echo_base_test, env_changes, no_clear_environ, no_clone_flags));
682 env_changes[kBaseTest] = "wibble";
683 EXPECT_EQ("wibble\n",
684 TestLaunchProcess(
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));
695 EXPECT_EQ(
696 "BASE_TEST=wibble\n",
697 TestLaunchProcess(
698 print_env, env_changes, true /* clear_environ */, no_clone_flags));
699 env_changes.clear();
700 EXPECT_EQ(
702 TestLaunchProcess(
703 print_env, env_changes, true /* clear_environ */, no_clone_flags));
704 #endif
707 TEST_F(ProcessUtilTest, GetAppOutput) {
708 std::string output;
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());
719 argv[2] = "exit 1";
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());
726 #else
727 EXPECT_TRUE(base::GetAppOutput(base::CommandLine(FilePath("true")),
728 &output));
729 EXPECT_STREQ("", output.c_str());
731 EXPECT_FALSE(base::GetAppOutput(base::CommandLine(FilePath("false")),
732 &output));
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
746 #else
747 #define MAYBE_GetAppOutputRestricted GetAppOutputRestricted
748 #endif
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
752 // its built-ins.
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,
763 100));
764 EXPECT_STREQ("", output.c_str());
766 argv[2] = "exit 1"; // equivalent to "false"
767 output = "before";
768 EXPECT_FALSE(base::GetAppOutputRestricted(base::CommandLine(argv), &output,
769 100));
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")
774 output.clear();
775 EXPECT_TRUE(base::GetAppOutputRestricted(base::CommandLine(argv), &output,
776 10));
777 EXPECT_STREQ("123456789\n", output.c_str());
779 // Amount of output greater than space allowed.
780 output.clear();
781 EXPECT_TRUE(base::GetAppOutputRestricted(base::CommandLine(argv), &output,
782 5));
783 EXPECT_STREQ("12345", output.c_str());
785 // Amount of output less than space allowed.
786 output.clear();
787 EXPECT_TRUE(base::GetAppOutputRestricted(base::CommandLine(argv), &output,
788 15));
789 EXPECT_STREQ("123456789\n", output.c_str());
791 // Zero space allowed.
792 output = "abc";
793 EXPECT_TRUE(base::GetAppOutputRestricted(base::CommandLine(argv), &output,
794 0));
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;
803 std::string output;
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,
810 10));
811 EXPECT_STREQ("1234567890", output.c_str());
812 #else
813 argv.push_back("yes");
814 EXPECT_TRUE(base::GetAppOutputRestricted(base::CommandLine(argv), &output,
815 10));
816 EXPECT_STREQ("y\ny\ny\ny\ny\n", output.c_str());
817 #endif
819 #endif
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
827 #else
828 #define MAYBE_GetAppOutputRestrictedNoZombies GetAppOutputRestrictedNoZombies
829 #endif
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++) {
840 std::string output;
841 EXPECT_TRUE(base::GetAppOutputRestricted(base::CommandLine(argv), &output,
842 100));
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++) {
848 std::string output;
849 EXPECT_TRUE(base::GetAppOutputRestricted(base::CommandLine(argv), &output,
850 10));
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;
858 std::string output;
859 int exit_code;
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,
864 &exit_code));
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
869 // code.
870 output.clear();
871 argv[2] = "echo foo; exit 2";
872 EXPECT_TRUE(base::GetAppOutputWithExitCode(base::CommandLine(argv), &output,
873 &exit_code));
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());
896 int exit_code;
897 child_process.WaitForExitWithTimeout(base::TimeDelta::FromSeconds(5),
898 &exit_code);
900 // Check that process was really killed.
901 EXPECT_TRUE(IsProcessDead(child_process.Handle()));
904 MULTIPROCESS_TEST_MAIN(process_util_test_never_die) {
905 while (1) {
906 sleep(500);
908 return 0;
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.
915 sleep(2);
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) {
923 return 0;
926 #if !defined(OS_ANDROID)
927 const char kPipeValue = '\xcc';
929 class ReadFromPipeDelegate : public base::LaunchOptions::PreExecDelegate {
930 public:
931 explicit ReadFromPipeDelegate(int fd) : fd_(fd) {}
932 ~ReadFromPipeDelegate() override {}
933 void RunAsyncSafe() override {
934 char c;
935 RAW_CHECK(HANDLE_EINTR(read(fd_, &c, 1)) == 1);
936 RAW_CHECK(IGNORE_EINTR(close(fd_)) == 0);
937 RAW_CHECK(c == kPipeValue);
940 private:
941 int fd_;
942 DISALLOW_COPY_AND_ASSIGN(ReadFromPipeDelegate);
945 TEST_F(ProcessUtilTest, PreExecHook) {
946 int pipe_fds[2];
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());
961 read_fd.reset();
962 ASSERT_EQ(1, HANDLE_EINTR(write(write_fd.get(), &kPipeValue, 1)));
964 int exit_code = 42;
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);
980 return kSuccess;
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.
988 return;
991 base::LaunchOptions options;
992 options.clone_flags = CLONE_NEWUSER | CLONE_NEWPID;
994 base::Process process(SpawnChildWithOptions("CheckPidProcess", options));
995 ASSERT_TRUE(process.IsValid());
997 int exit_code = 42;
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()) {
1006 return;
1009 // Warm up the libc pid cache, if there is one.
1010 ASSERT_EQ(syscall(__NR_getpid), getpid());
1012 pid_t ctid = 0;
1013 const pid_t pid =
1014 base::ForkWithFlags(SIGCHLD | CLONE_CHILD_SETTID, nullptr, &ctid);
1015 if (pid == 0) {
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);
1020 _exit(kSuccess);
1023 ASSERT_NE(-1, pid);
1024 int status = 42;
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);
1036 return kSuccess;
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());
1051 int exit_code = 42;
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);
1067 #endif