Roll src/third_party/WebKit eac3800:0237a66 (svn 202606:202607)
[chromium-blink-merge.git] / base / security_unittest.cc
bloba9c73f7c5927592ecdb8a9f867c0dd24ad60c3fb
1 // Copyright (c) 2013 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 #include <fcntl.h>
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <sys/stat.h>
10 #include <sys/types.h>
12 #include <algorithm>
13 #include <limits>
15 #include "base/files/file_util.h"
16 #include "base/logging.h"
17 #include "base/memory/scoped_ptr.h"
18 #include "build/build_config.h"
19 #include "testing/gtest/include/gtest/gtest.h"
21 #if defined(OS_POSIX)
22 #include <sys/mman.h>
23 #include <unistd.h>
24 #endif
26 using std::nothrow;
27 using std::numeric_limits;
29 namespace {
31 // This function acts as a compiler optimization barrier. We use it to
32 // prevent the compiler from making an expression a compile-time constant.
33 // We also use it so that the compiler doesn't discard certain return values
34 // as something we don't need (see the comment with calloc below).
35 template <typename Type>
36 NOINLINE Type HideValueFromCompiler(volatile Type value) {
37 #if defined(__GNUC__)
38 // In a GCC compatible compiler (GCC or Clang), make this compiler barrier
39 // more robust than merely using "volatile".
40 __asm__ volatile ("" : "+r" (value));
41 #endif // __GNUC__
42 return value;
45 // Tcmalloc and Windows allocator shim support setting malloc limits.
46 // - NO_TCMALLOC (should be defined if compiled with use_allocator!="tcmalloc")
47 // - ADDRESS_SANITIZER and SYZYASAN because they have their own memory allocator
48 // - IOS does not use tcmalloc
49 // - OS_MACOSX does not use tcmalloc
50 // - Windows allocator shim defines ALLOCATOR_SHIM
51 #if (!defined(NO_TCMALLOC) || defined(ALLOCATOR_SHIM)) && \
52 !defined(ADDRESS_SANITIZER) && !defined(OS_IOS) && !defined(OS_MACOSX) && \
53 !defined(SYZYASAN)
54 #define MALLOC_OVERFLOW_TEST(function) function
55 #else
56 #define MALLOC_OVERFLOW_TEST(function) DISABLED_##function
57 #endif
59 #if defined(OS_LINUX) && defined(__x86_64__)
60 // Detect runtime TCMalloc bypasses.
61 bool IsTcMallocBypassed() {
62 // This should detect a TCMalloc bypass from Valgrind.
63 char* g_slice = getenv("G_SLICE");
64 if (g_slice && !strcmp(g_slice, "always-malloc"))
65 return true;
66 return false;
68 #endif
70 // There are platforms where these tests are known to fail. We would like to
71 // be able to easily check the status on the bots, but marking tests as
72 // FAILS_ is too clunky.
73 void OverflowTestsSoftExpectTrue(bool overflow_detected) {
74 if (!overflow_detected) {
75 #if defined(OS_LINUX) || defined(OS_ANDROID) || defined(OS_MACOSX)
76 // Sadly, on Linux, Android, and OSX we don't have a good story yet. Don't
77 // fail the test, but report.
78 printf("Platform has overflow: %s\n",
79 !overflow_detected ? "yes." : "no.");
80 #else
81 // Otherwise, fail the test. (Note: EXPECT are ok in subfunctions, ASSERT
82 // aren't).
83 EXPECT_TRUE(overflow_detected);
84 #endif
88 #if defined(OS_IOS) || defined(OS_WIN) || defined(THREAD_SANITIZER) || defined(OS_MACOSX)
89 #define MAYBE_NewOverflow DISABLED_NewOverflow
90 #else
91 #define MAYBE_NewOverflow NewOverflow
92 #endif
93 // Test array[TooBig][X] and array[X][TooBig] allocations for int overflows.
94 // IOS doesn't honor nothrow, so disable the test there.
95 // Crashes on Windows Dbg builds, disable there as well.
96 // Fails on Mac 10.8 http://crbug.com/227092
97 TEST(SecurityTest, MAYBE_NewOverflow) {
98 const size_t kArraySize = 4096;
99 // We want something "dynamic" here, so that the compiler doesn't
100 // immediately reject crazy arrays.
101 const size_t kDynamicArraySize = HideValueFromCompiler(kArraySize);
102 // numeric_limits are still not constexpr until we switch to C++11, so we
103 // use an ugly cast.
104 const size_t kMaxSizeT = ~static_cast<size_t>(0);
105 ASSERT_EQ(numeric_limits<size_t>::max(), kMaxSizeT);
106 const size_t kArraySize2 = kMaxSizeT / kArraySize + 10;
107 const size_t kDynamicArraySize2 = HideValueFromCompiler(kArraySize2);
109 scoped_ptr<char[][kArraySize]> array_pointer(new (nothrow)
110 char[kDynamicArraySize2][kArraySize]);
111 OverflowTestsSoftExpectTrue(!array_pointer);
113 // On windows, the compiler prevents static array sizes of more than
114 // 0x7fffffff (error C2148).
115 #if defined(OS_WIN) && defined(ARCH_CPU_64_BITS)
116 ALLOW_UNUSED_LOCAL(kDynamicArraySize);
117 #else
119 scoped_ptr<char[][kArraySize2]> array_pointer(new (nothrow)
120 char[kDynamicArraySize][kArraySize2]);
121 OverflowTestsSoftExpectTrue(!array_pointer);
123 #endif // !defined(OS_WIN) || !defined(ARCH_CPU_64_BITS)
126 #if defined(OS_LINUX) && defined(__x86_64__)
127 // Check if ptr1 and ptr2 are separated by less than size chars.
128 bool ArePointersToSameArea(void* ptr1, void* ptr2, size_t size) {
129 ptrdiff_t ptr_diff = reinterpret_cast<char*>(std::max(ptr1, ptr2)) -
130 reinterpret_cast<char*>(std::min(ptr1, ptr2));
131 return static_cast<size_t>(ptr_diff) <= size;
134 // Check if TCMalloc uses an underlying random memory allocator.
135 TEST(SecurityTest, MALLOC_OVERFLOW_TEST(RandomMemoryAllocations)) {
136 if (IsTcMallocBypassed())
137 return;
138 size_t kPageSize = 4096; // We support x86_64 only.
139 // Check that malloc() returns an address that is neither the kernel's
140 // un-hinted mmap area, nor the current brk() area. The first malloc() may
141 // not be at a random address because TCMalloc will first exhaust any memory
142 // that it has allocated early on, before starting the sophisticated
143 // allocators.
144 void* default_mmap_heap_address =
145 mmap(0, kPageSize, PROT_READ|PROT_WRITE,
146 MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
147 ASSERT_NE(default_mmap_heap_address,
148 static_cast<void*>(MAP_FAILED));
149 ASSERT_EQ(munmap(default_mmap_heap_address, kPageSize), 0);
150 void* brk_heap_address = sbrk(0);
151 ASSERT_NE(brk_heap_address, reinterpret_cast<void*>(-1));
152 ASSERT_TRUE(brk_heap_address != NULL);
153 // 1 MB should get us past what TCMalloc pre-allocated before initializing
154 // the sophisticated allocators.
155 size_t kAllocSize = 1<<20;
156 scoped_ptr<char, base::FreeDeleter> ptr(
157 static_cast<char*>(malloc(kAllocSize)));
158 ASSERT_TRUE(ptr != NULL);
159 // If two pointers are separated by less than 512MB, they are considered
160 // to be in the same area.
161 // Our random pointer could be anywhere within 0x3fffffffffff (46bits),
162 // and we are checking that it's not withing 1GB (30 bits) from two
163 // addresses (brk and mmap heap). We have roughly one chance out of
164 // 2^15 to flake.
165 const size_t kAreaRadius = 1<<29;
166 bool in_default_mmap_heap = ArePointersToSameArea(
167 ptr.get(), default_mmap_heap_address, kAreaRadius);
168 EXPECT_FALSE(in_default_mmap_heap);
170 bool in_default_brk_heap = ArePointersToSameArea(
171 ptr.get(), brk_heap_address, kAreaRadius);
172 EXPECT_FALSE(in_default_brk_heap);
174 // In the implementation, we always mask our random addresses with
175 // kRandomMask, so we use it as an additional detection mechanism.
176 const uintptr_t kRandomMask = 0x3fffffffffffULL;
177 bool impossible_random_address =
178 reinterpret_cast<uintptr_t>(ptr.get()) & ~kRandomMask;
179 EXPECT_FALSE(impossible_random_address);
182 #endif // defined(OS_LINUX) && defined(__x86_64__)
184 } // namespace