Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / base / process / process_util_unittest.cc
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.
4
5 #define _CRT_SECURE_NO_WARNINGS
6
7 #include <limits>
8
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"
32
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
55
56 using base::FilePath;
57
58 namespace {
59
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
67
68 const char kSignalFileSlow[] = "SlowChildProcess.die";
69 const char kSignalFileKill[] = "KilledChildProcess.die";
70
71 #if defined(OS_WIN)
72 const int kExpectedStillRunningExitCode = 0x102;
73 const int kExpectedKilledExitCode = 1;
74 #else
75 const int kExpectedStillRunningExitCode = 0;
76 #endif
77
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);
86 }
87
88 // Signals children they should die now.
89 void SignalChildren(const char* filename) {
90   FILE* fp = fopen(filename, "w");
91   fclose(fp);
92 }
93
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());
111
112   return status;
113 }
114
115 }  // namespace
116
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);
126 };
127
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
137 }
138
139 MULTIPROCESS_TEST_MAIN(SimpleChildProcess) {
140   return 0;
141 }
142
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);
150 }
151
152 MULTIPROCESS_TEST_MAIN(SlowChildProcess) {
153   WaitToDie(ProcessUtilTest::GetSignalFilePath(kSignalFileSlow).c_str());
154   return 0;
155 }
156
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());
168 }
169
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);
177
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);
182
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());
191 }
192
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);
204 }
205 #endif
206
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.
212 //
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";
217
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;
229 }
230
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);
244
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);
249
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);
255
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);
265
266   // Reset signal handlers back to "normal".
267   base::debug::EnableInProcessStackDumping();
268   remove(signal_file.c_str());
269 }
270 #endif  // !defined(OS_MACOSX)
271
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;
283 }
284
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);
291
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);
296
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());
312 }
313
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!";
322   }
323   // cmd.exe's echo always adds a \r\n to its output.
324   std::string expected(message);
325   expected += "\r\n";
326
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);
334
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);
343 }
344
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));
353 }
354
355 static const char kEventToTriggerHandleSwitch[] = "event-to-trigger-handle";
356
357 MULTIPROCESS_TEST_MAIN(TriggerEventChildProcess) {
358   std::string handle_value_string =
359       CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
360           kEventToTriggerHandleSwitch);
361   CHECK(!handle_value_string.empty());
362
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));
367
368   event.Signal();
369
370   return 0;
371 }
372
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;
379
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;
387
388   CommandLine cmd_line = MakeCmdLine("TriggerEventChildProcess");
389   cmd_line.AppendSwitchASCII(kEventToTriggerHandleSwitch,
390       base::Uint64ToString(reinterpret_cast<uint64>(event.handle())));
391
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;
397   }
398
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()));
402 }
403 #endif  // defined(OS_WIN)
404
405 #if defined(OS_POSIX)
406
407 namespace {
408
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;
415   }
416
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;
422   }
423
424   return rlim.rlim_cur;
425 }
426
427 const int kChildPipe = 20;  // FD # for write end of pipe in child process.
428
429 #if defined(OS_MACOSX)
430
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
436
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
441
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
446
447 // <http://opensource.apple.com/source/xnu/xnu-2422.1.72/bsd/kern/kern_guarded.c?txt>
448 //
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);
456 }
457
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.
461 //
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;
471
472   // Saves the original flags to reset later.
473   int original_fdflags = 0;
474
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;
478
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;
485
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);
490
491   return true;
492 }
493 #endif  // OS_MACOSX
494
495 }  // namespace
496
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
509
510     if (i != kChildPipe) {
511       int fd;
512       if ((fd = HANDLE_EINTR(dup(i))) != -1) {
513         close(fd);
514         num_open_files += 1;
515       }
516     }
517   }
518
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);
524
525   return 0;
526 }
527
528 int ProcessUtilTest::CountOpenFDsInChild() {
529   int fds[2];
530   if (pipe(fds) < 0)
531     NOTREACHED();
532
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);
542
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)));
548
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);
558
559   return num_open_files;
560 }
561
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();
572
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);
578
579   int fds_after = CountOpenFDsInChild();
580
581   ASSERT_EQ(fds_after, fds_before);
582
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);
590 }
591
592 namespace {
593
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;
599
600   int fds[2];
601   PCHECK(pipe(fds) == 0);
602
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);
616
617   char buf[512];
618   const ssize_t n = HANDLE_EINTR(read(fds[0], buf, sizeof(buf)));
619
620   PCHECK(IGNORE_EINTR(close(fds[0])) == 0);
621
622   return std::string(buf, n);
623 }
624
625 const char kLargeString[] =
626     "0123456789012345678901234567890123456789012345678901234567890123456789"
627     "0123456789012345678901234567890123456789012345678901234567890123456789"
628     "0123456789012345678901234567890123456789012345678901234567890123456789"
629     "0123456789012345678901234567890123456789012345678901234567890123456789"
630     "0123456789012345678901234567890123456789012345678901234567890123456789"
631     "0123456789012345678901234567890123456789012345678901234567890123456789"
632     "0123456789012345678901234567890123456789012345678901234567890123456789";
633
634 }  // namespace
635
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");
642
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;
647
648   const char kBaseTest[] = "BASE_TEST";
649
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();
655
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));
660
661   env_changes[kBaseTest] = std::string();
662   EXPECT_EQ("\n",
663             TestLaunchProcess(
664                 echo_base_test, env_changes, no_clear_environ, no_clone_flags));
665
666   env_changes[kBaseTest] = "foo";
667   EXPECT_EQ("foo\n",
668             TestLaunchProcess(
669                 echo_base_test, env_changes, no_clear_environ, no_clone_flags));
670
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));
676
677   env_changes[kBaseTest] = "wibble";
678   EXPECT_EQ("wibble\n",
679             TestLaunchProcess(
680                 echo_base_test, env_changes, no_clear_environ, no_clone_flags));
681
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));
690   }
691
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(
698       "",
699       TestLaunchProcess(
700           print_env, env_changes, true /* clear_environ */, no_clone_flags));
701 #endif
702 }
703
704 TEST_F(ProcessUtilTest, GetAppOutput) {
705   std::string output;
706
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");
711
712   argv.push_back("exit 0");
713   EXPECT_TRUE(base::GetAppOutput(CommandLine(argv), &output));
714   EXPECT_STREQ("", output.c_str());
715
716   argv[2] = "exit 1";
717   EXPECT_FALSE(base::GetAppOutput(CommandLine(argv), &output));
718   EXPECT_STREQ("", output.c_str());
719
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());
726
727   EXPECT_FALSE(base::GetAppOutput(CommandLine(FilePath("false")), &output));
728
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)
736 }
737
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]
751
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());
759
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());
765
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());
771
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());
776
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());
781
782   // Zero space allowed.
783   output = "abc";
784   EXPECT_TRUE(base::GetAppOutputRestricted(CommandLine(argv), &output, 0));
785   EXPECT_STREQ("", output.c_str());
786 }
787
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;
794
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
806 }
807 #endif
808
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;
820
821   argv.push_back(std::string(kShellPath));  // argv[0]
822   argv.push_back("-c");  // argv[1]
823   argv.push_back("echo 123456789012345678901234567890");  // argv[2]
824
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());
831   }
832
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());
838   }
839 }
840
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);
853
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);
862 }
863
864 TEST_F(ProcessUtilTest, GetParentProcessId) {
865   base::ProcessId ppid = base::GetParentProcessId(base::GetCurrentProcId());
866   EXPECT_EQ(ppid, getppid());
867 }
868
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;
876 }
877
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));
883
884   // Check that process was really killed.
885   EXPECT_TRUE(IsProcessDead(child_process));
886   base::CloseProcessHandle(child_process);
887 }
888
889 MULTIPROCESS_TEST_MAIN(process_util_test_never_die) {
890   while (1) {
891     sleep(500);
892   }
893   return 0;
894 }
895
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);
903
904   // Check that process was really killed.
905   EXPECT_TRUE(IsProcessDead(child_process));
906   base::CloseProcessHandle(child_process);
907 }
908
909 MULTIPROCESS_TEST_MAIN(process_util_test_die_immediately) {
910   return 0;
911 }
912
913 #endif  // defined(OS_POSIX)