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