1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #define _CRT_SECURE_NO_WARNINGS
9 #include "base/command_line.h"
10 #include "base/debug/alias.h"
11 #include "base/debug/stack_trace.h"
12 #include "base/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_util.h"
18 #include "base/test/multiprocess_test.h"
19 #include "base/test/test_timeouts.h"
20 #include "base/third_party/dynamic_annotations/dynamic_annotations.h"
21 #include "base/threading/platform_thread.h"
22 #include "base/utf_string_conversions.h"
23 #include "testing/gtest/include/gtest/gtest.h"
24 #include "testing/multiprocess_func_list.h"
36 #include <sys/resource.h>
37 #include <sys/socket.h>
43 #if defined(OS_MACOSX)
44 #include <mach/vm_param.h>
45 #include <malloc/malloc.h>
46 #include "base/process_util_unittest_mac.h"
52 const wchar_t kProcessName
[] = L
"base_unittests.exe";
54 const wchar_t kProcessName
[] = L
"base_unittests";
55 #endif // defined(OS_WIN)
57 #if defined(OS_ANDROID)
58 const char kShellPath
[] = "/system/bin/sh";
59 const char kPosixShell
[] = "sh";
61 const char kShellPath
[] = "/bin/sh";
62 const char kPosixShell
[] = "bash";
65 const char kSignalFileSlow
[] = "SlowChildProcess.die";
66 const char kSignalFileCrash
[] = "CrashingChildProcess.die";
67 const char kSignalFileKill
[] = "KilledChildProcess.die";
70 const int kExpectedStillRunningExitCode
= 0x102;
71 const int kExpectedKilledExitCode
= 1;
73 const int kExpectedStillRunningExitCode
= 0;
76 // Sleeps until file filename is created.
77 void WaitToDie(const char* filename
) {
80 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(10));
81 fp
= fopen(filename
, "r");
86 // Signals children they should die now.
87 void SignalChildren(const char* filename
) {
88 FILE* fp
= fopen(filename
, "w");
92 // Using a pipe to the child to wait for an event was considered, but
93 // there were cases in the past where pipes caused problems (other
94 // libraries closing the fds, child deadlocking). This is a simple
95 // case, so it's not worth the risk. Using wait loops is discouraged
97 base::TerminationStatus
WaitForChildTermination(base::ProcessHandle handle
,
99 // Now we wait until the result is something other than STILL_RUNNING.
100 base::TerminationStatus status
= base::TERMINATION_STATUS_STILL_RUNNING
;
101 const base::TimeDelta kInterval
= base::TimeDelta::FromMilliseconds(20);
102 base::TimeDelta waited
;
104 status
= base::GetTerminationStatus(handle
, exit_code
);
105 base::PlatformThread::Sleep(kInterval
);
107 } while (status
== base::TERMINATION_STATUS_STILL_RUNNING
&&
108 // Waiting for more time for process termination on android devices.
109 #if defined(OS_ANDROID)
110 waited
< TestTimeouts::large_test_timeout());
112 waited
< TestTimeouts::action_max_timeout());
120 class ProcessUtilTest
: public base::MultiProcessTest
{
122 #if defined(OS_POSIX)
123 // Spawn a child process that counts how many file descriptors are open.
124 int CountOpenFDsInChild();
126 // Converts the filename to a platform specific filepath.
127 // On Android files can not be created in arbitrary directories.
128 static std::string
GetSignalFilePath(const char* filename
);
131 std::string
ProcessUtilTest::GetSignalFilePath(const char* filename
) {
132 #if !defined(OS_ANDROID)
136 PathService::Get(base::DIR_CACHE
, &tmp_dir
);
137 tmp_dir
= tmp_dir
.Append(filename
);
138 return tmp_dir
.value();
142 MULTIPROCESS_TEST_MAIN(SimpleChildProcess
) {
146 TEST_F(ProcessUtilTest
, SpawnChild
) {
147 base::ProcessHandle handle
= this->SpawnChild("SimpleChildProcess", false);
148 ASSERT_NE(base::kNullProcessHandle
, handle
);
149 EXPECT_TRUE(base::WaitForSingleProcess(
150 handle
, TestTimeouts::action_max_timeout()));
151 base::CloseProcessHandle(handle
);
154 MULTIPROCESS_TEST_MAIN(SlowChildProcess
) {
155 WaitToDie(ProcessUtilTest::GetSignalFilePath(kSignalFileSlow
).c_str());
159 TEST_F(ProcessUtilTest
, KillSlowChild
) {
160 const std::string signal_file
=
161 ProcessUtilTest::GetSignalFilePath(kSignalFileSlow
);
162 remove(signal_file
.c_str());
163 base::ProcessHandle handle
= this->SpawnChild("SlowChildProcess", false);
164 ASSERT_NE(base::kNullProcessHandle
, handle
);
165 SignalChildren(signal_file
.c_str());
166 EXPECT_TRUE(base::WaitForSingleProcess(
167 handle
, TestTimeouts::action_max_timeout()));
168 base::CloseProcessHandle(handle
);
169 remove(signal_file
.c_str());
172 // Times out on Linux and Win, flakes on other platforms, http://crbug.com/95058
173 TEST_F(ProcessUtilTest
, DISABLED_GetTerminationStatusExit
) {
174 const std::string signal_file
=
175 ProcessUtilTest::GetSignalFilePath(kSignalFileSlow
);
176 remove(signal_file
.c_str());
177 base::ProcessHandle handle
= this->SpawnChild("SlowChildProcess", false);
178 ASSERT_NE(base::kNullProcessHandle
, handle
);
181 EXPECT_EQ(base::TERMINATION_STATUS_STILL_RUNNING
,
182 base::GetTerminationStatus(handle
, &exit_code
));
183 EXPECT_EQ(kExpectedStillRunningExitCode
, exit_code
);
185 SignalChildren(signal_file
.c_str());
187 base::TerminationStatus status
=
188 WaitForChildTermination(handle
, &exit_code
);
189 EXPECT_EQ(base::TERMINATION_STATUS_NORMAL_TERMINATION
, status
);
190 EXPECT_EQ(0, exit_code
);
191 base::CloseProcessHandle(handle
);
192 remove(signal_file
.c_str());
196 // TODO(cpu): figure out how to test this in other platforms.
197 TEST_F(ProcessUtilTest
, GetProcId
) {
198 base::ProcessId id1
= base::GetProcId(GetCurrentProcess());
200 base::ProcessHandle handle
= this->SpawnChild("SimpleChildProcess", false);
201 ASSERT_NE(base::kNullProcessHandle
, handle
);
202 base::ProcessId id2
= base::GetProcId(handle
);
205 base::CloseProcessHandle(handle
);
208 TEST_F(ProcessUtilTest
, GetModuleFromAddress
) {
209 // Since the unit tests are their own EXE, this should be
210 // equivalent to the EXE's HINSTANCE.
212 // kExpectedKilledExitCode is a constant in this file and
213 // therefore within the unit test EXE.
214 EXPECT_EQ(::GetModuleHandle(NULL
),
215 base::GetModuleFromAddress(
216 const_cast<int*>(&kExpectedKilledExitCode
)));
218 // Any address within the kernel32 module should return
219 // kernel32's HMODULE. Our only assumption here is that
220 // kernel32 is larger than 4 bytes.
221 HMODULE kernel32
= ::GetModuleHandle(L
"kernel32.dll");
222 HMODULE kernel32_from_address
=
223 base::GetModuleFromAddress(reinterpret_cast<DWORD
*>(kernel32
) + 1);
224 EXPECT_EQ(kernel32
, kernel32_from_address
);
228 #if !defined(OS_MACOSX)
229 // This test is disabled on Mac, since it's flaky due to ReportCrash
230 // taking a variable amount of time to parse and load the debug and
231 // symbol data for this unit test's executable before firing the
234 // TODO(gspencer): turn this test process into a very small program
235 // with no symbols (instead of using the multiprocess testing
236 // framework) to reduce the ReportCrash overhead.
238 MULTIPROCESS_TEST_MAIN(CrashingChildProcess
) {
239 WaitToDie(ProcessUtilTest::GetSignalFilePath(kSignalFileCrash
).c_str());
240 #if defined(OS_POSIX)
241 // Have to disable to signal handler for segv so we can get a crash
242 // instead of an abnormal termination through the crash dump handler.
243 ::signal(SIGSEGV
, SIG_DFL
);
245 // Make this process have a segmentation fault.
246 volatile int* oops
= NULL
;
251 // This test intentionally crashes, so we don't need to run it under
253 #if defined(ADDRESS_SANITIZER)
254 #define MAYBE_GetTerminationStatusCrash DISABLED_GetTerminationStatusCrash
256 #define MAYBE_GetTerminationStatusCrash GetTerminationStatusCrash
258 TEST_F(ProcessUtilTest
, MAYBE_GetTerminationStatusCrash
) {
259 const std::string signal_file
=
260 ProcessUtilTest::GetSignalFilePath(kSignalFileCrash
);
261 remove(signal_file
.c_str());
262 base::ProcessHandle handle
= this->SpawnChild("CrashingChildProcess",
264 ASSERT_NE(base::kNullProcessHandle
, handle
);
267 EXPECT_EQ(base::TERMINATION_STATUS_STILL_RUNNING
,
268 base::GetTerminationStatus(handle
, &exit_code
));
269 EXPECT_EQ(kExpectedStillRunningExitCode
, exit_code
);
271 SignalChildren(signal_file
.c_str());
273 base::TerminationStatus status
=
274 WaitForChildTermination(handle
, &exit_code
);
275 EXPECT_EQ(base::TERMINATION_STATUS_PROCESS_CRASHED
, status
);
278 EXPECT_EQ(0xc0000005, exit_code
);
279 #elif defined(OS_POSIX)
280 int signaled
= WIFSIGNALED(exit_code
);
281 EXPECT_NE(0, signaled
);
282 int signal
= WTERMSIG(exit_code
);
283 EXPECT_EQ(SIGSEGV
, signal
);
285 base::CloseProcessHandle(handle
);
287 // Reset signal handlers back to "normal".
288 base::debug::EnableInProcessStackDumping();
289 remove(signal_file
.c_str());
291 #endif // !defined(OS_MACOSX)
293 MULTIPROCESS_TEST_MAIN(KilledChildProcess
) {
294 WaitToDie(ProcessUtilTest::GetSignalFilePath(kSignalFileKill
).c_str());
297 HANDLE handle
= ::OpenProcess(PROCESS_ALL_ACCESS
, 0, ::GetCurrentProcessId());
298 ::TerminateProcess(handle
, kExpectedKilledExitCode
);
299 #elif defined(OS_POSIX)
300 // Send a SIGKILL to this process, just like the OOM killer would.
301 ::kill(getpid(), SIGKILL
);
306 TEST_F(ProcessUtilTest
, GetTerminationStatusKill
) {
307 const std::string signal_file
=
308 ProcessUtilTest::GetSignalFilePath(kSignalFileKill
);
309 remove(signal_file
.c_str());
310 base::ProcessHandle handle
= this->SpawnChild("KilledChildProcess",
312 ASSERT_NE(base::kNullProcessHandle
, handle
);
315 EXPECT_EQ(base::TERMINATION_STATUS_STILL_RUNNING
,
316 base::GetTerminationStatus(handle
, &exit_code
));
317 EXPECT_EQ(kExpectedStillRunningExitCode
, exit_code
);
319 SignalChildren(signal_file
.c_str());
321 base::TerminationStatus status
=
322 WaitForChildTermination(handle
, &exit_code
);
323 EXPECT_EQ(base::TERMINATION_STATUS_PROCESS_WAS_KILLED
, status
);
325 EXPECT_EQ(kExpectedKilledExitCode
, exit_code
);
326 #elif defined(OS_POSIX)
327 int signaled
= WIFSIGNALED(exit_code
);
328 EXPECT_NE(0, signaled
);
329 int signal
= WTERMSIG(exit_code
);
330 EXPECT_EQ(SIGKILL
, signal
);
332 base::CloseProcessHandle(handle
);
333 remove(signal_file
.c_str());
336 // Ensure that the priority of a process is restored correctly after
337 // backgrounding and restoring.
338 // Note: a platform may not be willing or able to lower the priority of
339 // a process. The calls to SetProcessBackground should be noops then.
340 TEST_F(ProcessUtilTest
, SetProcessBackgrounded
) {
341 base::ProcessHandle handle
= this->SpawnChild("SimpleChildProcess", false);
342 base::Process
process(handle
);
343 int old_priority
= process
.GetPriority();
345 EXPECT_TRUE(process
.SetProcessBackgrounded(true));
346 EXPECT_TRUE(process
.IsProcessBackgrounded());
347 EXPECT_TRUE(process
.SetProcessBackgrounded(false));
348 EXPECT_FALSE(process
.IsProcessBackgrounded());
350 process
.SetProcessBackgrounded(true);
351 process
.SetProcessBackgrounded(false);
353 int new_priority
= process
.GetPriority();
354 EXPECT_EQ(old_priority
, new_priority
);
357 // Same as SetProcessBackgrounded but to this very process. It uses
358 // a different code path at least for Windows.
359 TEST_F(ProcessUtilTest
, SetProcessBackgroundedSelf
) {
360 base::Process
process(base::Process::Current().handle());
361 int old_priority
= process
.GetPriority();
363 EXPECT_TRUE(process
.SetProcessBackgrounded(true));
364 EXPECT_TRUE(process
.IsProcessBackgrounded());
365 EXPECT_TRUE(process
.SetProcessBackgrounded(false));
366 EXPECT_FALSE(process
.IsProcessBackgrounded());
368 process
.SetProcessBackgrounded(true);
369 process
.SetProcessBackgrounded(false);
371 int new_priority
= process
.GetPriority();
372 EXPECT_EQ(old_priority
, new_priority
);
375 // TODO(estade): if possible, port these 2 tests.
377 TEST_F(ProcessUtilTest
, EnableLFH
) {
378 ASSERT_TRUE(base::EnableLowFragmentationHeap());
379 if (IsDebuggerPresent()) {
380 // Under these conditions, LFH can't be enabled. There's no point to test
382 const char* no_debug_env
= getenv("_NO_DEBUG_HEAP");
383 if (!no_debug_env
|| strcmp(no_debug_env
, "1"))
386 HANDLE heaps
[1024] = { 0 };
387 unsigned number_heaps
= GetProcessHeaps(1024, heaps
);
388 EXPECT_GT(number_heaps
, 0u);
389 for (unsigned i
= 0; i
< number_heaps
; ++i
) {
392 ASSERT_NE(0, HeapQueryInformation(heaps
[i
],
393 HeapCompatibilityInformation
,
397 // If flag is 0, the heap is a standard heap that does not support
398 // look-asides. If flag is 1, the heap supports look-asides. If flag is 2,
399 // the heap is a low-fragmentation heap (LFH). Note that look-asides are not
400 // supported on the LFH.
402 // We don't have any documented way of querying the HEAP_NO_SERIALIZE flag.
408 TEST_F(ProcessUtilTest
, CalcFreeMemory
) {
409 scoped_ptr
<base::ProcessMetrics
> metrics(
410 base::ProcessMetrics::CreateProcessMetrics(::GetCurrentProcess()));
411 ASSERT_TRUE(NULL
!= metrics
.get());
413 // Typical values here is ~1900 for total and ~1000 for largest. Obviously
414 // it depends in what other tests have done to this process.
415 base::FreeMBytes free_mem1
= {0};
416 EXPECT_TRUE(metrics
->CalculateFreeMemory(&free_mem1
));
417 EXPECT_LT(10u, free_mem1
.total
);
418 EXPECT_LT(10u, free_mem1
.largest
);
419 EXPECT_GT(2048u, free_mem1
.total
);
420 EXPECT_GT(2048u, free_mem1
.largest
);
421 EXPECT_GE(free_mem1
.total
, free_mem1
.largest
);
422 EXPECT_TRUE(NULL
!= free_mem1
.largest_ptr
);
424 // Allocate 20M and check again. It should have gone down.
425 const int kAllocMB
= 20;
426 scoped_array
<char> alloc(new char[kAllocMB
* 1024 * 1024]);
427 size_t expected_total
= free_mem1
.total
- kAllocMB
;
428 size_t expected_largest
= free_mem1
.largest
;
430 base::FreeMBytes free_mem2
= {0};
431 EXPECT_TRUE(metrics
->CalculateFreeMemory(&free_mem2
));
432 EXPECT_GE(free_mem2
.total
, free_mem2
.largest
);
433 EXPECT_GE(expected_total
, free_mem2
.total
);
434 EXPECT_GE(expected_largest
, free_mem2
.largest
);
435 EXPECT_TRUE(NULL
!= free_mem2
.largest_ptr
);
438 TEST_F(ProcessUtilTest
, GetAppOutput
) {
439 // Let's create a decently long message.
441 for (int i
= 0; i
< 1025; i
++) { // 1025 so it does not end on a kilo-byte
445 // cmd.exe's echo always adds a \r\n to its output.
446 std::string
expected(message
);
449 FilePath
cmd(L
"cmd.exe");
450 CommandLine
cmd_line(cmd
);
451 cmd_line
.AppendArg("/c");
452 cmd_line
.AppendArg("echo " + message
+ "");
454 ASSERT_TRUE(base::GetAppOutput(cmd_line
, &output
));
455 EXPECT_EQ(expected
, output
);
457 // Let's make sure stderr is ignored.
458 CommandLine
other_cmd_line(cmd
);
459 other_cmd_line
.AppendArg("/c");
460 // http://msdn.microsoft.com/library/cc772622.aspx
461 cmd_line
.AppendArg("echo " + message
+ " >&2");
463 ASSERT_TRUE(base::GetAppOutput(other_cmd_line
, &output
));
464 EXPECT_EQ("", output
);
467 TEST_F(ProcessUtilTest
, LaunchAsUser
) {
468 base::UserTokenHandle token
;
469 ASSERT_TRUE(OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS
, &token
));
470 std::wstring cmdline
=
471 this->MakeCmdLine("SimpleChildProcess", false).GetCommandLineString();
472 base::LaunchOptions options
;
473 options
.as_user
= token
;
474 EXPECT_TRUE(base::LaunchProcess(cmdline
, options
, NULL
));
477 #endif // defined(OS_WIN)
479 #if defined(OS_MACOSX)
481 // For the following Mac tests:
482 // Note that base::EnableTerminationOnHeapCorruption() is called as part of
483 // test suite setup and does not need to be done again, else mach_override
486 #if !defined(ADDRESS_SANITIZER)
487 // The following code tests the system implementation of malloc() thus no need
488 // to test it under AddressSanitizer.
489 TEST_F(ProcessUtilTest
, MacMallocFailureDoesNotTerminate
) {
490 // Install the OOM killer.
491 base::EnableTerminationOnOutOfMemory();
493 // Test that ENOMEM doesn't crash via CrMallocErrorBreak two ways: the exit
494 // code and lack of the error string. The number of bytes is one less than
495 // MALLOC_ABSOLUTE_MAX_SIZE, more than which the system early-returns NULL and
496 // does not call through malloc_error_break(). See the comment at
497 // EnableTerminationOnOutOfMemory() for more information.
500 buf
= malloc(std::numeric_limits
<size_t>::max() - (2 * PAGE_SIZE
) - 1),
501 testing::KilledBySignal(SIGTRAP
),
502 "\\*\\*\\* error: can't allocate region.*"
503 "(Terminating process due to a potential for future heap "
506 base::debug::Alias(buf
);
508 #endif // !defined(ADDRESS_SANITIZER)
510 TEST_F(ProcessUtilTest
, MacTerminateOnHeapCorruption
) {
511 // Assert that freeing an unallocated pointer will crash the process.
513 asm("" : "=r" (buf
)); // Prevent clang from being too smart.
514 #if !defined(ADDRESS_SANITIZER)
515 ASSERT_DEATH(free(buf
), "being freed.*"
516 "\\*\\*\\* set a breakpoint in malloc_error_break to debug.*"
517 "Terminating process due to a potential for future heap corruption");
519 // AddressSanitizer replaces malloc() and prints a different error message on
521 ASSERT_DEATH(free(buf
), "attempting free on address which "
522 "was not malloc\\(\\)-ed");
523 #endif // !defined(ADDRESS_SANITIZER)
526 #endif // defined(OS_MACOSX)
528 #if defined(OS_POSIX)
532 // Returns the maximum number of files that a process can have open.
533 // Returns 0 on error.
534 int GetMaxFilesOpenInProcess() {
536 if (getrlimit(RLIMIT_NOFILE
, &rlim
) != 0) {
540 // rlim_t is a uint64 - clip to maxint. We do this since FD #s are ints
541 // which are all 32 bits on the supported platforms.
542 rlim_t max_int
= static_cast<rlim_t
>(std::numeric_limits
<int32
>::max());
543 if (rlim
.rlim_cur
> max_int
) {
547 return rlim
.rlim_cur
;
550 const int kChildPipe
= 20; // FD # for write end of pipe in child process.
554 MULTIPROCESS_TEST_MAIN(ProcessUtilsLeakFDChildProcess
) {
555 // This child process counts the number of open FDs, it then writes that
556 // number out to a pipe connected to the parent.
557 int num_open_files
= 0;
558 int write_pipe
= kChildPipe
;
559 int max_files
= GetMaxFilesOpenInProcess();
560 for (int i
= STDERR_FILENO
+ 1; i
< max_files
; i
++) {
561 if (i
!= kChildPipe
) {
563 if ((fd
= HANDLE_EINTR(dup(i
))) != -1) {
570 int written
= HANDLE_EINTR(write(write_pipe
, &num_open_files
,
571 sizeof(num_open_files
)));
572 DCHECK_EQ(static_cast<size_t>(written
), sizeof(num_open_files
));
573 int ret
= HANDLE_EINTR(close(write_pipe
));
579 int ProcessUtilTest::CountOpenFDsInChild() {
584 base::FileHandleMappingVector fd_mapping_vec
;
585 fd_mapping_vec
.push_back(std::pair
<int, int>(fds
[1], kChildPipe
));
586 base::ProcessHandle handle
= this->SpawnChild(
587 "ProcessUtilsLeakFDChildProcess", fd_mapping_vec
, false);
589 int ret
= HANDLE_EINTR(close(fds
[1]));
592 // Read number of open files in client process from pipe;
593 int num_open_files
= -1;
595 HANDLE_EINTR(read(fds
[0], &num_open_files
, sizeof(num_open_files
)));
596 CHECK_EQ(bytes_read
, static_cast<ssize_t
>(sizeof(num_open_files
)));
598 #if defined(THREAD_SANITIZER)
599 // Compiler-based ThreadSanitizer makes this test slow.
600 CHECK(base::WaitForSingleProcess(handle
, base::TimeDelta::FromSeconds(3)));
602 CHECK(base::WaitForSingleProcess(handle
, base::TimeDelta::FromSeconds(1)));
604 base::CloseProcessHandle(handle
);
605 ret
= HANDLE_EINTR(close(fds
[0]));
608 return num_open_files
;
611 TEST_F(ProcessUtilTest
, FDRemapping
) {
612 int fds_before
= CountOpenFDsInChild();
614 // open some dummy fds to make sure they don't propagate over to the
616 int dev_null
= open("/dev/null", O_RDONLY
);
618 socketpair(AF_UNIX
, SOCK_STREAM
, 0, sockets
);
620 int fds_after
= CountOpenFDsInChild();
622 ASSERT_EQ(fds_after
, fds_before
);
625 ret
= HANDLE_EINTR(close(sockets
[0]));
627 ret
= HANDLE_EINTR(close(sockets
[1]));
629 ret
= HANDLE_EINTR(close(dev_null
));
635 std::string
TestLaunchProcess(const base::EnvironmentVector
& env_changes
,
636 const int clone_flags
) {
637 std::vector
<std::string
> args
;
638 base::FileHandleMappingVector fds_to_remap
;
640 args
.push_back(kPosixShell
);
641 args
.push_back("-c");
642 args
.push_back("echo $BASE_TEST");
645 PCHECK(pipe(fds
) == 0);
647 fds_to_remap
.push_back(std::make_pair(fds
[1], 1));
648 base::LaunchOptions options
;
650 options
.environ
= &env_changes
;
651 options
.fds_to_remap
= &fds_to_remap
;
652 #if defined(OS_LINUX)
653 options
.clone_flags
= clone_flags
;
655 CHECK_EQ(0, clone_flags
);
657 EXPECT_TRUE(base::LaunchProcess(args
, options
, NULL
));
658 PCHECK(HANDLE_EINTR(close(fds
[1])) == 0);
661 const ssize_t n
= HANDLE_EINTR(read(fds
[0], buf
, sizeof(buf
)));
664 PCHECK(HANDLE_EINTR(close(fds
[0])) == 0);
666 return std::string(buf
, n
);
669 const char kLargeString
[] =
670 "0123456789012345678901234567890123456789012345678901234567890123456789"
671 "0123456789012345678901234567890123456789012345678901234567890123456789"
672 "0123456789012345678901234567890123456789012345678901234567890123456789"
673 "0123456789012345678901234567890123456789012345678901234567890123456789"
674 "0123456789012345678901234567890123456789012345678901234567890123456789"
675 "0123456789012345678901234567890123456789012345678901234567890123456789"
676 "0123456789012345678901234567890123456789012345678901234567890123456789";
680 TEST_F(ProcessUtilTest
, LaunchProcess
) {
681 base::EnvironmentVector env_changes
;
682 const int no_clone_flags
= 0;
684 env_changes
.push_back(std::make_pair(std::string("BASE_TEST"),
685 std::string("bar")));
686 EXPECT_EQ("bar\n", TestLaunchProcess(env_changes
, no_clone_flags
));
689 EXPECT_EQ(0, setenv("BASE_TEST", "testing", 1 /* override */));
690 EXPECT_EQ("testing\n", TestLaunchProcess(env_changes
, no_clone_flags
));
692 env_changes
.push_back(std::make_pair(std::string("BASE_TEST"),
694 EXPECT_EQ("\n", TestLaunchProcess(env_changes
, no_clone_flags
));
696 env_changes
[0].second
= "foo";
697 EXPECT_EQ("foo\n", TestLaunchProcess(env_changes
, no_clone_flags
));
700 EXPECT_EQ(0, setenv("BASE_TEST", kLargeString
, 1 /* override */));
701 EXPECT_EQ(std::string(kLargeString
) + "\n",
702 TestLaunchProcess(env_changes
, no_clone_flags
));
704 env_changes
.push_back(std::make_pair(std::string("BASE_TEST"),
705 std::string("wibble")));
706 EXPECT_EQ("wibble\n", TestLaunchProcess(env_changes
, no_clone_flags
));
708 #if defined(OS_LINUX)
709 // Test a non-trival value for clone_flags.
710 // Don't test on Valgrind as it has limited support for clone().
711 if (!RunningOnValgrind()) {
712 EXPECT_EQ("wibble\n", TestLaunchProcess(env_changes
, CLONE_FS
| SIGCHLD
));
717 TEST_F(ProcessUtilTest
, AlterEnvironment
) {
718 const char* const empty
[] = { NULL
};
719 const char* const a2
[] = { "A=2", NULL
};
720 base::EnvironmentVector changes
;
723 e
= base::AlterEnvironment(changes
, empty
);
724 EXPECT_TRUE(e
[0] == NULL
);
727 changes
.push_back(std::make_pair(std::string("A"), std::string("1")));
728 e
= base::AlterEnvironment(changes
, empty
);
729 EXPECT_EQ(std::string("A=1"), e
[0]);
730 EXPECT_TRUE(e
[1] == NULL
);
734 changes
.push_back(std::make_pair(std::string("A"), std::string("")));
735 e
= base::AlterEnvironment(changes
, empty
);
736 EXPECT_TRUE(e
[0] == NULL
);
740 e
= base::AlterEnvironment(changes
, a2
);
741 EXPECT_EQ(std::string("A=2"), e
[0]);
742 EXPECT_TRUE(e
[1] == NULL
);
746 changes
.push_back(std::make_pair(std::string("A"), std::string("1")));
747 e
= base::AlterEnvironment(changes
, a2
);
748 EXPECT_EQ(std::string("A=1"), e
[0]);
749 EXPECT_TRUE(e
[1] == NULL
);
753 changes
.push_back(std::make_pair(std::string("A"), std::string("")));
754 e
= base::AlterEnvironment(changes
, a2
);
755 EXPECT_TRUE(e
[0] == NULL
);
759 TEST_F(ProcessUtilTest
, GetAppOutput
) {
762 #if defined(OS_ANDROID)
763 std::vector
<std::string
> argv
;
764 argv
.push_back("sh"); // Instead of /bin/sh, force path search to find it.
765 argv
.push_back("-c");
767 argv
.push_back("exit 0");
768 EXPECT_TRUE(base::GetAppOutput(CommandLine(argv
), &output
));
769 EXPECT_STREQ("", output
.c_str());
772 EXPECT_FALSE(base::GetAppOutput(CommandLine(argv
), &output
));
773 EXPECT_STREQ("", output
.c_str());
775 argv
[2] = "echo foobar42";
776 EXPECT_TRUE(base::GetAppOutput(CommandLine(argv
), &output
));
777 EXPECT_STREQ("foobar42\n", output
.c_str());
779 EXPECT_TRUE(base::GetAppOutput(CommandLine(FilePath("true")), &output
));
780 EXPECT_STREQ("", output
.c_str());
782 EXPECT_FALSE(base::GetAppOutput(CommandLine(FilePath("false")), &output
));
784 std::vector
<std::string
> argv
;
785 argv
.push_back("/bin/echo");
786 argv
.push_back("-n");
787 argv
.push_back("foobar42");
788 EXPECT_TRUE(base::GetAppOutput(CommandLine(argv
), &output
));
789 EXPECT_STREQ("foobar42", output
.c_str());
790 #endif // defined(OS_ANDROID)
793 TEST_F(ProcessUtilTest
, GetAppOutputRestricted
) {
794 // Unfortunately, since we can't rely on the path, we need to know where
795 // everything is. So let's use /bin/sh, which is on every POSIX system, and
797 std::vector
<std::string
> argv
;
798 argv
.push_back(std::string(kShellPath
)); // argv[0]
799 argv
.push_back("-c"); // argv[1]
801 // On success, should set |output|. We use |/bin/sh -c 'exit 0'| instead of
802 // |true| since the location of the latter may be |/bin| or |/usr/bin| (and we
803 // need absolute paths).
804 argv
.push_back("exit 0"); // argv[2]; equivalent to "true"
805 std::string output
= "abc";
806 EXPECT_TRUE(base::GetAppOutputRestricted(CommandLine(argv
), &output
, 100));
807 EXPECT_STREQ("", output
.c_str());
809 argv
[2] = "exit 1"; // equivalent to "false"
811 EXPECT_FALSE(base::GetAppOutputRestricted(CommandLine(argv
),
813 EXPECT_STREQ("", output
.c_str());
815 // Amount of output exactly equal to space allowed.
816 argv
[2] = "echo 123456789"; // (the sh built-in doesn't take "-n")
818 EXPECT_TRUE(base::GetAppOutputRestricted(CommandLine(argv
), &output
, 10));
819 EXPECT_STREQ("123456789\n", output
.c_str());
821 // Amount of output greater than space allowed.
823 EXPECT_TRUE(base::GetAppOutputRestricted(CommandLine(argv
), &output
, 5));
824 EXPECT_STREQ("12345", output
.c_str());
826 // Amount of output less than space allowed.
828 EXPECT_TRUE(base::GetAppOutputRestricted(CommandLine(argv
), &output
, 15));
829 EXPECT_STREQ("123456789\n", output
.c_str());
831 // Zero space allowed.
833 EXPECT_TRUE(base::GetAppOutputRestricted(CommandLine(argv
), &output
, 0));
834 EXPECT_STREQ("", output
.c_str());
837 #if !defined(OS_MACOSX) && !defined(OS_OPENBSD)
838 // TODO(benwells): GetAppOutputRestricted should terminate applications
839 // with SIGPIPE when we have enough output. http://crbug.com/88502
840 TEST_F(ProcessUtilTest
, GetAppOutputRestrictedSIGPIPE
) {
841 std::vector
<std::string
> argv
;
844 argv
.push_back(std::string(kShellPath
)); // argv[0]
845 argv
.push_back("-c");
846 #if defined(OS_ANDROID)
847 argv
.push_back("while echo 12345678901234567890; do :; done");
848 EXPECT_TRUE(base::GetAppOutputRestricted(CommandLine(argv
), &output
, 10));
849 EXPECT_STREQ("1234567890", output
.c_str());
851 argv
.push_back("yes");
852 EXPECT_TRUE(base::GetAppOutputRestricted(CommandLine(argv
), &output
, 10));
853 EXPECT_STREQ("y\ny\ny\ny\ny\n", output
.c_str());
858 TEST_F(ProcessUtilTest
, GetAppOutputRestrictedNoZombies
) {
859 std::vector
<std::string
> argv
;
861 argv
.push_back(std::string(kShellPath
)); // argv[0]
862 argv
.push_back("-c"); // argv[1]
863 argv
.push_back("echo 123456789012345678901234567890"); // argv[2]
865 // Run |GetAppOutputRestricted()| 300 (> default per-user processes on Mac OS
866 // 10.5) times with an output buffer big enough to capture all output.
867 for (int i
= 0; i
< 300; i
++) {
869 EXPECT_TRUE(base::GetAppOutputRestricted(CommandLine(argv
), &output
, 100));
870 EXPECT_STREQ("123456789012345678901234567890\n", output
.c_str());
873 // Ditto, but with an output buffer too small to capture all output.
874 for (int i
= 0; i
< 300; i
++) {
876 EXPECT_TRUE(base::GetAppOutputRestricted(CommandLine(argv
), &output
, 10));
877 EXPECT_STREQ("1234567890", output
.c_str());
881 TEST_F(ProcessUtilTest
, GetAppOutputWithExitCode
) {
882 // Test getting output from a successful application.
883 std::vector
<std::string
> argv
;
886 argv
.push_back(std::string(kShellPath
)); // argv[0]
887 argv
.push_back("-c"); // argv[1]
888 argv
.push_back("echo foo"); // argv[2];
889 EXPECT_TRUE(base::GetAppOutputWithExitCode(CommandLine(argv
), &output
,
891 EXPECT_STREQ("foo\n", output
.c_str());
892 EXPECT_EQ(exit_code
, 0);
894 // Test getting output from an application which fails with a specific exit
897 argv
[2] = "echo foo; exit 2";
898 EXPECT_TRUE(base::GetAppOutputWithExitCode(CommandLine(argv
), &output
,
900 EXPECT_STREQ("foo\n", output
.c_str());
901 EXPECT_EQ(exit_code
, 2);
904 TEST_F(ProcessUtilTest
, GetParentProcessId
) {
905 base::ProcessId ppid
= base::GetParentProcessId(base::GetCurrentProcId());
906 EXPECT_EQ(ppid
, getppid());
909 #if defined(OS_LINUX) || defined(OS_ANDROID)
910 TEST_F(ProcessUtilTest
, ParseProcStatCPU
) {
911 // /proc/self/stat for a process running "top".
912 const char kTopStat
[] = "960 (top) S 16230 960 16230 34818 960 "
914 "12 16 0 0 " // <- These are the goods.
915 "20 0 1 0 121946157 15077376 314 18446744073709551615 4194304 "
916 "4246868 140733983044336 18446744073709551615 140244213071219 "
917 "0 0 0 138047495 0 0 0 17 1 0 0 0 0 0";
918 EXPECT_EQ(12 + 16, base::ParseProcStatCPU(kTopStat
));
920 // cat /proc/self/stat on a random other machine I have.
921 const char kSelfStat
[] = "5364 (cat) R 5354 5364 5354 34819 5364 "
923 "0 0 0 0 " // <- No CPU, apparently.
924 "16 0 1 0 1676099790 2957312 114 4294967295 134512640 134528148 "
925 "3221224832 3221224344 3086339742 0 0 0 0 0 0 0 17 0 0 0";
927 EXPECT_EQ(0, base::ParseProcStatCPU(kSelfStat
));
929 #endif // defined(OS_LINUX) || defined(OS_ANDROID)
931 // TODO(port): port those unit tests.
932 bool IsProcessDead(base::ProcessHandle child
) {
933 // waitpid() will actually reap the process which is exactly NOT what we
934 // want to test for. The good thing is that if it can't find the process
935 // we'll get a nice value for errno which we can test for.
936 const pid_t result
= HANDLE_EINTR(waitpid(child
, NULL
, WNOHANG
));
937 return result
== -1 && errno
== ECHILD
;
940 TEST_F(ProcessUtilTest
, DelayedTermination
) {
941 base::ProcessHandle child_process
=
942 SpawnChild("process_util_test_never_die", false);
943 ASSERT_TRUE(child_process
);
944 base::EnsureProcessTerminated(child_process
);
945 base::WaitForSingleProcess(child_process
, base::TimeDelta::FromSeconds(5));
947 // Check that process was really killed.
948 EXPECT_TRUE(IsProcessDead(child_process
));
949 base::CloseProcessHandle(child_process
);
952 MULTIPROCESS_TEST_MAIN(process_util_test_never_die
) {
959 TEST_F(ProcessUtilTest
, ImmediateTermination
) {
960 base::ProcessHandle child_process
=
961 SpawnChild("process_util_test_die_immediately", false);
962 ASSERT_TRUE(child_process
);
963 // Give it time to die.
965 base::EnsureProcessTerminated(child_process
);
967 // Check that process was really killed.
968 EXPECT_TRUE(IsProcessDead(child_process
));
969 base::CloseProcessHandle(child_process
);
972 MULTIPROCESS_TEST_MAIN(process_util_test_die_immediately
) {
976 #endif // defined(OS_POSIX)
978 // Android doesn't implement set_new_handler, so we can't use the
979 // OutOfMemoryTest cases.
980 // OpenBSD does not support these tests either.
981 // AddressSanitizer defines the malloc()/free()/etc. functions so that they
982 // don't crash if the program is out of memory, so the OOM tests aren't supposed
984 // TODO(vandebo) make this work on Windows too.
985 #if !defined(OS_ANDROID) && !defined(OS_OPENBSD) && \
986 !defined(OS_WIN) && !defined(ADDRESS_SANITIZER)
988 #if defined(USE_TCMALLOC)
990 int tc_set_new_mode(int mode
);
992 #endif // defined(USE_TCMALLOC)
994 class OutOfMemoryDeathTest
: public testing::Test
{
996 OutOfMemoryDeathTest()
998 // Make test size as large as possible minus a few pages so
999 // that alignment or other rounding doesn't make it wrap.
1000 test_size_(std::numeric_limits
<std::size_t>::max() - 12 * 1024),
1001 signed_test_size_(std::numeric_limits
<ssize_t
>::max()) {
1004 #if defined(USE_TCMALLOC)
1005 virtual void SetUp() OVERRIDE
{
1009 virtual void TearDown() OVERRIDE
{
1012 #endif // defined(USE_TCMALLOC)
1014 void SetUpInDeathAssert() {
1015 // Must call EnableTerminationOnOutOfMemory() because that is called from
1016 // chrome's main function and therefore hasn't been called yet.
1017 // Since this call may result in another thread being created and death
1018 // tests shouldn't be started in a multithread environment, this call
1019 // should be done inside of the ASSERT_DEATH.
1020 base::EnableTerminationOnOutOfMemory();
1025 ssize_t signed_test_size_
;
1028 TEST_F(OutOfMemoryDeathTest
, New
) {
1030 SetUpInDeathAssert();
1031 value_
= operator new(test_size_
);
1035 TEST_F(OutOfMemoryDeathTest
, NewArray
) {
1037 SetUpInDeathAssert();
1038 value_
= new char[test_size_
];
1042 TEST_F(OutOfMemoryDeathTest
, Malloc
) {
1044 SetUpInDeathAssert();
1045 value_
= malloc(test_size_
);
1049 TEST_F(OutOfMemoryDeathTest
, Realloc
) {
1051 SetUpInDeathAssert();
1052 value_
= realloc(NULL
, test_size_
);
1056 TEST_F(OutOfMemoryDeathTest
, Calloc
) {
1058 SetUpInDeathAssert();
1059 value_
= calloc(1024, test_size_
/ 1024L);
1063 TEST_F(OutOfMemoryDeathTest
, Valloc
) {
1065 SetUpInDeathAssert();
1066 value_
= valloc(test_size_
);
1070 #if defined(OS_LINUX)
1071 TEST_F(OutOfMemoryDeathTest
, Pvalloc
) {
1073 SetUpInDeathAssert();
1074 value_
= pvalloc(test_size_
);
1078 TEST_F(OutOfMemoryDeathTest
, Memalign
) {
1080 SetUpInDeathAssert();
1081 value_
= memalign(4, test_size_
);
1085 TEST_F(OutOfMemoryDeathTest
, ViaSharedLibraries
) {
1086 // g_try_malloc is documented to return NULL on failure. (g_malloc is the
1087 // 'safe' default that crashes if allocation fails). However, since we have
1088 // hopefully overridden malloc, even g_try_malloc should fail. This tests
1089 // that the run-time symbol resolution is overriding malloc for shared
1090 // libraries as well as for our code.
1092 SetUpInDeathAssert();
1093 value_
= g_try_malloc(test_size_
);
1098 // Android doesn't implement posix_memalign().
1099 #if defined(OS_POSIX) && !defined(OS_ANDROID)
1100 TEST_F(OutOfMemoryDeathTest
, Posix_memalign
) {
1101 // Grab the return value of posix_memalign to silence a compiler warning
1102 // about unused return values. We don't actually care about the return
1103 // value, since we're asserting death.
1105 SetUpInDeathAssert();
1106 EXPECT_EQ(ENOMEM
, posix_memalign(&value_
, 8, test_size_
));
1109 #endif // defined(OS_POSIX) && !defined(OS_ANDROID)
1111 #if defined(OS_MACOSX)
1113 // Purgeable zone tests
1115 TEST_F(OutOfMemoryDeathTest
, MallocPurgeable
) {
1116 malloc_zone_t
* zone
= malloc_default_purgeable_zone();
1118 SetUpInDeathAssert();
1119 value_
= malloc_zone_malloc(zone
, test_size_
);
1123 TEST_F(OutOfMemoryDeathTest
, ReallocPurgeable
) {
1124 malloc_zone_t
* zone
= malloc_default_purgeable_zone();
1126 SetUpInDeathAssert();
1127 value_
= malloc_zone_realloc(zone
, NULL
, test_size_
);
1131 TEST_F(OutOfMemoryDeathTest
, CallocPurgeable
) {
1132 malloc_zone_t
* zone
= malloc_default_purgeable_zone();
1134 SetUpInDeathAssert();
1135 value_
= malloc_zone_calloc(zone
, 1024, test_size_
/ 1024L);
1139 TEST_F(OutOfMemoryDeathTest
, VallocPurgeable
) {
1140 malloc_zone_t
* zone
= malloc_default_purgeable_zone();
1142 SetUpInDeathAssert();
1143 value_
= malloc_zone_valloc(zone
, test_size_
);
1147 TEST_F(OutOfMemoryDeathTest
, PosixMemalignPurgeable
) {
1148 malloc_zone_t
* zone
= malloc_default_purgeable_zone();
1150 SetUpInDeathAssert();
1151 value_
= malloc_zone_memalign(zone
, 8, test_size_
);
1155 // Since these allocation functions take a signed size, it's possible that
1156 // calling them just once won't be enough to exhaust memory. In the 32-bit
1157 // environment, it's likely that these allocation attempts will fail because
1158 // not enough contiguous address space is available. In the 64-bit environment,
1159 // it's likely that they'll fail because they would require a preposterous
1160 // amount of (virtual) memory.
1162 TEST_F(OutOfMemoryDeathTest
, CFAllocatorSystemDefault
) {
1164 SetUpInDeathAssert();
1166 base::AllocateViaCFAllocatorSystemDefault(signed_test_size_
))) {}
1170 TEST_F(OutOfMemoryDeathTest
, CFAllocatorMalloc
) {
1172 SetUpInDeathAssert();
1174 base::AllocateViaCFAllocatorMalloc(signed_test_size_
))) {}
1178 TEST_F(OutOfMemoryDeathTest
, CFAllocatorMallocZone
) {
1180 SetUpInDeathAssert();
1182 base::AllocateViaCFAllocatorMallocZone(signed_test_size_
))) {}
1186 #if !defined(ARCH_CPU_64_BITS)
1188 // See process_util_unittest_mac.mm for an explanation of why this test isn't
1189 // run in the 64-bit environment.
1191 TEST_F(OutOfMemoryDeathTest
, PsychoticallyBigObjCObject
) {
1193 SetUpInDeathAssert();
1194 while ((value_
= base::AllocatePsychoticallyBigObjCObject())) {}
1198 #endif // !ARCH_CPU_64_BITS
1201 #endif // !defined(OS_ANDROID) && !defined(OS_OPENBSD) &&
1202 // !defined(OS_WIN) && !defined(ADDRESS_SANITIZER)