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.
10 #include <sys/types.h>
15 #include "base/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"
27 using std::numeric_limits
;
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 Type
HideValueFromCompiler(volatile Type value
) {
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
));
45 // - NO_TCMALLOC (should be defined if compiled with use_allocator!="tcmalloc")
46 // - ADDRESS_SANITIZER and SYZYASAN because they have their own memory allocator
47 // - IOS does not use tcmalloc
48 // - OS_MACOSX does not use tcmalloc
49 #if !defined(NO_TCMALLOC) && !defined(ADDRESS_SANITIZER) && \
50 !defined(OS_IOS) && !defined(OS_MACOSX) && !defined(SYZYASAN)
51 #define TCMALLOC_TEST(function) function
53 #define TCMALLOC_TEST(function) DISABLED_##function
56 // TODO(jln): switch to std::numeric_limits<int>::max() when we switch to
58 const size_t kTooBigAllocSize
= INT_MAX
;
60 // Detect runtime TCMalloc bypasses.
61 bool IsTcMallocBypassed() {
62 #if defined(OS_LINUX) || defined(OS_CHROMEOS)
63 // This should detect a TCMalloc bypass from Valgrind.
64 char* g_slice
= getenv("G_SLICE");
65 if (g_slice
&& !strcmp(g_slice
, "always-malloc"))
68 // This should detect a TCMalloc bypass from setting
69 // the CHROME_ALLOCATOR environment variable.
70 char* allocator
= getenv("CHROME_ALLOCATOR");
71 if (allocator
&& strcmp(allocator
, "tcmalloc"))
77 bool CallocDiesOnOOM() {
78 // The sanitizers' calloc dies on OOM instead of returning NULL.
79 // The wrapper function in base/process_util_linux.cc that is used when we
80 // compile without TCMalloc will just die on OOM instead of returning NULL.
81 #if !defined(OS_WIN) && (defined(ADDRESS_SANITIZER) || \
82 defined(MEMORY_SANITIZER) || defined(THREAD_SANITIZER) || \
83 (defined(OS_LINUX) && defined(NO_TCMALLOC)))
90 // Fake test that allow to know the state of TCMalloc by looking at bots.
91 TEST(SecurityTest
, TCMALLOC_TEST(IsTCMallocDynamicallyBypassed
)) {
92 printf("Malloc is dynamically bypassed: %s\n",
93 IsTcMallocBypassed() ? "yes." : "no.");
96 // The MemoryAllocationRestrictions* tests test that we can not allocate a
97 // memory range that cannot be indexed via an int. This is used to mitigate
98 // vulnerabilities in libraries that use int instead of size_t. See
101 TEST(SecurityTest
, TCMALLOC_TEST(MemoryAllocationRestrictionsMalloc
)) {
102 if (!IsTcMallocBypassed()) {
103 scoped_ptr
<char, base::FreeDeleter
> ptr(static_cast<char*>(
104 HideValueFromCompiler(malloc(kTooBigAllocSize
))));
109 TEST(SecurityTest
, TCMALLOC_TEST(MemoryAllocationRestrictionsCalloc
)) {
110 if (!IsTcMallocBypassed()) {
111 scoped_ptr
<char, base::FreeDeleter
> ptr(static_cast<char*>(
112 HideValueFromCompiler(calloc(kTooBigAllocSize
, 1))));
117 TEST(SecurityTest
, TCMALLOC_TEST(MemoryAllocationRestrictionsRealloc
)) {
118 if (!IsTcMallocBypassed()) {
119 char* orig_ptr
= static_cast<char*>(malloc(1));
120 ASSERT_TRUE(orig_ptr
);
121 scoped_ptr
<char, base::FreeDeleter
> ptr(static_cast<char*>(
122 HideValueFromCompiler(realloc(orig_ptr
, kTooBigAllocSize
))));
124 // If realloc() did not succeed, we need to free orig_ptr.
130 char large_array
[kTooBigAllocSize
];
133 TEST(SecurityTest
, TCMALLOC_TEST(MemoryAllocationRestrictionsNew
)) {
134 if (!IsTcMallocBypassed()) {
135 scoped_ptr
<VeryLargeStruct
> ptr(
136 HideValueFromCompiler(new (nothrow
) VeryLargeStruct
));
141 TEST(SecurityTest
, TCMALLOC_TEST(MemoryAllocationRestrictionsNewArray
)) {
142 if (!IsTcMallocBypassed()) {
143 scoped_ptr
<char[]> ptr(
144 HideValueFromCompiler(new (nothrow
) char[kTooBigAllocSize
]));
149 // The tests bellow check for overflows in new[] and calloc().
151 #if defined(OS_IOS) || defined(OS_WIN) || defined(THREAD_SANITIZER)
152 #define DISABLE_ON_IOS_AND_WIN_AND_TSAN(function) DISABLED_##function
154 #define DISABLE_ON_IOS_AND_WIN_AND_TSAN(function) function
157 // There are platforms where these tests are known to fail. We would like to
158 // be able to easily check the status on the bots, but marking tests as
159 // FAILS_ is too clunky.
160 void OverflowTestsSoftExpectTrue(bool overflow_detected
) {
161 if (!overflow_detected
) {
162 #if defined(OS_LINUX) || defined(OS_ANDROID) || defined(OS_MACOSX)
163 // Sadly, on Linux, Android, and OSX we don't have a good story yet. Don't
164 // fail the test, but report.
165 printf("Platform has overflow: %s\n",
166 !overflow_detected
? "yes." : "no.");
168 // Otherwise, fail the test. (Note: EXPECT are ok in subfunctions, ASSERT
170 EXPECT_TRUE(overflow_detected
);
175 // Test array[TooBig][X] and array[X][TooBig] allocations for int overflows.
176 // IOS doesn't honor nothrow, so disable the test there.
177 // Crashes on Windows Dbg builds, disable there as well.
178 TEST(SecurityTest
, DISABLE_ON_IOS_AND_WIN_AND_TSAN(NewOverflow
)) {
179 const size_t kArraySize
= 4096;
180 // We want something "dynamic" here, so that the compiler doesn't
181 // immediately reject crazy arrays.
182 const size_t kDynamicArraySize
= HideValueFromCompiler(kArraySize
);
183 // numeric_limits are still not constexpr until we switch to C++11, so we
185 const size_t kMaxSizeT
= ~static_cast<size_t>(0);
186 ASSERT_EQ(numeric_limits
<size_t>::max(), kMaxSizeT
);
187 const size_t kArraySize2
= kMaxSizeT
/ kArraySize
+ 10;
188 const size_t kDynamicArraySize2
= HideValueFromCompiler(kArraySize2
);
190 scoped_ptr
<char[][kArraySize
]> array_pointer(new (nothrow
)
191 char[kDynamicArraySize2
][kArraySize
]);
192 OverflowTestsSoftExpectTrue(!array_pointer
);
194 // On windows, the compiler prevents static array sizes of more than
195 // 0x7fffffff (error C2148).
196 #if !defined(OS_WIN) || !defined(ARCH_CPU_64_BITS)
198 scoped_ptr
<char[][kArraySize2
]> array_pointer(new (nothrow
)
199 char[kDynamicArraySize
][kArraySize2
]);
200 OverflowTestsSoftExpectTrue(!array_pointer
);
202 #endif // !defined(OS_WIN) || !defined(ARCH_CPU_64_BITS)
205 // Call calloc(), eventually free the memory and return whether or not
206 // calloc() did succeed.
207 bool CallocReturnsNull(size_t nmemb
, size_t size
) {
208 scoped_ptr
<char, base::FreeDeleter
> array_pointer(
209 static_cast<char*>(calloc(nmemb
, size
)));
210 // We need the call to HideValueFromCompiler(): we have seen LLVM
211 // optimize away the call to calloc() entirely and assume
212 // the pointer to not be NULL.
213 return HideValueFromCompiler(array_pointer
.get()) == NULL
;
216 // Test if calloc() can overflow.
217 TEST(SecurityTest
, CallocOverflow
) {
218 const size_t kArraySize
= 4096;
219 const size_t kMaxSizeT
= numeric_limits
<size_t>::max();
220 const size_t kArraySize2
= kMaxSizeT
/ kArraySize
+ 10;
221 if (!CallocDiesOnOOM()) {
222 EXPECT_TRUE(CallocReturnsNull(kArraySize
, kArraySize2
));
223 EXPECT_TRUE(CallocReturnsNull(kArraySize2
, kArraySize
));
225 // It's also ok for calloc to just terminate the process.
226 #if defined(GTEST_HAS_DEATH_TEST)
227 EXPECT_DEATH(CallocReturnsNull(kArraySize
, kArraySize2
), "");
228 EXPECT_DEATH(CallocReturnsNull(kArraySize2
, kArraySize
), "");
229 #endif // GTEST_HAS_DEATH_TEST
233 #if (defined(OS_LINUX) || defined(OS_CHROMEOS)) && defined(__x86_64__)
234 // Check if ptr1 and ptr2 are separated by less than size chars.
235 bool ArePointersToSameArea(void* ptr1
, void* ptr2
, size_t size
) {
236 ptrdiff_t ptr_diff
= reinterpret_cast<char*>(std::max(ptr1
, ptr2
)) -
237 reinterpret_cast<char*>(std::min(ptr1
, ptr2
));
238 return static_cast<size_t>(ptr_diff
) <= size
;
241 // Check if TCMalloc uses an underlying random memory allocator.
242 TEST(SecurityTest
, TCMALLOC_TEST(RandomMemoryAllocations
)) {
243 if (IsTcMallocBypassed())
245 size_t kPageSize
= 4096; // We support x86_64 only.
246 // Check that malloc() returns an address that is neither the kernel's
247 // un-hinted mmap area, nor the current brk() area. The first malloc() may
248 // not be at a random address because TCMalloc will first exhaust any memory
249 // that it has allocated early on, before starting the sophisticated
251 void* default_mmap_heap_address
=
252 mmap(0, kPageSize
, PROT_READ
|PROT_WRITE
,
253 MAP_PRIVATE
|MAP_ANONYMOUS
, -1, 0);
254 ASSERT_NE(default_mmap_heap_address
,
255 static_cast<void*>(MAP_FAILED
));
256 ASSERT_EQ(munmap(default_mmap_heap_address
, kPageSize
), 0);
257 void* brk_heap_address
= sbrk(0);
258 ASSERT_NE(brk_heap_address
, reinterpret_cast<void*>(-1));
259 ASSERT_TRUE(brk_heap_address
!= NULL
);
260 // 1 MB should get us past what TCMalloc pre-allocated before initializing
261 // the sophisticated allocators.
262 size_t kAllocSize
= 1<<20;
263 scoped_ptr
<char, base::FreeDeleter
> ptr(
264 static_cast<char*>(malloc(kAllocSize
)));
265 ASSERT_TRUE(ptr
!= NULL
);
266 // If two pointers are separated by less than 512MB, they are considered
267 // to be in the same area.
268 // Our random pointer could be anywhere within 0x3fffffffffff (46bits),
269 // and we are checking that it's not withing 1GB (30 bits) from two
270 // addresses (brk and mmap heap). We have roughly one chance out of
272 const size_t kAreaRadius
= 1<<29;
273 bool in_default_mmap_heap
= ArePointersToSameArea(
274 ptr
.get(), default_mmap_heap_address
, kAreaRadius
);
275 EXPECT_FALSE(in_default_mmap_heap
);
277 bool in_default_brk_heap
= ArePointersToSameArea(
278 ptr
.get(), brk_heap_address
, kAreaRadius
);
279 EXPECT_FALSE(in_default_brk_heap
);
281 // In the implementation, we always mask our random addresses with
282 // kRandomMask, so we use it as an additional detection mechanism.
283 const uintptr_t kRandomMask
= 0x3fffffffffffULL
;
284 bool impossible_random_address
=
285 reinterpret_cast<uintptr_t>(ptr
.get()) & ~kRandomMask
;
286 EXPECT_FALSE(impossible_random_address
);
289 #endif // (defined(OS_LINUX) || defined(OS_CHROMEOS)) && defined(__x86_64__)