Home | History | Annotate | Download | only in process
      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 #endif
     54 
     55 using base::FilePath;
     56 
     57 namespace {
     58 
     59 #if defined(OS_ANDROID)
     60 const char kShellPath[] = "/system/bin/sh";
     61 const char kPosixShell[] = "sh";
     62 #else
     63 const char kShellPath[] = "/bin/sh";
     64 const char kPosixShell[] = "bash";
     65 #endif
     66 
     67 const char kSignalFileSlow[] = "SlowChildProcess.die";
     68 const char kSignalFileKill[] = "KilledChildProcess.die";
     69 
     70 #if defined(OS_WIN)
     71 const int kExpectedStillRunningExitCode = 0x102;
     72 const int kExpectedKilledExitCode = 1;
     73 #else
     74 const int kExpectedStillRunningExitCode = 0;
     75 #endif
     76 
     77 // Sleeps until file filename is created.
     78 void WaitToDie(const char* filename) {
     79   FILE* fp;
     80   do {
     81     base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(10));
     82     fp = fopen(filename, "r");
     83   } while (!fp);
     84   fclose(fp);
     85 }
     86 
     87 // Signals children they should die now.
     88 void SignalChildren(const char* filename) {
     89   FILE* fp = fopen(filename, "w");
     90   fclose(fp);
     91 }
     92 
     93 // Using a pipe to the child to wait for an event was considered, but
     94 // there were cases in the past where pipes caused problems (other
     95 // libraries closing the fds, child deadlocking). This is a simple
     96 // case, so it's not worth the risk.  Using wait loops is discouraged
     97 // in most instances.
     98 base::TerminationStatus WaitForChildTermination(base::ProcessHandle handle,
     99                                                 int* exit_code) {
    100   // Now we wait until the result is something other than STILL_RUNNING.
    101   base::TerminationStatus status = base::TERMINATION_STATUS_STILL_RUNNING;
    102   const base::TimeDelta kInterval = base::TimeDelta::FromMilliseconds(20);
    103   base::TimeDelta waited;
    104   do {
    105     status = base::GetTerminationStatus(handle, exit_code);
    106     base::PlatformThread::Sleep(kInterval);
    107     waited += kInterval;
    108   } while (status == base::TERMINATION_STATUS_STILL_RUNNING &&
    109 // Waiting for more time for process termination on android devices.
    110 #if defined(OS_ANDROID)
    111            waited < TestTimeouts::large_test_timeout());
    112 #else
    113            waited < TestTimeouts::action_max_timeout());
    114 #endif
    115 
    116   return status;
    117 }
    118 
    119 }  // namespace
    120 
    121 class ProcessUtilTest : public base::MultiProcessTest {
    122  public:
    123 #if defined(OS_POSIX)
    124   // Spawn a child process that counts how many file descriptors are open.
    125   int CountOpenFDsInChild();
    126 #endif
    127   // Converts the filename to a platform specific filepath.
    128   // On Android files can not be created in arbitrary directories.
    129   static std::string GetSignalFilePath(const char* filename);
    130 };
    131 
    132 std::string ProcessUtilTest::GetSignalFilePath(const char* filename) {
    133 #if !defined(OS_ANDROID)
    134   return filename;
    135 #else
    136   FilePath tmp_dir;
    137   PathService::Get(base::DIR_CACHE, &tmp_dir);
    138   tmp_dir = tmp_dir.Append(filename);
    139   return tmp_dir.value();
    140 #endif
    141 }
    142 
    143 MULTIPROCESS_TEST_MAIN(SimpleChildProcess) {
    144   return 0;
    145 }
    146 
    147 TEST_F(ProcessUtilTest, SpawnChild) {
    148   base::ProcessHandle handle = this->SpawnChild("SimpleChildProcess", false);
    149   ASSERT_NE(base::kNullProcessHandle, handle);
    150   EXPECT_TRUE(base::WaitForSingleProcess(
    151                   handle, TestTimeouts::action_max_timeout()));
    152   base::CloseProcessHandle(handle);
    153 }
    154 
    155 MULTIPROCESS_TEST_MAIN(SlowChildProcess) {
    156   WaitToDie(ProcessUtilTest::GetSignalFilePath(kSignalFileSlow).c_str());
    157   return 0;
    158 }
    159 
    160 TEST_F(ProcessUtilTest, KillSlowChild) {
    161   const std::string signal_file =
    162       ProcessUtilTest::GetSignalFilePath(kSignalFileSlow);
    163   remove(signal_file.c_str());
    164   base::ProcessHandle handle = this->SpawnChild("SlowChildProcess", false);
    165   ASSERT_NE(base::kNullProcessHandle, handle);
    166   SignalChildren(signal_file.c_str());
    167   EXPECT_TRUE(base::WaitForSingleProcess(
    168                   handle, TestTimeouts::action_max_timeout()));
    169   base::CloseProcessHandle(handle);
    170   remove(signal_file.c_str());
    171 }
    172 
    173 // Times out on Linux and Win, flakes on other platforms, http://crbug.com/95058
    174 TEST_F(ProcessUtilTest, DISABLED_GetTerminationStatusExit) {
    175   const std::string signal_file =
    176       ProcessUtilTest::GetSignalFilePath(kSignalFileSlow);
    177   remove(signal_file.c_str());
    178   base::ProcessHandle handle = this->SpawnChild("SlowChildProcess", false);
    179   ASSERT_NE(base::kNullProcessHandle, handle);
    180 
    181   int exit_code = 42;
    182   EXPECT_EQ(base::TERMINATION_STATUS_STILL_RUNNING,
    183             base::GetTerminationStatus(handle, &exit_code));
    184   EXPECT_EQ(kExpectedStillRunningExitCode, exit_code);
    185 
    186   SignalChildren(signal_file.c_str());
    187   exit_code = 42;
    188   base::TerminationStatus status =
    189       WaitForChildTermination(handle, &exit_code);
    190   EXPECT_EQ(base::TERMINATION_STATUS_NORMAL_TERMINATION, status);
    191   EXPECT_EQ(0, exit_code);
    192   base::CloseProcessHandle(handle);
    193   remove(signal_file.c_str());
    194 }
    195 
    196 #if defined(OS_WIN)
    197 // TODO(cpu): figure out how to test this in other platforms.
    198 TEST_F(ProcessUtilTest, GetProcId) {
    199   base::ProcessId id1 = base::GetProcId(GetCurrentProcess());
    200   EXPECT_NE(0ul, id1);
    201   base::ProcessHandle handle = this->SpawnChild("SimpleChildProcess", false);
    202   ASSERT_NE(base::kNullProcessHandle, handle);
    203   base::ProcessId id2 = base::GetProcId(handle);
    204   EXPECT_NE(0ul, id2);
    205   EXPECT_NE(id1, id2);
    206   base::CloseProcessHandle(handle);
    207 }
    208 #endif
    209 
    210 #if !defined(OS_MACOSX)
    211 // This test is disabled on Mac, since it's flaky due to ReportCrash
    212 // taking a variable amount of time to parse and load the debug and
    213 // symbol data for this unit test's executable before firing the
    214 // signal handler.
    215 //
    216 // TODO(gspencer): turn this test process into a very small program
    217 // with no symbols (instead of using the multiprocess testing
    218 // framework) to reduce the ReportCrash overhead.
    219 const char kSignalFileCrash[] = "CrashingChildProcess.die";
    220 
    221 MULTIPROCESS_TEST_MAIN(CrashingChildProcess) {
    222   WaitToDie(ProcessUtilTest::GetSignalFilePath(kSignalFileCrash).c_str());
    223 #if defined(OS_POSIX)
    224   // Have to disable to signal handler for segv so we can get a crash
    225   // instead of an abnormal termination through the crash dump handler.
    226   ::signal(SIGSEGV, SIG_DFL);
    227 #endif
    228   // Make this process have a segmentation fault.
    229   volatile int* oops = NULL;
    230   *oops = 0xDEAD;
    231   return 1;
    232 }
    233 
    234 // This test intentionally crashes, so we don't need to run it under
    235 // AddressSanitizer.
    236 // TODO(jschuh): crbug.com/175753 Fix this in Win64 bots.
    237 #if defined(ADDRESS_SANITIZER) || (defined(OS_WIN) && defined(ARCH_CPU_X86_64))
    238 #define MAYBE_GetTerminationStatusCrash DISABLED_GetTerminationStatusCrash
    239 #else
    240 #define MAYBE_GetTerminationStatusCrash GetTerminationStatusCrash
    241 #endif
    242 TEST_F(ProcessUtilTest, MAYBE_GetTerminationStatusCrash) {
    243   const std::string signal_file =
    244     ProcessUtilTest::GetSignalFilePath(kSignalFileCrash);
    245   remove(signal_file.c_str());
    246   base::ProcessHandle handle = this->SpawnChild("CrashingChildProcess",
    247                                                 false);
    248   ASSERT_NE(base::kNullProcessHandle, handle);
    249 
    250   int exit_code = 42;
    251   EXPECT_EQ(base::TERMINATION_STATUS_STILL_RUNNING,
    252             base::GetTerminationStatus(handle, &exit_code));
    253   EXPECT_EQ(kExpectedStillRunningExitCode, exit_code);
    254 
    255   SignalChildren(signal_file.c_str());
    256   exit_code = 42;
    257   base::TerminationStatus status =
    258       WaitForChildTermination(handle, &exit_code);
    259   EXPECT_EQ(base::TERMINATION_STATUS_PROCESS_CRASHED, status);
    260 
    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
    269   base::CloseProcessHandle(handle);
    270 
    271   // Reset signal handlers back to "normal".
    272   base::debug::EnableInProcessStackDumping();
    273   remove(signal_file.c_str());
    274 }
    275 #endif  // !defined(OS_MACOSX)
    276 
    277 MULTIPROCESS_TEST_MAIN(KilledChildProcess) {
    278   WaitToDie(ProcessUtilTest::GetSignalFilePath(kSignalFileKill).c_str());
    279 #if defined(OS_WIN)
    280   // Kill ourselves.
    281   HANDLE handle = ::OpenProcess(PROCESS_ALL_ACCESS, 0, ::GetCurrentProcessId());
    282   ::TerminateProcess(handle, kExpectedKilledExitCode);
    283 #elif defined(OS_POSIX)
    284   // Send a SIGKILL to this process, just like the OOM killer would.
    285   ::kill(getpid(), SIGKILL);
    286 #endif
    287   return 1;
    288 }
    289 
    290 TEST_F(ProcessUtilTest, GetTerminationStatusKill) {
    291   const std::string signal_file =
    292     ProcessUtilTest::GetSignalFilePath(kSignalFileKill);
    293   remove(signal_file.c_str());
    294   base::ProcessHandle handle = this->SpawnChild("KilledChildProcess",
    295                                                 false);
    296   ASSERT_NE(base::kNullProcessHandle, handle);
    297 
    298   int exit_code = 42;
    299   EXPECT_EQ(base::TERMINATION_STATUS_STILL_RUNNING,
    300             base::GetTerminationStatus(handle, &exit_code));
    301   EXPECT_EQ(kExpectedStillRunningExitCode, exit_code);
    302 
    303   SignalChildren(signal_file.c_str());
    304   exit_code = 42;
    305   base::TerminationStatus status =
    306       WaitForChildTermination(handle, &exit_code);
    307   EXPECT_EQ(base::TERMINATION_STATUS_PROCESS_WAS_KILLED, status);
    308 #if defined(OS_WIN)
    309   EXPECT_EQ(kExpectedKilledExitCode, exit_code);
    310 #elif defined(OS_POSIX)
    311   int signaled = WIFSIGNALED(exit_code);
    312   EXPECT_NE(0, signaled);
    313   int signal = WTERMSIG(exit_code);
    314   EXPECT_EQ(SIGKILL, signal);
    315 #endif
    316   base::CloseProcessHandle(handle);
    317   remove(signal_file.c_str());
    318 }
    319 
    320 // Ensure that the priority of a process is restored correctly after
    321 // backgrounding and restoring.
    322 // Note: a platform may not be willing or able to lower the priority of
    323 // a process. The calls to SetProcessBackground should be noops then.
    324 TEST_F(ProcessUtilTest, SetProcessBackgrounded) {
    325   base::ProcessHandle handle = this->SpawnChild("SimpleChildProcess", false);
    326   base::Process process(handle);
    327   int old_priority = process.GetPriority();
    328 #if defined(OS_WIN)
    329   EXPECT_TRUE(process.SetProcessBackgrounded(true));
    330   EXPECT_TRUE(process.IsProcessBackgrounded());
    331   EXPECT_TRUE(process.SetProcessBackgrounded(false));
    332   EXPECT_FALSE(process.IsProcessBackgrounded());
    333 #else
    334   process.SetProcessBackgrounded(true);
    335   process.SetProcessBackgrounded(false);
    336 #endif
    337   int new_priority = process.GetPriority();
    338   EXPECT_EQ(old_priority, new_priority);
    339 }
    340 
    341 // Same as SetProcessBackgrounded but to this very process. It uses
    342 // a different code path at least for Windows.
    343 TEST_F(ProcessUtilTest, SetProcessBackgroundedSelf) {
    344   base::Process process(base::Process::Current().handle());
    345   int old_priority = process.GetPriority();
    346 #if defined(OS_WIN)
    347   EXPECT_TRUE(process.SetProcessBackgrounded(true));
    348   EXPECT_TRUE(process.IsProcessBackgrounded());
    349   EXPECT_TRUE(process.SetProcessBackgrounded(false));
    350   EXPECT_FALSE(process.IsProcessBackgrounded());
    351 #else
    352   process.SetProcessBackgrounded(true);
    353   process.SetProcessBackgrounded(false);
    354 #endif
    355   int new_priority = process.GetPriority();
    356   EXPECT_EQ(old_priority, new_priority);
    357 }
    358 
    359 #if defined(OS_WIN)
    360 // TODO(estade): if possible, port this test.
    361 TEST_F(ProcessUtilTest, GetAppOutput) {
    362   // Let's create a decently long message.
    363   std::string message;
    364   for (int i = 0; i < 1025; i++) {  // 1025 so it does not end on a kilo-byte
    365                                     // boundary.
    366     message += "Hello!";
    367   }
    368   // cmd.exe's echo always adds a \r\n to its output.
    369   std::string expected(message);
    370   expected += "\r\n";
    371 
    372   FilePath cmd(L"cmd.exe");
    373   CommandLine cmd_line(cmd);
    374   cmd_line.AppendArg("/c");
    375   cmd_line.AppendArg("echo " + message + "");
    376   std::string output;
    377   ASSERT_TRUE(base::GetAppOutput(cmd_line, &output));
    378   EXPECT_EQ(expected, output);
    379 
    380   // Let's make sure stderr is ignored.
    381   CommandLine other_cmd_line(cmd);
    382   other_cmd_line.AppendArg("/c");
    383   // http://msdn.microsoft.com/library/cc772622.aspx
    384   cmd_line.AppendArg("echo " + message + " >&2");
    385   output.clear();
    386   ASSERT_TRUE(base::GetAppOutput(other_cmd_line, &output));
    387   EXPECT_EQ("", output);
    388 }
    389 
    390 // TODO(estade): if possible, port this test.
    391 TEST_F(ProcessUtilTest, LaunchAsUser) {
    392   base::UserTokenHandle token;
    393   ASSERT_TRUE(OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &token));
    394   base::LaunchOptions options;
    395   options.as_user = token;
    396   EXPECT_TRUE(base::LaunchProcess(
    397       this->MakeCmdLine("SimpleChildProcess", false), options, NULL));
    398 }
    399 
    400 static const char kEventToTriggerHandleSwitch[] = "event-to-trigger-handle";
    401 
    402 MULTIPROCESS_TEST_MAIN(TriggerEventChildProcess) {
    403   std::string handle_value_string =
    404       CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
    405           kEventToTriggerHandleSwitch);
    406   CHECK(!handle_value_string.empty());
    407 
    408   uint64 handle_value_uint64;
    409   CHECK(base::StringToUint64(handle_value_string, &handle_value_uint64));
    410   // Give ownership of the handle to |event|.
    411   base::WaitableEvent event(reinterpret_cast<HANDLE>(handle_value_uint64));
    412 
    413   event.Signal();
    414 
    415   return 0;
    416 }
    417 
    418 TEST_F(ProcessUtilTest, InheritSpecifiedHandles) {
    419   // Manually create the event, so that it can be inheritable.
    420   SECURITY_ATTRIBUTES security_attributes = {};
    421   security_attributes.nLength = static_cast<DWORD>(sizeof(security_attributes));
    422   security_attributes.lpSecurityDescriptor = NULL;
    423   security_attributes.bInheritHandle = true;
    424 
    425   // Takes ownership of the event handle.
    426   base::WaitableEvent event(
    427       CreateEvent(&security_attributes, true, false, NULL));
    428   base::HandlesToInheritVector handles_to_inherit;
    429   handles_to_inherit.push_back(event.handle());
    430   base::LaunchOptions options;
    431   options.handles_to_inherit = &handles_to_inherit;
    432 
    433   CommandLine cmd_line = MakeCmdLine("TriggerEventChildProcess", false);
    434   cmd_line.AppendSwitchASCII(kEventToTriggerHandleSwitch,
    435       base::Uint64ToString(reinterpret_cast<uint64>(event.handle())));
    436 
    437   // This functionality actually requires Vista or later. Make sure that it
    438   // fails properly on XP.
    439   if (base::win::GetVersion() < base::win::VERSION_VISTA) {
    440     EXPECT_FALSE(base::LaunchProcess(cmd_line, options, NULL));
    441     return;
    442   }
    443 
    444   // Launch the process and wait for it to trigger the event.
    445   ASSERT_TRUE(base::LaunchProcess(cmd_line, options, NULL));
    446   EXPECT_TRUE(event.TimedWait(TestTimeouts::action_max_timeout()));
    447 }
    448 #endif  // defined(OS_WIN)
    449 
    450 #if defined(OS_POSIX)
    451 
    452 namespace {
    453 
    454 // Returns the maximum number of files that a process can have open.
    455 // Returns 0 on error.
    456 int GetMaxFilesOpenInProcess() {
    457   struct rlimit rlim;
    458   if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
    459     return 0;
    460   }
    461 
    462   // rlim_t is a uint64 - clip to maxint. We do this since FD #s are ints
    463   // which are all 32 bits on the supported platforms.
    464   rlim_t max_int = static_cast<rlim_t>(std::numeric_limits<int32>::max());
    465   if (rlim.rlim_cur > max_int) {
    466     return max_int;
    467   }
    468 
    469   return rlim.rlim_cur;
    470 }
    471 
    472 const int kChildPipe = 20;  // FD # for write end of pipe in child process.
    473 
    474 }  // namespace
    475 
    476 MULTIPROCESS_TEST_MAIN(ProcessUtilsLeakFDChildProcess) {
    477   // This child process counts the number of open FDs, it then writes that
    478   // number out to a pipe connected to the parent.
    479   int num_open_files = 0;
    480   int write_pipe = kChildPipe;
    481   int max_files = GetMaxFilesOpenInProcess();
    482   for (int i = STDERR_FILENO + 1; i < max_files; i++) {
    483     if (i != kChildPipe) {
    484       int fd;
    485       if ((fd = HANDLE_EINTR(dup(i))) != -1) {
    486         close(fd);
    487         num_open_files += 1;
    488       }
    489     }
    490   }
    491 
    492   int written = HANDLE_EINTR(write(write_pipe, &num_open_files,
    493                                    sizeof(num_open_files)));
    494   DCHECK_EQ(static_cast<size_t>(written), sizeof(num_open_files));
    495   int ret = IGNORE_EINTR(close(write_pipe));
    496   DPCHECK(ret == 0);
    497 
    498   return 0;
    499 }
    500 
    501 int ProcessUtilTest::CountOpenFDsInChild() {
    502   int fds[2];
    503   if (pipe(fds) < 0)
    504     NOTREACHED();
    505 
    506   base::FileHandleMappingVector fd_mapping_vec;
    507   fd_mapping_vec.push_back(std::pair<int, int>(fds[1], kChildPipe));
    508   base::ProcessHandle handle = this->SpawnChild(
    509       "ProcessUtilsLeakFDChildProcess", fd_mapping_vec, false);
    510   CHECK(handle);
    511   int ret = IGNORE_EINTR(close(fds[1]));
    512   DPCHECK(ret == 0);
    513 
    514   // Read number of open files in client process from pipe;
    515   int num_open_files = -1;
    516   ssize_t bytes_read =
    517       HANDLE_EINTR(read(fds[0], &num_open_files, sizeof(num_open_files)));
    518   CHECK_EQ(bytes_read, static_cast<ssize_t>(sizeof(num_open_files)));
    519 
    520 #if defined(THREAD_SANITIZER) || defined(USE_HEAPCHECKER)
    521   // Compiler-based ThreadSanitizer makes this test slow.
    522   CHECK(base::WaitForSingleProcess(handle, base::TimeDelta::FromSeconds(3)));
    523 #else
    524   CHECK(base::WaitForSingleProcess(handle, base::TimeDelta::FromSeconds(1)));
    525 #endif
    526   base::CloseProcessHandle(handle);
    527   ret = IGNORE_EINTR(close(fds[0]));
    528   DPCHECK(ret == 0);
    529 
    530   return num_open_files;
    531 }
    532 
    533 #if defined(ADDRESS_SANITIZER) || defined(THREAD_SANITIZER)
    534 // ProcessUtilTest.FDRemapping is flaky when ran under xvfb-run on Precise.
    535 // The problem is 100% reproducible with both ASan and TSan.
    536 // See http://crbug.com/136720.
    537 #define MAYBE_FDRemapping DISABLED_FDRemapping
    538 #else
    539 #define MAYBE_FDRemapping FDRemapping
    540 #endif
    541 TEST_F(ProcessUtilTest, MAYBE_FDRemapping) {
    542   int fds_before = CountOpenFDsInChild();
    543 
    544   // open some dummy fds to make sure they don't propagate over to the
    545   // child process.
    546   int dev_null = open("/dev/null", O_RDONLY);
    547   int sockets[2];
    548   socketpair(AF_UNIX, SOCK_STREAM, 0, sockets);
    549 
    550   int fds_after = CountOpenFDsInChild();
    551 
    552   ASSERT_EQ(fds_after, fds_before);
    553 
    554   int ret;
    555   ret = IGNORE_EINTR(close(sockets[0]));
    556   DPCHECK(ret == 0);
    557   ret = IGNORE_EINTR(close(sockets[1]));
    558   DPCHECK(ret == 0);
    559   ret = IGNORE_EINTR(close(dev_null));
    560   DPCHECK(ret == 0);
    561 }
    562 
    563 namespace {
    564 
    565 std::string TestLaunchProcess(const base::EnvironmentMap& env_changes,
    566                               const int clone_flags) {
    567   std::vector<std::string> args;
    568   base::FileHandleMappingVector fds_to_remap;
    569 
    570   args.push_back(kPosixShell);
    571   args.push_back("-c");
    572   args.push_back("echo $BASE_TEST");
    573 
    574   int fds[2];
    575   PCHECK(pipe(fds) == 0);
    576 
    577   fds_to_remap.push_back(std::make_pair(fds[1], 1));
    578   base::LaunchOptions options;
    579   options.wait = true;
    580   options.environ = env_changes;
    581   options.fds_to_remap = &fds_to_remap;
    582 #if defined(OS_LINUX)
    583   options.clone_flags = clone_flags;
    584 #else
    585   CHECK_EQ(0, clone_flags);
    586 #endif  // OS_LINUX
    587   EXPECT_TRUE(base::LaunchProcess(args, options, NULL));
    588   PCHECK(IGNORE_EINTR(close(fds[1])) == 0);
    589 
    590   char buf[512];
    591   const ssize_t n = HANDLE_EINTR(read(fds[0], buf, sizeof(buf)));
    592   PCHECK(n > 0);
    593 
    594   PCHECK(IGNORE_EINTR(close(fds[0])) == 0);
    595 
    596   return std::string(buf, n);
    597 }
    598 
    599 const char kLargeString[] =
    600     "0123456789012345678901234567890123456789012345678901234567890123456789"
    601     "0123456789012345678901234567890123456789012345678901234567890123456789"
    602     "0123456789012345678901234567890123456789012345678901234567890123456789"
    603     "0123456789012345678901234567890123456789012345678901234567890123456789"
    604     "0123456789012345678901234567890123456789012345678901234567890123456789"
    605     "0123456789012345678901234567890123456789012345678901234567890123456789"
    606     "0123456789012345678901234567890123456789012345678901234567890123456789";
    607 
    608 }  // namespace
    609 
    610 TEST_F(ProcessUtilTest, LaunchProcess) {
    611   base::EnvironmentMap env_changes;
    612   const int no_clone_flags = 0;
    613 
    614   const char kBaseTest[] = "BASE_TEST";
    615 
    616   env_changes[kBaseTest] = "bar";
    617   EXPECT_EQ("bar\n", TestLaunchProcess(env_changes, no_clone_flags));
    618   env_changes.clear();
    619 
    620   EXPECT_EQ(0, setenv(kBaseTest, "testing", 1 /* override */));
    621   EXPECT_EQ("testing\n", TestLaunchProcess(env_changes, no_clone_flags));
    622 
    623   env_changes[kBaseTest] = std::string();
    624   EXPECT_EQ("\n", TestLaunchProcess(env_changes, no_clone_flags));
    625 
    626   env_changes[kBaseTest] = "foo";
    627   EXPECT_EQ("foo\n", TestLaunchProcess(env_changes, no_clone_flags));
    628 
    629   env_changes.clear();
    630   EXPECT_EQ(0, setenv(kBaseTest, kLargeString, 1 /* override */));
    631   EXPECT_EQ(std::string(kLargeString) + "\n",
    632             TestLaunchProcess(env_changes, no_clone_flags));
    633 
    634   env_changes[kBaseTest] = "wibble";
    635   EXPECT_EQ("wibble\n", TestLaunchProcess(env_changes, no_clone_flags));
    636 
    637 #if defined(OS_LINUX)
    638   // Test a non-trival value for clone_flags.
    639   // Don't test on Valgrind as it has limited support for clone().
    640   if (!RunningOnValgrind()) {
    641     EXPECT_EQ("wibble\n", TestLaunchProcess(env_changes, CLONE_FS | SIGCHLD));
    642   }
    643 #endif
    644 }
    645 
    646 TEST_F(ProcessUtilTest, GetAppOutput) {
    647   std::string output;
    648 
    649 #if defined(OS_ANDROID)
    650   std::vector<std::string> argv;
    651   argv.push_back("sh");  // Instead of /bin/sh, force path search to find it.
    652   argv.push_back("-c");
    653 
    654   argv.push_back("exit 0");
    655   EXPECT_TRUE(base::GetAppOutput(CommandLine(argv), &output));
    656   EXPECT_STREQ("", output.c_str());
    657 
    658   argv[2] = "exit 1";
    659   EXPECT_FALSE(base::GetAppOutput(CommandLine(argv), &output));
    660   EXPECT_STREQ("", output.c_str());
    661 
    662   argv[2] = "echo foobar42";
    663   EXPECT_TRUE(base::GetAppOutput(CommandLine(argv), &output));
    664   EXPECT_STREQ("foobar42\n", output.c_str());
    665 #else
    666   EXPECT_TRUE(base::GetAppOutput(CommandLine(FilePath("true")), &output));
    667   EXPECT_STREQ("", output.c_str());
    668 
    669   EXPECT_FALSE(base::GetAppOutput(CommandLine(FilePath("false")), &output));
    670 
    671   std::vector<std::string> argv;
    672   argv.push_back("/bin/echo");
    673   argv.push_back("-n");
    674   argv.push_back("foobar42");
    675   EXPECT_TRUE(base::GetAppOutput(CommandLine(argv), &output));
    676   EXPECT_STREQ("foobar42", output.c_str());
    677 #endif  // defined(OS_ANDROID)
    678 }
    679 
    680 TEST_F(ProcessUtilTest, GetAppOutputRestricted) {
    681   // Unfortunately, since we can't rely on the path, we need to know where
    682   // everything is. So let's use /bin/sh, which is on every POSIX system, and
    683   // its built-ins.
    684   std::vector<std::string> argv;
    685   argv.push_back(std::string(kShellPath));  // argv[0]
    686   argv.push_back("-c");  // argv[1]
    687 
    688   // On success, should set |output|. We use |/bin/sh -c 'exit 0'| instead of
    689   // |true| since the location of the latter may be |/bin| or |/usr/bin| (and we
    690   // need absolute paths).
    691   argv.push_back("exit 0");   // argv[2]; equivalent to "true"
    692   std::string output = "abc";
    693   EXPECT_TRUE(base::GetAppOutputRestricted(CommandLine(argv), &output, 100));
    694   EXPECT_STREQ("", output.c_str());
    695 
    696   argv[2] = "exit 1";  // equivalent to "false"
    697   output = "before";
    698   EXPECT_FALSE(base::GetAppOutputRestricted(CommandLine(argv),
    699                                             &output, 100));
    700   EXPECT_STREQ("", output.c_str());
    701 
    702   // Amount of output exactly equal to space allowed.
    703   argv[2] = "echo 123456789";  // (the sh built-in doesn't take "-n")
    704   output.clear();
    705   EXPECT_TRUE(base::GetAppOutputRestricted(CommandLine(argv), &output, 10));
    706   EXPECT_STREQ("123456789\n", output.c_str());
    707 
    708   // Amount of output greater than space allowed.
    709   output.clear();
    710   EXPECT_TRUE(base::GetAppOutputRestricted(CommandLine(argv), &output, 5));
    711   EXPECT_STREQ("12345", output.c_str());
    712 
    713   // Amount of output less than space allowed.
    714   output.clear();
    715   EXPECT_TRUE(base::GetAppOutputRestricted(CommandLine(argv), &output, 15));
    716   EXPECT_STREQ("123456789\n", output.c_str());
    717 
    718   // Zero space allowed.
    719   output = "abc";
    720   EXPECT_TRUE(base::GetAppOutputRestricted(CommandLine(argv), &output, 0));
    721   EXPECT_STREQ("", output.c_str());
    722 }
    723 
    724 #if !defined(OS_MACOSX) && !defined(OS_OPENBSD)
    725 // TODO(benwells): GetAppOutputRestricted should terminate applications
    726 // with SIGPIPE when we have enough output. http://crbug.com/88502
    727 TEST_F(ProcessUtilTest, GetAppOutputRestrictedSIGPIPE) {
    728   std::vector<std::string> argv;
    729   std::string output;
    730 
    731   argv.push_back(std::string(kShellPath));  // argv[0]
    732   argv.push_back("-c");
    733 #if defined(OS_ANDROID)
    734   argv.push_back("while echo 12345678901234567890; do :; done");
    735   EXPECT_TRUE(base::GetAppOutputRestricted(CommandLine(argv), &output, 10));
    736   EXPECT_STREQ("1234567890", output.c_str());
    737 #else
    738   argv.push_back("yes");
    739   EXPECT_TRUE(base::GetAppOutputRestricted(CommandLine(argv), &output, 10));
    740   EXPECT_STREQ("y\ny\ny\ny\ny\n", output.c_str());
    741 #endif
    742 }
    743 #endif
    744 
    745 #if defined(ADDRESS_SANITIZER) && defined(OS_MACOSX) && \
    746     defined(ARCH_CPU_64_BITS)
    747 // Times out under AddressSanitizer on 64-bit OS X, see
    748 // http://crbug.com/298197.
    749 #define MAYBE_GetAppOutputRestrictedNoZombies \
    750     DISABLED_GetAppOutputRestrictedNoZombies
    751 #else
    752 #define MAYBE_GetAppOutputRestrictedNoZombies GetAppOutputRestrictedNoZombies
    753 #endif
    754 TEST_F(ProcessUtilTest, MAYBE_GetAppOutputRestrictedNoZombies) {
    755   std::vector<std::string> argv;
    756 
    757   argv.push_back(std::string(kShellPath));  // argv[0]
    758   argv.push_back("-c");  // argv[1]
    759   argv.push_back("echo 123456789012345678901234567890");  // argv[2]
    760 
    761   // Run |GetAppOutputRestricted()| 300 (> default per-user processes on Mac OS
    762   // 10.5) times with an output buffer big enough to capture all output.
    763   for (int i = 0; i < 300; i++) {
    764     std::string output;
    765     EXPECT_TRUE(base::GetAppOutputRestricted(CommandLine(argv), &output, 100));
    766     EXPECT_STREQ("123456789012345678901234567890\n", output.c_str());
    767   }
    768 
    769   // Ditto, but with an output buffer too small to capture all output.
    770   for (int i = 0; i < 300; i++) {
    771     std::string output;
    772     EXPECT_TRUE(base::GetAppOutputRestricted(CommandLine(argv), &output, 10));
    773     EXPECT_STREQ("1234567890", output.c_str());
    774   }
    775 }
    776 
    777 TEST_F(ProcessUtilTest, GetAppOutputWithExitCode) {
    778   // Test getting output from a successful application.
    779   std::vector<std::string> argv;
    780   std::string output;
    781   int exit_code;
    782   argv.push_back(std::string(kShellPath));  // argv[0]
    783   argv.push_back("-c");  // argv[1]
    784   argv.push_back("echo foo");  // argv[2];
    785   EXPECT_TRUE(base::GetAppOutputWithExitCode(CommandLine(argv), &output,
    786                                              &exit_code));
    787   EXPECT_STREQ("foo\n", output.c_str());
    788   EXPECT_EQ(exit_code, 0);
    789 
    790   // Test getting output from an application which fails with a specific exit
    791   // code.
    792   output.clear();
    793   argv[2] = "echo foo; exit 2";
    794   EXPECT_TRUE(base::GetAppOutputWithExitCode(CommandLine(argv), &output,
    795                                              &exit_code));
    796   EXPECT_STREQ("foo\n", output.c_str());
    797   EXPECT_EQ(exit_code, 2);
    798 }
    799 
    800 TEST_F(ProcessUtilTest, GetParentProcessId) {
    801   base::ProcessId ppid = base::GetParentProcessId(base::GetCurrentProcId());
    802   EXPECT_EQ(ppid, getppid());
    803 }
    804 
    805 // TODO(port): port those unit tests.
    806 bool IsProcessDead(base::ProcessHandle child) {
    807   // waitpid() will actually reap the process which is exactly NOT what we
    808   // want to test for.  The good thing is that if it can't find the process
    809   // we'll get a nice value for errno which we can test for.
    810   const pid_t result = HANDLE_EINTR(waitpid(child, NULL, WNOHANG));
    811   return result == -1 && errno == ECHILD;
    812 }
    813 
    814 TEST_F(ProcessUtilTest, DelayedTermination) {
    815   base::ProcessHandle child_process =
    816       SpawnChild("process_util_test_never_die", false);
    817   ASSERT_TRUE(child_process);
    818   base::EnsureProcessTerminated(child_process);
    819   base::WaitForSingleProcess(child_process, base::TimeDelta::FromSeconds(5));
    820 
    821   // Check that process was really killed.
    822   EXPECT_TRUE(IsProcessDead(child_process));
    823   base::CloseProcessHandle(child_process);
    824 }
    825 
    826 MULTIPROCESS_TEST_MAIN(process_util_test_never_die) {
    827   while (1) {
    828     sleep(500);
    829   }
    830   return 0;
    831 }
    832 
    833 TEST_F(ProcessUtilTest, ImmediateTermination) {
    834   base::ProcessHandle child_process =
    835       SpawnChild("process_util_test_die_immediately", false);
    836   ASSERT_TRUE(child_process);
    837   // Give it time to die.
    838   sleep(2);
    839   base::EnsureProcessTerminated(child_process);
    840 
    841   // Check that process was really killed.
    842   EXPECT_TRUE(IsProcessDead(child_process));
    843   base::CloseProcessHandle(child_process);
    844 }
    845 
    846 MULTIPROCESS_TEST_MAIN(process_util_test_die_immediately) {
    847   return 0;
    848 }
    849 
    850 #endif  // defined(OS_POSIX)
    851