Record error when CreateDir fails.
[chromium-blink-merge.git] / base / process_util_unittest.cc
blobd3a4100611a2a1eb6f7fd18b858546994077d197
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #define _CRT_SECURE_NO_WARNINGS
7 #include <limits>
9 #include "base/command_line.h"
10 #include "base/debug/alias.h"
11 #include "base/debug/stack_trace.h"
12 #include "base/files/file_path.h"
13 #include "base/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/strings/utf_string_conversions.h"
19 #include "base/test/multiprocess_test.h"
20 #include "base/test/test_timeouts.h"
21 #include "base/third_party/dynamic_annotations/dynamic_annotations.h"
22 #include "base/threading/platform_thread.h"
23 #include "base/threading/thread.h"
24 #include "testing/gtest/include/gtest/gtest.h"
25 #include "testing/multiprocess_func_list.h"
27 #if defined(OS_LINUX)
28 #include <glib.h>
29 #include <malloc.h>
30 #include <sched.h>
31 #endif
32 #if defined(OS_POSIX)
33 #include <dlfcn.h>
34 #include <errno.h>
35 #include <fcntl.h>
36 #include <signal.h>
37 #include <sys/resource.h>
38 #include <sys/socket.h>
39 #include <sys/wait.h>
40 #endif
41 #if defined(OS_WIN)
42 #include <windows.h>
43 #endif
44 #if defined(OS_MACOSX)
45 #include <mach/vm_param.h>
46 #include <malloc/malloc.h>
47 #include "base/process_util_unittest_mac.h"
48 #endif
50 using base::FilePath;
52 namespace {
54 #if defined(OS_WIN)
55 const wchar_t kProcessName[] = L"base_unittests.exe";
56 #else
57 const wchar_t kProcessName[] = L"base_unittests";
58 #endif // defined(OS_WIN)
60 #if defined(OS_ANDROID)
61 const char kShellPath[] = "/system/bin/sh";
62 const char kPosixShell[] = "sh";
63 #else
64 const char kShellPath[] = "/bin/sh";
65 const char kPosixShell[] = "bash";
66 #endif
68 const char kSignalFileSlow[] = "SlowChildProcess.die";
69 const char kSignalFileCrash[] = "CrashingChildProcess.die";
70 const char kSignalFileKill[] = "KilledChildProcess.die";
72 #if defined(OS_WIN)
73 const int kExpectedStillRunningExitCode = 0x102;
74 const int kExpectedKilledExitCode = 1;
75 #else
76 const int kExpectedStillRunningExitCode = 0;
77 #endif
79 #if defined(OS_WIN)
80 // HeapQueryInformation function pointer.
81 typedef BOOL (WINAPI* HeapQueryFn) \
82 (HANDLE, HEAP_INFORMATION_CLASS, PVOID, SIZE_T, PSIZE_T);
83 #endif
85 // Sleeps until file filename is created.
86 void WaitToDie(const char* filename) {
87 FILE* fp;
88 do {
89 base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(10));
90 fp = fopen(filename, "r");
91 } while (!fp);
92 fclose(fp);
95 // Signals children they should die now.
96 void SignalChildren(const char* filename) {
97 FILE* fp = fopen(filename, "w");
98 fclose(fp);
101 // Using a pipe to the child to wait for an event was considered, but
102 // there were cases in the past where pipes caused problems (other
103 // libraries closing the fds, child deadlocking). This is a simple
104 // case, so it's not worth the risk. Using wait loops is discouraged
105 // in most instances.
106 base::TerminationStatus WaitForChildTermination(base::ProcessHandle handle,
107 int* exit_code) {
108 // Now we wait until the result is something other than STILL_RUNNING.
109 base::TerminationStatus status = base::TERMINATION_STATUS_STILL_RUNNING;
110 const base::TimeDelta kInterval = base::TimeDelta::FromMilliseconds(20);
111 base::TimeDelta waited;
112 do {
113 status = base::GetTerminationStatus(handle, exit_code);
114 base::PlatformThread::Sleep(kInterval);
115 waited += kInterval;
116 } while (status == base::TERMINATION_STATUS_STILL_RUNNING &&
117 // Waiting for more time for process termination on android devices.
118 #if defined(OS_ANDROID)
119 waited < TestTimeouts::large_test_timeout());
120 #else
121 waited < TestTimeouts::action_max_timeout());
122 #endif
124 return status;
127 } // namespace
129 class ProcessUtilTest : public base::MultiProcessTest {
130 public:
131 #if defined(OS_POSIX)
132 // Spawn a child process that counts how many file descriptors are open.
133 int CountOpenFDsInChild();
134 #endif
135 // Converts the filename to a platform specific filepath.
136 // On Android files can not be created in arbitrary directories.
137 static std::string GetSignalFilePath(const char* filename);
140 std::string ProcessUtilTest::GetSignalFilePath(const char* filename) {
141 #if !defined(OS_ANDROID)
142 return filename;
143 #else
144 FilePath tmp_dir;
145 PathService::Get(base::DIR_CACHE, &tmp_dir);
146 tmp_dir = tmp_dir.Append(filename);
147 return tmp_dir.value();
148 #endif
151 MULTIPROCESS_TEST_MAIN(SimpleChildProcess) {
152 return 0;
155 TEST_F(ProcessUtilTest, SpawnChild) {
156 base::ProcessHandle handle = this->SpawnChild("SimpleChildProcess", false);
157 ASSERT_NE(base::kNullProcessHandle, handle);
158 EXPECT_TRUE(base::WaitForSingleProcess(
159 handle, TestTimeouts::action_max_timeout()));
160 base::CloseProcessHandle(handle);
163 MULTIPROCESS_TEST_MAIN(SlowChildProcess) {
164 WaitToDie(ProcessUtilTest::GetSignalFilePath(kSignalFileSlow).c_str());
165 return 0;
168 TEST_F(ProcessUtilTest, KillSlowChild) {
169 const std::string signal_file =
170 ProcessUtilTest::GetSignalFilePath(kSignalFileSlow);
171 remove(signal_file.c_str());
172 base::ProcessHandle handle = this->SpawnChild("SlowChildProcess", false);
173 ASSERT_NE(base::kNullProcessHandle, handle);
174 SignalChildren(signal_file.c_str());
175 EXPECT_TRUE(base::WaitForSingleProcess(
176 handle, TestTimeouts::action_max_timeout()));
177 base::CloseProcessHandle(handle);
178 remove(signal_file.c_str());
181 // Times out on Linux and Win, flakes on other platforms, http://crbug.com/95058
182 TEST_F(ProcessUtilTest, DISABLED_GetTerminationStatusExit) {
183 const std::string signal_file =
184 ProcessUtilTest::GetSignalFilePath(kSignalFileSlow);
185 remove(signal_file.c_str());
186 base::ProcessHandle handle = this->SpawnChild("SlowChildProcess", false);
187 ASSERT_NE(base::kNullProcessHandle, handle);
189 int exit_code = 42;
190 EXPECT_EQ(base::TERMINATION_STATUS_STILL_RUNNING,
191 base::GetTerminationStatus(handle, &exit_code));
192 EXPECT_EQ(kExpectedStillRunningExitCode, exit_code);
194 SignalChildren(signal_file.c_str());
195 exit_code = 42;
196 base::TerminationStatus status =
197 WaitForChildTermination(handle, &exit_code);
198 EXPECT_EQ(base::TERMINATION_STATUS_NORMAL_TERMINATION, status);
199 EXPECT_EQ(0, exit_code);
200 base::CloseProcessHandle(handle);
201 remove(signal_file.c_str());
204 #if defined(OS_WIN)
205 // TODO(cpu): figure out how to test this in other platforms.
206 TEST_F(ProcessUtilTest, GetProcId) {
207 base::ProcessId id1 = base::GetProcId(GetCurrentProcess());
208 EXPECT_NE(0ul, id1);
209 base::ProcessHandle handle = this->SpawnChild("SimpleChildProcess", false);
210 ASSERT_NE(base::kNullProcessHandle, handle);
211 base::ProcessId id2 = base::GetProcId(handle);
212 EXPECT_NE(0ul, id2);
213 EXPECT_NE(id1, id2);
214 base::CloseProcessHandle(handle);
217 TEST_F(ProcessUtilTest, GetModuleFromAddress) {
218 // Since the unit tests are their own EXE, this should be
219 // equivalent to the EXE's HINSTANCE.
221 // kExpectedKilledExitCode is a constant in this file and
222 // therefore within the unit test EXE.
223 EXPECT_EQ(::GetModuleHandle(NULL),
224 base::GetModuleFromAddress(
225 const_cast<int*>(&kExpectedKilledExitCode)));
227 // Any address within the kernel32 module should return
228 // kernel32's HMODULE. Our only assumption here is that
229 // kernel32 is larger than 4 bytes.
230 HMODULE kernel32 = ::GetModuleHandle(L"kernel32.dll");
231 HMODULE kernel32_from_address =
232 base::GetModuleFromAddress(reinterpret_cast<DWORD*>(kernel32) + 1);
233 EXPECT_EQ(kernel32, kernel32_from_address);
235 #endif
237 #if !defined(OS_MACOSX)
238 // This test is disabled on Mac, since it's flaky due to ReportCrash
239 // taking a variable amount of time to parse and load the debug and
240 // symbol data for this unit test's executable before firing the
241 // signal handler.
243 // TODO(gspencer): turn this test process into a very small program
244 // with no symbols (instead of using the multiprocess testing
245 // framework) to reduce the ReportCrash overhead.
247 MULTIPROCESS_TEST_MAIN(CrashingChildProcess) {
248 WaitToDie(ProcessUtilTest::GetSignalFilePath(kSignalFileCrash).c_str());
249 #if defined(OS_POSIX)
250 // Have to disable to signal handler for segv so we can get a crash
251 // instead of an abnormal termination through the crash dump handler.
252 ::signal(SIGSEGV, SIG_DFL);
253 #endif
254 // Make this process have a segmentation fault.
255 volatile int* oops = NULL;
256 *oops = 0xDEAD;
257 return 1;
260 // This test intentionally crashes, so we don't need to run it under
261 // AddressSanitizer.
262 // TODO(jschuh): crbug.com/175753 Fix this in Win64 bots.
263 #if defined(ADDRESS_SANITIZER) || (defined(OS_WIN) && defined(ARCH_CPU_X86_64))
264 #define MAYBE_GetTerminationStatusCrash DISABLED_GetTerminationStatusCrash
265 #else
266 #define MAYBE_GetTerminationStatusCrash GetTerminationStatusCrash
267 #endif
268 TEST_F(ProcessUtilTest, MAYBE_GetTerminationStatusCrash) {
269 const std::string signal_file =
270 ProcessUtilTest::GetSignalFilePath(kSignalFileCrash);
271 remove(signal_file.c_str());
272 base::ProcessHandle handle = this->SpawnChild("CrashingChildProcess",
273 false);
274 ASSERT_NE(base::kNullProcessHandle, handle);
276 int exit_code = 42;
277 EXPECT_EQ(base::TERMINATION_STATUS_STILL_RUNNING,
278 base::GetTerminationStatus(handle, &exit_code));
279 EXPECT_EQ(kExpectedStillRunningExitCode, exit_code);
281 SignalChildren(signal_file.c_str());
282 exit_code = 42;
283 base::TerminationStatus status =
284 WaitForChildTermination(handle, &exit_code);
285 EXPECT_EQ(base::TERMINATION_STATUS_PROCESS_CRASHED, status);
287 #if defined(OS_WIN)
288 EXPECT_EQ(0xc0000005, exit_code);
289 #elif defined(OS_POSIX)
290 int signaled = WIFSIGNALED(exit_code);
291 EXPECT_NE(0, signaled);
292 int signal = WTERMSIG(exit_code);
293 EXPECT_EQ(SIGSEGV, signal);
294 #endif
295 base::CloseProcessHandle(handle);
297 // Reset signal handlers back to "normal".
298 base::debug::EnableInProcessStackDumping();
299 remove(signal_file.c_str());
301 #endif // !defined(OS_MACOSX)
303 MULTIPROCESS_TEST_MAIN(KilledChildProcess) {
304 WaitToDie(ProcessUtilTest::GetSignalFilePath(kSignalFileKill).c_str());
305 #if defined(OS_WIN)
306 // Kill ourselves.
307 HANDLE handle = ::OpenProcess(PROCESS_ALL_ACCESS, 0, ::GetCurrentProcessId());
308 ::TerminateProcess(handle, kExpectedKilledExitCode);
309 #elif defined(OS_POSIX)
310 // Send a SIGKILL to this process, just like the OOM killer would.
311 ::kill(getpid(), SIGKILL);
312 #endif
313 return 1;
316 TEST_F(ProcessUtilTest, GetTerminationStatusKill) {
317 const std::string signal_file =
318 ProcessUtilTest::GetSignalFilePath(kSignalFileKill);
319 remove(signal_file.c_str());
320 base::ProcessHandle handle = this->SpawnChild("KilledChildProcess",
321 false);
322 ASSERT_NE(base::kNullProcessHandle, handle);
324 int exit_code = 42;
325 EXPECT_EQ(base::TERMINATION_STATUS_STILL_RUNNING,
326 base::GetTerminationStatus(handle, &exit_code));
327 EXPECT_EQ(kExpectedStillRunningExitCode, exit_code);
329 SignalChildren(signal_file.c_str());
330 exit_code = 42;
331 base::TerminationStatus status =
332 WaitForChildTermination(handle, &exit_code);
333 EXPECT_EQ(base::TERMINATION_STATUS_PROCESS_WAS_KILLED, status);
334 #if defined(OS_WIN)
335 EXPECT_EQ(kExpectedKilledExitCode, exit_code);
336 #elif defined(OS_POSIX)
337 int signaled = WIFSIGNALED(exit_code);
338 EXPECT_NE(0, signaled);
339 int signal = WTERMSIG(exit_code);
340 EXPECT_EQ(SIGKILL, signal);
341 #endif
342 base::CloseProcessHandle(handle);
343 remove(signal_file.c_str());
346 // Ensure that the priority of a process is restored correctly after
347 // backgrounding and restoring.
348 // Note: a platform may not be willing or able to lower the priority of
349 // a process. The calls to SetProcessBackground should be noops then.
350 TEST_F(ProcessUtilTest, SetProcessBackgrounded) {
351 base::ProcessHandle handle = this->SpawnChild("SimpleChildProcess", false);
352 base::Process process(handle);
353 int old_priority = process.GetPriority();
354 #if defined(OS_WIN)
355 EXPECT_TRUE(process.SetProcessBackgrounded(true));
356 EXPECT_TRUE(process.IsProcessBackgrounded());
357 EXPECT_TRUE(process.SetProcessBackgrounded(false));
358 EXPECT_FALSE(process.IsProcessBackgrounded());
359 #else
360 process.SetProcessBackgrounded(true);
361 process.SetProcessBackgrounded(false);
362 #endif
363 int new_priority = process.GetPriority();
364 EXPECT_EQ(old_priority, new_priority);
367 // Same as SetProcessBackgrounded but to this very process. It uses
368 // a different code path at least for Windows.
369 TEST_F(ProcessUtilTest, SetProcessBackgroundedSelf) {
370 base::Process process(base::Process::Current().handle());
371 int old_priority = process.GetPriority();
372 #if defined(OS_WIN)
373 EXPECT_TRUE(process.SetProcessBackgrounded(true));
374 EXPECT_TRUE(process.IsProcessBackgrounded());
375 EXPECT_TRUE(process.SetProcessBackgrounded(false));
376 EXPECT_FALSE(process.IsProcessBackgrounded());
377 #else
378 process.SetProcessBackgrounded(true);
379 process.SetProcessBackgrounded(false);
380 #endif
381 int new_priority = process.GetPriority();
382 EXPECT_EQ(old_priority, new_priority);
385 #if defined(OS_LINUX) || defined(OS_ANDROID)
386 TEST_F(ProcessUtilTest, GetSystemMemoryInfo) {
387 base::SystemMemoryInfoKB info;
388 EXPECT_TRUE(base::GetSystemMemoryInfo(&info));
390 // Ensure each field received a value.
391 EXPECT_GT(info.total, 0);
392 EXPECT_GT(info.free, 0);
393 EXPECT_GT(info.buffers, 0);
394 EXPECT_GT(info.cached, 0);
395 EXPECT_GT(info.active_anon, 0);
396 EXPECT_GT(info.inactive_anon, 0);
397 EXPECT_GT(info.active_file, 0);
398 EXPECT_GT(info.inactive_file, 0);
400 // All the values should be less than the total amount of memory.
401 EXPECT_LT(info.free, info.total);
402 EXPECT_LT(info.buffers, info.total);
403 EXPECT_LT(info.cached, info.total);
404 EXPECT_LT(info.active_anon, info.total);
405 EXPECT_LT(info.inactive_anon, info.total);
406 EXPECT_LT(info.active_file, info.total);
407 EXPECT_LT(info.inactive_file, info.total);
409 #if defined(OS_CHROMEOS)
410 // Chrome OS exposes shmem.
411 EXPECT_GT(info.shmem, 0);
412 EXPECT_LT(info.shmem, info.total);
413 // Chrome unit tests are not run on actual Chrome OS hardware, so gem_objects
414 // and gem_size cannot be tested here.
415 #endif
417 #endif // defined(OS_LINUX) || defined(OS_ANDROID)
419 // TODO(estade): if possible, port these 2 tests.
420 #if defined(OS_WIN)
421 TEST_F(ProcessUtilTest, EnableLFH) {
422 ASSERT_TRUE(base::EnableLowFragmentationHeap());
423 if (IsDebuggerPresent()) {
424 // Under these conditions, LFH can't be enabled. There's no point to test
425 // anything.
426 const char* no_debug_env = getenv("_NO_DEBUG_HEAP");
427 if (!no_debug_env || strcmp(no_debug_env, "1"))
428 return;
430 HMODULE kernel32 = GetModuleHandle(L"kernel32.dll");
431 ASSERT_TRUE(kernel32 != NULL);
432 HeapQueryFn heap_query = reinterpret_cast<HeapQueryFn>(GetProcAddress(
433 kernel32,
434 "HeapQueryInformation"));
436 // On Windows 2000, the function is not exported. This is not a reason to
437 // fail but we won't be able to retrieves information about the heap, so we
438 // should stop here.
439 if (heap_query == NULL)
440 return;
442 HANDLE heaps[1024] = { 0 };
443 unsigned number_heaps = GetProcessHeaps(1024, heaps);
444 EXPECT_GT(number_heaps, 0u);
445 for (unsigned i = 0; i < number_heaps; ++i) {
446 ULONG flag = 0;
447 SIZE_T length;
448 ASSERT_NE(0, heap_query(heaps[i],
449 HeapCompatibilityInformation,
450 &flag,
451 sizeof(flag),
452 &length));
453 // If flag is 0, the heap is a standard heap that does not support
454 // look-asides. If flag is 1, the heap supports look-asides. If flag is 2,
455 // the heap is a low-fragmentation heap (LFH). Note that look-asides are not
456 // supported on the LFH.
458 // We don't have any documented way of querying the HEAP_NO_SERIALIZE flag.
459 EXPECT_LE(flag, 2u);
460 EXPECT_NE(flag, 1u);
464 TEST_F(ProcessUtilTest, CalcFreeMemory) {
465 scoped_ptr<base::ProcessMetrics> metrics(
466 base::ProcessMetrics::CreateProcessMetrics(::GetCurrentProcess()));
467 ASSERT_TRUE(NULL != metrics.get());
469 bool using_tcmalloc = false;
471 // Detect if we are using tcmalloc
472 #if !defined(NO_TCMALLOC)
473 const char* chrome_allocator = getenv("CHROME_ALLOCATOR");
474 if (!chrome_allocator || _stricmp(chrome_allocator, "tcmalloc") == 0)
475 using_tcmalloc = true;
476 #endif
478 // Typical values here is ~1900 for total and ~1000 for largest. Obviously
479 // it depends in what other tests have done to this process.
480 base::FreeMBytes free_mem1 = {0};
481 EXPECT_TRUE(metrics->CalculateFreeMemory(&free_mem1));
482 EXPECT_LT(10u, free_mem1.total);
483 EXPECT_LT(10u, free_mem1.largest);
484 EXPECT_GT(2048u, free_mem1.total);
485 EXPECT_GT(2048u, free_mem1.largest);
486 EXPECT_GE(free_mem1.total, free_mem1.largest);
487 EXPECT_TRUE(NULL != free_mem1.largest_ptr);
489 // Allocate 20M and check again. It should have gone down.
490 const int kAllocMB = 20;
491 scoped_ptr<char[]> alloc(new char[kAllocMB * 1024 * 1024]);
492 size_t expected_total = free_mem1.total - kAllocMB;
493 size_t expected_largest = free_mem1.largest;
495 base::FreeMBytes free_mem2 = {0};
496 EXPECT_TRUE(metrics->CalculateFreeMemory(&free_mem2));
497 EXPECT_GE(free_mem2.total, free_mem2.largest);
498 // This test is flaky when using tcmalloc, because tcmalloc
499 // allocation strategy sometimes results in less than the
500 // full drop of 20Mb of free memory.
501 if (!using_tcmalloc)
502 EXPECT_GE(expected_total, free_mem2.total);
503 EXPECT_GE(expected_largest, free_mem2.largest);
504 EXPECT_TRUE(NULL != free_mem2.largest_ptr);
507 TEST_F(ProcessUtilTest, GetAppOutput) {
508 // Let's create a decently long message.
509 std::string message;
510 for (int i = 0; i < 1025; i++) { // 1025 so it does not end on a kilo-byte
511 // boundary.
512 message += "Hello!";
514 // cmd.exe's echo always adds a \r\n to its output.
515 std::string expected(message);
516 expected += "\r\n";
518 FilePath cmd(L"cmd.exe");
519 CommandLine cmd_line(cmd);
520 cmd_line.AppendArg("/c");
521 cmd_line.AppendArg("echo " + message + "");
522 std::string output;
523 ASSERT_TRUE(base::GetAppOutput(cmd_line, &output));
524 EXPECT_EQ(expected, output);
526 // Let's make sure stderr is ignored.
527 CommandLine other_cmd_line(cmd);
528 other_cmd_line.AppendArg("/c");
529 // http://msdn.microsoft.com/library/cc772622.aspx
530 cmd_line.AppendArg("echo " + message + " >&2");
531 output.clear();
532 ASSERT_TRUE(base::GetAppOutput(other_cmd_line, &output));
533 EXPECT_EQ("", output);
536 TEST_F(ProcessUtilTest, LaunchAsUser) {
537 base::UserTokenHandle token;
538 ASSERT_TRUE(OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &token));
539 std::wstring cmdline =
540 this->MakeCmdLine("SimpleChildProcess", false).GetCommandLineString();
541 base::LaunchOptions options;
542 options.as_user = token;
543 EXPECT_TRUE(base::LaunchProcess(cmdline, options, NULL));
546 #endif // defined(OS_WIN)
548 #if defined(OS_MACOSX)
550 // For the following Mac tests:
551 // Note that base::EnableTerminationOnHeapCorruption() is called as part of
552 // test suite setup and does not need to be done again, else mach_override
553 // will fail.
555 #if !defined(ADDRESS_SANITIZER)
556 // The following code tests the system implementation of malloc() thus no need
557 // to test it under AddressSanitizer.
558 TEST_F(ProcessUtilTest, MacMallocFailureDoesNotTerminate) {
559 // Test that ENOMEM doesn't crash via CrMallocErrorBreak two ways: the exit
560 // code and lack of the error string. The number of bytes is one less than
561 // MALLOC_ABSOLUTE_MAX_SIZE, more than which the system early-returns NULL and
562 // does not call through malloc_error_break(). See the comment at
563 // EnableTerminationOnOutOfMemory() for more information.
564 void* buf = NULL;
565 ASSERT_EXIT(
567 base::EnableTerminationOnOutOfMemory();
569 buf = malloc(std::numeric_limits<size_t>::max() - (2 * PAGE_SIZE) - 1);
571 testing::KilledBySignal(SIGTRAP),
572 "\\*\\*\\* error: can't allocate region.*"
573 "(Terminating process due to a potential for future heap "
574 "corruption){0}");
576 base::debug::Alias(buf);
578 #endif // !defined(ADDRESS_SANITIZER)
580 TEST_F(ProcessUtilTest, MacTerminateOnHeapCorruption) {
581 // Assert that freeing an unallocated pointer will crash the process.
582 char buf[3];
583 asm("" : "=r" (buf)); // Prevent clang from being too smart.
584 #if ARCH_CPU_64_BITS
585 // On 64 bit Macs, the malloc system automatically abort()s on heap corruption
586 // but does not output anything.
587 ASSERT_DEATH(free(buf), "");
588 #elif defined(ADDRESS_SANITIZER)
589 // AddressSanitizer replaces malloc() and prints a different error message on
590 // heap corruption.
591 ASSERT_DEATH(free(buf), "attempting free on address which "
592 "was not malloc\\(\\)-ed");
593 #else
594 ASSERT_DEATH(free(buf), "being freed.*"
595 "\\*\\*\\* set a breakpoint in malloc_error_break to debug.*"
596 "Terminating process due to a potential for future heap corruption");
597 #endif // ARCH_CPU_64_BITS || defined(ADDRESS_SANITIZER)
600 #endif // defined(OS_MACOSX)
602 #if defined(OS_POSIX)
604 namespace {
606 // Returns the maximum number of files that a process can have open.
607 // Returns 0 on error.
608 int GetMaxFilesOpenInProcess() {
609 struct rlimit rlim;
610 if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
611 return 0;
614 // rlim_t is a uint64 - clip to maxint. We do this since FD #s are ints
615 // which are all 32 bits on the supported platforms.
616 rlim_t max_int = static_cast<rlim_t>(std::numeric_limits<int32>::max());
617 if (rlim.rlim_cur > max_int) {
618 return max_int;
621 return rlim.rlim_cur;
624 const int kChildPipe = 20; // FD # for write end of pipe in child process.
626 } // namespace
628 MULTIPROCESS_TEST_MAIN(ProcessUtilsLeakFDChildProcess) {
629 // This child process counts the number of open FDs, it then writes that
630 // number out to a pipe connected to the parent.
631 int num_open_files = 0;
632 int write_pipe = kChildPipe;
633 int max_files = GetMaxFilesOpenInProcess();
634 for (int i = STDERR_FILENO + 1; i < max_files; i++) {
635 if (i != kChildPipe) {
636 int fd;
637 if ((fd = HANDLE_EINTR(dup(i))) != -1) {
638 close(fd);
639 num_open_files += 1;
644 int written = HANDLE_EINTR(write(write_pipe, &num_open_files,
645 sizeof(num_open_files)));
646 DCHECK_EQ(static_cast<size_t>(written), sizeof(num_open_files));
647 int ret = HANDLE_EINTR(close(write_pipe));
648 DPCHECK(ret == 0);
650 return 0;
653 int ProcessUtilTest::CountOpenFDsInChild() {
654 int fds[2];
655 if (pipe(fds) < 0)
656 NOTREACHED();
658 base::FileHandleMappingVector fd_mapping_vec;
659 fd_mapping_vec.push_back(std::pair<int, int>(fds[1], kChildPipe));
660 base::ProcessHandle handle = this->SpawnChild(
661 "ProcessUtilsLeakFDChildProcess", fd_mapping_vec, false);
662 CHECK(handle);
663 int ret = HANDLE_EINTR(close(fds[1]));
664 DPCHECK(ret == 0);
666 // Read number of open files in client process from pipe;
667 int num_open_files = -1;
668 ssize_t bytes_read =
669 HANDLE_EINTR(read(fds[0], &num_open_files, sizeof(num_open_files)));
670 CHECK_EQ(bytes_read, static_cast<ssize_t>(sizeof(num_open_files)));
672 #if defined(THREAD_SANITIZER) || defined(USE_HEAPCHECKER)
673 // Compiler-based ThreadSanitizer makes this test slow.
674 CHECK(base::WaitForSingleProcess(handle, base::TimeDelta::FromSeconds(3)));
675 #else
676 CHECK(base::WaitForSingleProcess(handle, base::TimeDelta::FromSeconds(1)));
677 #endif
678 base::CloseProcessHandle(handle);
679 ret = HANDLE_EINTR(close(fds[0]));
680 DPCHECK(ret == 0);
682 return num_open_files;
685 #if defined(ADDRESS_SANITIZER) || defined(THREAD_SANITIZER)
686 // ProcessUtilTest.FDRemapping is flaky when ran under xvfb-run on Precise.
687 // The problem is 100% reproducible with both ASan and TSan.
688 // See http://crbug.com/136720.
689 #define MAYBE_FDRemapping DISABLED_FDRemapping
690 #else
691 #define MAYBE_FDRemapping FDRemapping
692 #endif
693 TEST_F(ProcessUtilTest, MAYBE_FDRemapping) {
694 int fds_before = CountOpenFDsInChild();
696 // open some dummy fds to make sure they don't propagate over to the
697 // child process.
698 int dev_null = open("/dev/null", O_RDONLY);
699 int sockets[2];
700 socketpair(AF_UNIX, SOCK_STREAM, 0, sockets);
702 int fds_after = CountOpenFDsInChild();
704 ASSERT_EQ(fds_after, fds_before);
706 int ret;
707 ret = HANDLE_EINTR(close(sockets[0]));
708 DPCHECK(ret == 0);
709 ret = HANDLE_EINTR(close(sockets[1]));
710 DPCHECK(ret == 0);
711 ret = HANDLE_EINTR(close(dev_null));
712 DPCHECK(ret == 0);
715 namespace {
717 std::string TestLaunchProcess(const base::EnvironmentVector& env_changes,
718 const int clone_flags) {
719 std::vector<std::string> args;
720 base::FileHandleMappingVector fds_to_remap;
722 args.push_back(kPosixShell);
723 args.push_back("-c");
724 args.push_back("echo $BASE_TEST");
726 int fds[2];
727 PCHECK(pipe(fds) == 0);
729 fds_to_remap.push_back(std::make_pair(fds[1], 1));
730 base::LaunchOptions options;
731 options.wait = true;
732 options.environ = &env_changes;
733 options.fds_to_remap = &fds_to_remap;
734 #if defined(OS_LINUX)
735 options.clone_flags = clone_flags;
736 #else
737 CHECK_EQ(0, clone_flags);
738 #endif // OS_LINUX
739 EXPECT_TRUE(base::LaunchProcess(args, options, NULL));
740 PCHECK(HANDLE_EINTR(close(fds[1])) == 0);
742 char buf[512];
743 const ssize_t n = HANDLE_EINTR(read(fds[0], buf, sizeof(buf)));
744 PCHECK(n > 0);
746 PCHECK(HANDLE_EINTR(close(fds[0])) == 0);
748 return std::string(buf, n);
751 const char kLargeString[] =
752 "0123456789012345678901234567890123456789012345678901234567890123456789"
753 "0123456789012345678901234567890123456789012345678901234567890123456789"
754 "0123456789012345678901234567890123456789012345678901234567890123456789"
755 "0123456789012345678901234567890123456789012345678901234567890123456789"
756 "0123456789012345678901234567890123456789012345678901234567890123456789"
757 "0123456789012345678901234567890123456789012345678901234567890123456789"
758 "0123456789012345678901234567890123456789012345678901234567890123456789";
760 } // namespace
762 TEST_F(ProcessUtilTest, LaunchProcess) {
763 base::EnvironmentVector env_changes;
764 const int no_clone_flags = 0;
766 env_changes.push_back(std::make_pair(std::string("BASE_TEST"),
767 std::string("bar")));
768 EXPECT_EQ("bar\n", TestLaunchProcess(env_changes, no_clone_flags));
769 env_changes.clear();
771 EXPECT_EQ(0, setenv("BASE_TEST", "testing", 1 /* override */));
772 EXPECT_EQ("testing\n", TestLaunchProcess(env_changes, no_clone_flags));
774 env_changes.push_back(
775 std::make_pair(std::string("BASE_TEST"), std::string()));
776 EXPECT_EQ("\n", TestLaunchProcess(env_changes, no_clone_flags));
778 env_changes[0].second = "foo";
779 EXPECT_EQ("foo\n", TestLaunchProcess(env_changes, no_clone_flags));
781 env_changes.clear();
782 EXPECT_EQ(0, setenv("BASE_TEST", kLargeString, 1 /* override */));
783 EXPECT_EQ(std::string(kLargeString) + "\n",
784 TestLaunchProcess(env_changes, no_clone_flags));
786 env_changes.push_back(std::make_pair(std::string("BASE_TEST"),
787 std::string("wibble")));
788 EXPECT_EQ("wibble\n", TestLaunchProcess(env_changes, no_clone_flags));
790 #if defined(OS_LINUX)
791 // Test a non-trival value for clone_flags.
792 // Don't test on Valgrind as it has limited support for clone().
793 if (!RunningOnValgrind()) {
794 EXPECT_EQ("wibble\n", TestLaunchProcess(env_changes, CLONE_FS | SIGCHLD));
796 #endif
799 TEST_F(ProcessUtilTest, AlterEnvironment) {
800 const char* const empty[] = { NULL };
801 const char* const a2[] = { "A=2", NULL };
802 base::EnvironmentVector changes;
803 char** e;
805 e = base::AlterEnvironment(changes, empty);
806 EXPECT_TRUE(e[0] == NULL);
807 delete[] e;
809 changes.push_back(std::make_pair(std::string("A"), std::string("1")));
810 e = base::AlterEnvironment(changes, empty);
811 EXPECT_EQ(std::string("A=1"), e[0]);
812 EXPECT_TRUE(e[1] == NULL);
813 delete[] e;
815 changes.clear();
816 changes.push_back(std::make_pair(std::string("A"), std::string()));
817 e = base::AlterEnvironment(changes, empty);
818 EXPECT_TRUE(e[0] == NULL);
819 delete[] e;
821 changes.clear();
822 e = base::AlterEnvironment(changes, a2);
823 EXPECT_EQ(std::string("A=2"), e[0]);
824 EXPECT_TRUE(e[1] == NULL);
825 delete[] e;
827 changes.clear();
828 changes.push_back(std::make_pair(std::string("A"), std::string("1")));
829 e = base::AlterEnvironment(changes, a2);
830 EXPECT_EQ(std::string("A=1"), e[0]);
831 EXPECT_TRUE(e[1] == NULL);
832 delete[] e;
834 changes.clear();
835 changes.push_back(std::make_pair(std::string("A"), std::string()));
836 e = base::AlterEnvironment(changes, a2);
837 EXPECT_TRUE(e[0] == NULL);
838 delete[] e;
841 TEST_F(ProcessUtilTest, GetAppOutput) {
842 std::string output;
844 #if defined(OS_ANDROID)
845 std::vector<std::string> argv;
846 argv.push_back("sh"); // Instead of /bin/sh, force path search to find it.
847 argv.push_back("-c");
849 argv.push_back("exit 0");
850 EXPECT_TRUE(base::GetAppOutput(CommandLine(argv), &output));
851 EXPECT_STREQ("", output.c_str());
853 argv[2] = "exit 1";
854 EXPECT_FALSE(base::GetAppOutput(CommandLine(argv), &output));
855 EXPECT_STREQ("", output.c_str());
857 argv[2] = "echo foobar42";
858 EXPECT_TRUE(base::GetAppOutput(CommandLine(argv), &output));
859 EXPECT_STREQ("foobar42\n", output.c_str());
860 #else
861 EXPECT_TRUE(base::GetAppOutput(CommandLine(FilePath("true")), &output));
862 EXPECT_STREQ("", output.c_str());
864 EXPECT_FALSE(base::GetAppOutput(CommandLine(FilePath("false")), &output));
866 std::vector<std::string> argv;
867 argv.push_back("/bin/echo");
868 argv.push_back("-n");
869 argv.push_back("foobar42");
870 EXPECT_TRUE(base::GetAppOutput(CommandLine(argv), &output));
871 EXPECT_STREQ("foobar42", output.c_str());
872 #endif // defined(OS_ANDROID)
875 TEST_F(ProcessUtilTest, GetAppOutputRestricted) {
876 // Unfortunately, since we can't rely on the path, we need to know where
877 // everything is. So let's use /bin/sh, which is on every POSIX system, and
878 // its built-ins.
879 std::vector<std::string> argv;
880 argv.push_back(std::string(kShellPath)); // argv[0]
881 argv.push_back("-c"); // argv[1]
883 // On success, should set |output|. We use |/bin/sh -c 'exit 0'| instead of
884 // |true| since the location of the latter may be |/bin| or |/usr/bin| (and we
885 // need absolute paths).
886 argv.push_back("exit 0"); // argv[2]; equivalent to "true"
887 std::string output = "abc";
888 EXPECT_TRUE(base::GetAppOutputRestricted(CommandLine(argv), &output, 100));
889 EXPECT_STREQ("", output.c_str());
891 argv[2] = "exit 1"; // equivalent to "false"
892 output = "before";
893 EXPECT_FALSE(base::GetAppOutputRestricted(CommandLine(argv),
894 &output, 100));
895 EXPECT_STREQ("", output.c_str());
897 // Amount of output exactly equal to space allowed.
898 argv[2] = "echo 123456789"; // (the sh built-in doesn't take "-n")
899 output.clear();
900 EXPECT_TRUE(base::GetAppOutputRestricted(CommandLine(argv), &output, 10));
901 EXPECT_STREQ("123456789\n", output.c_str());
903 // Amount of output greater than space allowed.
904 output.clear();
905 EXPECT_TRUE(base::GetAppOutputRestricted(CommandLine(argv), &output, 5));
906 EXPECT_STREQ("12345", output.c_str());
908 // Amount of output less than space allowed.
909 output.clear();
910 EXPECT_TRUE(base::GetAppOutputRestricted(CommandLine(argv), &output, 15));
911 EXPECT_STREQ("123456789\n", output.c_str());
913 // Zero space allowed.
914 output = "abc";
915 EXPECT_TRUE(base::GetAppOutputRestricted(CommandLine(argv), &output, 0));
916 EXPECT_STREQ("", output.c_str());
919 #if !defined(OS_MACOSX) && !defined(OS_OPENBSD)
920 // TODO(benwells): GetAppOutputRestricted should terminate applications
921 // with SIGPIPE when we have enough output. http://crbug.com/88502
922 TEST_F(ProcessUtilTest, GetAppOutputRestrictedSIGPIPE) {
923 std::vector<std::string> argv;
924 std::string output;
926 argv.push_back(std::string(kShellPath)); // argv[0]
927 argv.push_back("-c");
928 #if defined(OS_ANDROID)
929 argv.push_back("while echo 12345678901234567890; do :; done");
930 EXPECT_TRUE(base::GetAppOutputRestricted(CommandLine(argv), &output, 10));
931 EXPECT_STREQ("1234567890", output.c_str());
932 #else
933 argv.push_back("yes");
934 EXPECT_TRUE(base::GetAppOutputRestricted(CommandLine(argv), &output, 10));
935 EXPECT_STREQ("y\ny\ny\ny\ny\n", output.c_str());
936 #endif
938 #endif
940 TEST_F(ProcessUtilTest, GetAppOutputRestrictedNoZombies) {
941 std::vector<std::string> argv;
943 argv.push_back(std::string(kShellPath)); // argv[0]
944 argv.push_back("-c"); // argv[1]
945 argv.push_back("echo 123456789012345678901234567890"); // argv[2]
947 // Run |GetAppOutputRestricted()| 300 (> default per-user processes on Mac OS
948 // 10.5) times with an output buffer big enough to capture all output.
949 for (int i = 0; i < 300; i++) {
950 std::string output;
951 EXPECT_TRUE(base::GetAppOutputRestricted(CommandLine(argv), &output, 100));
952 EXPECT_STREQ("123456789012345678901234567890\n", output.c_str());
955 // Ditto, but with an output buffer too small to capture all output.
956 for (int i = 0; i < 300; i++) {
957 std::string output;
958 EXPECT_TRUE(base::GetAppOutputRestricted(CommandLine(argv), &output, 10));
959 EXPECT_STREQ("1234567890", output.c_str());
963 TEST_F(ProcessUtilTest, GetAppOutputWithExitCode) {
964 // Test getting output from a successful application.
965 std::vector<std::string> argv;
966 std::string output;
967 int exit_code;
968 argv.push_back(std::string(kShellPath)); // argv[0]
969 argv.push_back("-c"); // argv[1]
970 argv.push_back("echo foo"); // argv[2];
971 EXPECT_TRUE(base::GetAppOutputWithExitCode(CommandLine(argv), &output,
972 &exit_code));
973 EXPECT_STREQ("foo\n", output.c_str());
974 EXPECT_EQ(exit_code, 0);
976 // Test getting output from an application which fails with a specific exit
977 // code.
978 output.clear();
979 argv[2] = "echo foo; exit 2";
980 EXPECT_TRUE(base::GetAppOutputWithExitCode(CommandLine(argv), &output,
981 &exit_code));
982 EXPECT_STREQ("foo\n", output.c_str());
983 EXPECT_EQ(exit_code, 2);
986 TEST_F(ProcessUtilTest, GetParentProcessId) {
987 base::ProcessId ppid = base::GetParentProcessId(base::GetCurrentProcId());
988 EXPECT_EQ(ppid, getppid());
991 #if defined(OS_LINUX) || defined(OS_ANDROID)
992 TEST_F(ProcessUtilTest, ParseProcStatCPU) {
993 // /proc/self/stat for a process running "top".
994 const char kTopStat[] = "960 (top) S 16230 960 16230 34818 960 "
995 "4202496 471 0 0 0 "
996 "12 16 0 0 " // <- These are the goods.
997 "20 0 1 0 121946157 15077376 314 18446744073709551615 4194304 "
998 "4246868 140733983044336 18446744073709551615 140244213071219 "
999 "0 0 0 138047495 0 0 0 17 1 0 0 0 0 0";
1000 EXPECT_EQ(12 + 16, base::ParseProcStatCPU(kTopStat));
1002 // cat /proc/self/stat on a random other machine I have.
1003 const char kSelfStat[] = "5364 (cat) R 5354 5364 5354 34819 5364 "
1004 "0 142 0 0 0 "
1005 "0 0 0 0 " // <- No CPU, apparently.
1006 "16 0 1 0 1676099790 2957312 114 4294967295 134512640 134528148 "
1007 "3221224832 3221224344 3086339742 0 0 0 0 0 0 0 17 0 0 0";
1009 EXPECT_EQ(0, base::ParseProcStatCPU(kSelfStat));
1012 // Disable on Android because base_unittests runs inside a Dalvik VM that
1013 // starts and stop threads (crbug.com/175563).
1014 #if !defined(OS_ANDROID)
1015 TEST_F(ProcessUtilTest, GetNumberOfThreads) {
1016 const base::ProcessHandle current = base::GetCurrentProcessHandle();
1017 const int initial_threads = base::GetNumberOfThreads(current);
1018 ASSERT_GT(initial_threads, 0);
1019 const int kNumAdditionalThreads = 10;
1021 scoped_ptr<base::Thread> my_threads[kNumAdditionalThreads];
1022 for (int i = 0; i < kNumAdditionalThreads; ++i) {
1023 my_threads[i].reset(new base::Thread("GetNumberOfThreadsTest"));
1024 my_threads[i]->Start();
1025 ASSERT_EQ(base::GetNumberOfThreads(current), initial_threads + 1 + i);
1028 // The Thread destructor will stop them.
1029 ASSERT_EQ(initial_threads, base::GetNumberOfThreads(current));
1031 #endif // !defined(OS_ANDROID)
1033 #endif // defined(OS_LINUX) || defined(OS_ANDROID)
1035 // TODO(port): port those unit tests.
1036 bool IsProcessDead(base::ProcessHandle child) {
1037 // waitpid() will actually reap the process which is exactly NOT what we
1038 // want to test for. The good thing is that if it can't find the process
1039 // we'll get a nice value for errno which we can test for.
1040 const pid_t result = HANDLE_EINTR(waitpid(child, NULL, WNOHANG));
1041 return result == -1 && errno == ECHILD;
1044 TEST_F(ProcessUtilTest, DelayedTermination) {
1045 base::ProcessHandle child_process =
1046 SpawnChild("process_util_test_never_die", false);
1047 ASSERT_TRUE(child_process);
1048 base::EnsureProcessTerminated(child_process);
1049 base::WaitForSingleProcess(child_process, base::TimeDelta::FromSeconds(5));
1051 // Check that process was really killed.
1052 EXPECT_TRUE(IsProcessDead(child_process));
1053 base::CloseProcessHandle(child_process);
1056 MULTIPROCESS_TEST_MAIN(process_util_test_never_die) {
1057 while (1) {
1058 sleep(500);
1060 return 0;
1063 TEST_F(ProcessUtilTest, ImmediateTermination) {
1064 base::ProcessHandle child_process =
1065 SpawnChild("process_util_test_die_immediately", false);
1066 ASSERT_TRUE(child_process);
1067 // Give it time to die.
1068 sleep(2);
1069 base::EnsureProcessTerminated(child_process);
1071 // Check that process was really killed.
1072 EXPECT_TRUE(IsProcessDead(child_process));
1073 base::CloseProcessHandle(child_process);
1076 MULTIPROCESS_TEST_MAIN(process_util_test_die_immediately) {
1077 return 0;
1080 #endif // defined(OS_POSIX)
1082 // Android doesn't implement set_new_handler, so we can't use the
1083 // OutOfMemoryTest cases.
1084 // OpenBSD does not support these tests either.
1085 // AddressSanitizer and ThreadSanitizer define the malloc()/free()/etc.
1086 // functions so that they don't crash if the program is out of memory, so the
1087 // OOM tests aren't supposed to work.
1088 // TODO(vandebo) make this work on Windows too.
1089 #if !defined(OS_ANDROID) && !defined(OS_OPENBSD) && \
1090 !defined(OS_WIN) && \
1091 !defined(ADDRESS_SANITIZER) && !defined(THREAD_SANITIZER)
1093 #if defined(USE_TCMALLOC)
1094 extern "C" {
1095 int tc_set_new_mode(int mode);
1097 #endif // defined(USE_TCMALLOC)
1099 class OutOfMemoryDeathTest : public testing::Test {
1100 public:
1101 OutOfMemoryDeathTest()
1102 : value_(NULL),
1103 // Make test size as large as possible minus a few pages so
1104 // that alignment or other rounding doesn't make it wrap.
1105 test_size_(std::numeric_limits<std::size_t>::max() - 12 * 1024),
1106 signed_test_size_(std::numeric_limits<ssize_t>::max()) {
1109 #if defined(USE_TCMALLOC)
1110 virtual void SetUp() OVERRIDE {
1111 tc_set_new_mode(1);
1114 virtual void TearDown() OVERRIDE {
1115 tc_set_new_mode(0);
1117 #endif // defined(USE_TCMALLOC)
1119 void SetUpInDeathAssert() {
1120 // Must call EnableTerminationOnOutOfMemory() because that is called from
1121 // chrome's main function and therefore hasn't been called yet.
1122 // Since this call may result in another thread being created and death
1123 // tests shouldn't be started in a multithread environment, this call
1124 // should be done inside of the ASSERT_DEATH.
1125 base::EnableTerminationOnOutOfMemory();
1128 void* value_;
1129 size_t test_size_;
1130 ssize_t signed_test_size_;
1133 TEST_F(OutOfMemoryDeathTest, New) {
1134 ASSERT_DEATH({
1135 SetUpInDeathAssert();
1136 value_ = operator new(test_size_);
1137 }, "");
1140 TEST_F(OutOfMemoryDeathTest, NewArray) {
1141 ASSERT_DEATH({
1142 SetUpInDeathAssert();
1143 value_ = new char[test_size_];
1144 }, "");
1147 TEST_F(OutOfMemoryDeathTest, Malloc) {
1148 ASSERT_DEATH({
1149 SetUpInDeathAssert();
1150 value_ = malloc(test_size_);
1151 }, "");
1154 TEST_F(OutOfMemoryDeathTest, Realloc) {
1155 ASSERT_DEATH({
1156 SetUpInDeathAssert();
1157 value_ = realloc(NULL, test_size_);
1158 }, "");
1161 TEST_F(OutOfMemoryDeathTest, Calloc) {
1162 ASSERT_DEATH({
1163 SetUpInDeathAssert();
1164 value_ = calloc(1024, test_size_ / 1024L);
1165 }, "");
1168 TEST_F(OutOfMemoryDeathTest, Valloc) {
1169 ASSERT_DEATH({
1170 SetUpInDeathAssert();
1171 value_ = valloc(test_size_);
1172 }, "");
1175 #if defined(OS_LINUX)
1176 TEST_F(OutOfMemoryDeathTest, Pvalloc) {
1177 ASSERT_DEATH({
1178 SetUpInDeathAssert();
1179 value_ = pvalloc(test_size_);
1180 }, "");
1183 TEST_F(OutOfMemoryDeathTest, Memalign) {
1184 ASSERT_DEATH({
1185 SetUpInDeathAssert();
1186 value_ = memalign(4, test_size_);
1187 }, "");
1190 TEST_F(OutOfMemoryDeathTest, ViaSharedLibraries) {
1191 // g_try_malloc is documented to return NULL on failure. (g_malloc is the
1192 // 'safe' default that crashes if allocation fails). However, since we have
1193 // hopefully overridden malloc, even g_try_malloc should fail. This tests
1194 // that the run-time symbol resolution is overriding malloc for shared
1195 // libraries as well as for our code.
1196 ASSERT_DEATH({
1197 SetUpInDeathAssert();
1198 value_ = g_try_malloc(test_size_);
1199 }, "");
1201 #endif // OS_LINUX
1203 // Android doesn't implement posix_memalign().
1204 #if defined(OS_POSIX) && !defined(OS_ANDROID)
1205 TEST_F(OutOfMemoryDeathTest, Posix_memalign) {
1206 // Grab the return value of posix_memalign to silence a compiler warning
1207 // about unused return values. We don't actually care about the return
1208 // value, since we're asserting death.
1209 ASSERT_DEATH({
1210 SetUpInDeathAssert();
1211 EXPECT_EQ(ENOMEM, posix_memalign(&value_, 8, test_size_));
1212 }, "");
1214 #endif // defined(OS_POSIX) && !defined(OS_ANDROID)
1216 #if defined(OS_MACOSX)
1218 // Purgeable zone tests
1220 TEST_F(OutOfMemoryDeathTest, MallocPurgeable) {
1221 malloc_zone_t* zone = malloc_default_purgeable_zone();
1222 ASSERT_DEATH({
1223 SetUpInDeathAssert();
1224 value_ = malloc_zone_malloc(zone, test_size_);
1225 }, "");
1228 TEST_F(OutOfMemoryDeathTest, ReallocPurgeable) {
1229 malloc_zone_t* zone = malloc_default_purgeable_zone();
1230 ASSERT_DEATH({
1231 SetUpInDeathAssert();
1232 value_ = malloc_zone_realloc(zone, NULL, test_size_);
1233 }, "");
1236 TEST_F(OutOfMemoryDeathTest, CallocPurgeable) {
1237 malloc_zone_t* zone = malloc_default_purgeable_zone();
1238 ASSERT_DEATH({
1239 SetUpInDeathAssert();
1240 value_ = malloc_zone_calloc(zone, 1024, test_size_ / 1024L);
1241 }, "");
1244 TEST_F(OutOfMemoryDeathTest, VallocPurgeable) {
1245 malloc_zone_t* zone = malloc_default_purgeable_zone();
1246 ASSERT_DEATH({
1247 SetUpInDeathAssert();
1248 value_ = malloc_zone_valloc(zone, test_size_);
1249 }, "");
1252 TEST_F(OutOfMemoryDeathTest, PosixMemalignPurgeable) {
1253 malloc_zone_t* zone = malloc_default_purgeable_zone();
1254 ASSERT_DEATH({
1255 SetUpInDeathAssert();
1256 value_ = malloc_zone_memalign(zone, 8, test_size_);
1257 }, "");
1260 // Since these allocation functions take a signed size, it's possible that
1261 // calling them just once won't be enough to exhaust memory. In the 32-bit
1262 // environment, it's likely that these allocation attempts will fail because
1263 // not enough contiguous address space is available. In the 64-bit environment,
1264 // it's likely that they'll fail because they would require a preposterous
1265 // amount of (virtual) memory.
1267 TEST_F(OutOfMemoryDeathTest, CFAllocatorSystemDefault) {
1268 ASSERT_DEATH({
1269 SetUpInDeathAssert();
1270 while ((value_ =
1271 base::AllocateViaCFAllocatorSystemDefault(signed_test_size_))) {}
1272 }, "");
1275 TEST_F(OutOfMemoryDeathTest, CFAllocatorMalloc) {
1276 ASSERT_DEATH({
1277 SetUpInDeathAssert();
1278 while ((value_ =
1279 base::AllocateViaCFAllocatorMalloc(signed_test_size_))) {}
1280 }, "");
1283 TEST_F(OutOfMemoryDeathTest, CFAllocatorMallocZone) {
1284 ASSERT_DEATH({
1285 SetUpInDeathAssert();
1286 while ((value_ =
1287 base::AllocateViaCFAllocatorMallocZone(signed_test_size_))) {}
1288 }, "");
1291 #if !defined(ARCH_CPU_64_BITS)
1293 // See process_util_unittest_mac.mm for an explanation of why this test isn't
1294 // run in the 64-bit environment.
1296 TEST_F(OutOfMemoryDeathTest, PsychoticallyBigObjCObject) {
1297 ASSERT_DEATH({
1298 SetUpInDeathAssert();
1299 while ((value_ = base::AllocatePsychoticallyBigObjCObject())) {}
1300 }, "");
1303 #endif // !ARCH_CPU_64_BITS
1304 #endif // OS_MACOSX
1306 #endif // !defined(OS_ANDROID) && !defined(OS_OPENBSD) &&
1307 // !defined(OS_WIN) && !defined(ADDRESS_SANITIZER)