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 we compile with linux_use_tcmalloc=0)
46 // - ADDRESS_SANITIZER because it has its 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)
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"))
71 bool CallocDiesOnOOM() {
72 // The wrapper function in base/process_util_linux.cc that is used when we
73 // compile without TCMalloc will just die on OOM instead of returning NULL.
74 // This function is explicitly disabled if we compile with AddressSanitizer,
75 // MemorySanitizer or ThreadSanitizer.
76 #if defined(OS_LINUX) && defined(NO_TCMALLOC) && \
77 (!defined(ADDRESS_SANITIZER) && \
78 !defined(MEMORY_SANITIZER) && \
79 !defined(THREAD_SANITIZER))
86 // Fake test that allow to know the state of TCMalloc by looking at bots.
87 TEST(SecurityTest
, TCMALLOC_TEST(IsTCMallocDynamicallyBypassed
)) {
88 printf("Malloc is dynamically bypassed: %s\n",
89 IsTcMallocBypassed() ? "yes." : "no.");
92 // The MemoryAllocationRestrictions* tests test that we can not allocate a
93 // memory range that cannot be indexed via an int. This is used to mitigate
94 // vulnerabilities in libraries that use int instead of size_t. See
97 TEST(SecurityTest
, TCMALLOC_TEST(MemoryAllocationRestrictionsMalloc
)) {
98 if (!IsTcMallocBypassed()) {
99 scoped_ptr
<char, base::FreeDeleter
> ptr(static_cast<char*>(
100 HideValueFromCompiler(malloc(kTooBigAllocSize
))));
105 TEST(SecurityTest
, TCMALLOC_TEST(MemoryAllocationRestrictionsCalloc
)) {
106 if (!IsTcMallocBypassed()) {
107 scoped_ptr
<char, base::FreeDeleter
> ptr(static_cast<char*>(
108 HideValueFromCompiler(calloc(kTooBigAllocSize
, 1))));
113 TEST(SecurityTest
, TCMALLOC_TEST(MemoryAllocationRestrictionsRealloc
)) {
114 if (!IsTcMallocBypassed()) {
115 char* orig_ptr
= static_cast<char*>(malloc(1));
116 ASSERT_TRUE(orig_ptr
);
117 scoped_ptr
<char, base::FreeDeleter
> ptr(static_cast<char*>(
118 HideValueFromCompiler(realloc(orig_ptr
, kTooBigAllocSize
))));
120 // If realloc() did not succeed, we need to free orig_ptr.
126 char large_array
[kTooBigAllocSize
];
129 TEST(SecurityTest
, TCMALLOC_TEST(MemoryAllocationRestrictionsNew
)) {
130 if (!IsTcMallocBypassed()) {
131 scoped_ptr
<VeryLargeStruct
> ptr(
132 HideValueFromCompiler(new (nothrow
) VeryLargeStruct
));
137 TEST(SecurityTest
, TCMALLOC_TEST(MemoryAllocationRestrictionsNewArray
)) {
138 if (!IsTcMallocBypassed()) {
139 scoped_ptr
<char[]> ptr(
140 HideValueFromCompiler(new (nothrow
) char[kTooBigAllocSize
]));
145 // The tests bellow check for overflows in new[] and calloc().
147 #if defined(OS_IOS) || defined(OS_WIN)
148 #define DISABLE_ON_IOS_AND_WIN(function) DISABLED_##function
150 #define DISABLE_ON_IOS_AND_WIN(function) function
153 // There are platforms where these tests are known to fail. We would like to
154 // be able to easily check the status on the bots, but marking tests as
155 // FAILS_ is too clunky.
156 void OverflowTestsSoftExpectTrue(bool overflow_detected
) {
157 if (!overflow_detected
) {
158 #if defined(OS_LINUX) || defined(OS_ANDROID) || defined(OS_MACOSX)
159 // Sadly, on Linux, Android, and OSX we don't have a good story yet. Don't
160 // fail the test, but report.
161 printf("Platform has overflow: %s\n",
162 !overflow_detected
? "yes." : "no.");
164 // Otherwise, fail the test. (Note: EXPECT are ok in subfunctions, ASSERT
166 EXPECT_TRUE(overflow_detected
);
171 // Test array[TooBig][X] and array[X][TooBig] allocations for int overflows.
172 // IOS doesn't honor nothrow, so disable the test there.
173 // Crashes on Windows Dbg builds, disable there as well.
174 TEST(SecurityTest
, DISABLE_ON_IOS_AND_WIN(NewOverflow
)) {
175 const size_t kArraySize
= 4096;
176 // We want something "dynamic" here, so that the compiler doesn't
177 // immediately reject crazy arrays.
178 const size_t kDynamicArraySize
= HideValueFromCompiler(kArraySize
);
179 // numeric_limits are still not constexpr until we switch to C++11, so we
181 const size_t kMaxSizeT
= ~static_cast<size_t>(0);
182 ASSERT_EQ(numeric_limits
<size_t>::max(), kMaxSizeT
);
183 const size_t kArraySize2
= kMaxSizeT
/ kArraySize
+ 10;
184 const size_t kDynamicArraySize2
= HideValueFromCompiler(kArraySize2
);
186 scoped_ptr
<char[][kArraySize
]> array_pointer(new (nothrow
)
187 char[kDynamicArraySize2
][kArraySize
]);
188 OverflowTestsSoftExpectTrue(!array_pointer
);
190 // On windows, the compiler prevents static array sizes of more than
191 // 0x7fffffff (error C2148).
192 #if !defined(OS_WIN) || !defined(ARCH_CPU_64_BITS)
194 scoped_ptr
<char[][kArraySize2
]> array_pointer(new (nothrow
)
195 char[kDynamicArraySize
][kArraySize2
]);
196 OverflowTestsSoftExpectTrue(!array_pointer
);
198 #endif // !defined(OS_WIN) || !defined(ARCH_CPU_64_BITS)
201 // Call calloc(), eventually free the memory and return whether or not
202 // calloc() did succeed.
203 bool CallocReturnsNull(size_t nmemb
, size_t size
) {
204 scoped_ptr
<char, base::FreeDeleter
> array_pointer(
205 static_cast<char*>(calloc(nmemb
, size
)));
206 // We need the call to HideValueFromCompiler(): we have seen LLVM
207 // optimize away the call to calloc() entirely and assume
208 // the pointer to not be NULL.
209 return HideValueFromCompiler(array_pointer
.get()) == NULL
;
212 // Test if calloc() can overflow.
213 TEST(SecurityTest
, CallocOverflow
) {
214 const size_t kArraySize
= 4096;
215 const size_t kMaxSizeT
= numeric_limits
<size_t>::max();
216 const size_t kArraySize2
= kMaxSizeT
/ kArraySize
+ 10;
217 if (!CallocDiesOnOOM()) {
218 EXPECT_TRUE(CallocReturnsNull(kArraySize
, kArraySize2
));
219 EXPECT_TRUE(CallocReturnsNull(kArraySize2
, kArraySize
));
221 // It's also ok for calloc to just terminate the process.
222 #if defined(GTEST_HAS_DEATH_TEST)
223 EXPECT_DEATH(CallocReturnsNull(kArraySize
, kArraySize2
), "");
224 EXPECT_DEATH(CallocReturnsNull(kArraySize2
, kArraySize
), "");
225 #endif // GTEST_HAS_DEATH_TEST
229 #if (defined(OS_LINUX) || defined(OS_CHROMEOS)) && defined(__x86_64__)
230 // Useful for debugging.
231 void PrintProcSelfMaps() {
232 int fd
= open("/proc/self/maps", O_RDONLY
);
233 file_util::ScopedFD
fd_closer(&fd
);
237 ret
= read(fd
, buffer
, sizeof(buffer
) - 1);
240 fprintf(stdout
, "%s\n", buffer
);
243 // Check if ptr1 and ptr2 are separated by less than size chars.
244 bool ArePointersToSameArea(void* ptr1
, void* ptr2
, size_t size
) {
245 ptrdiff_t ptr_diff
= reinterpret_cast<char*>(std::max(ptr1
, ptr2
)) -
246 reinterpret_cast<char*>(std::min(ptr1
, ptr2
));
247 return static_cast<size_t>(ptr_diff
) <= size
;
250 // Check if TCMalloc uses an underlying random memory allocator.
251 TEST(SecurityTest
, TCMALLOC_TEST(RandomMemoryAllocations
)) {
252 if (IsTcMallocBypassed())
254 size_t kPageSize
= 4096; // We support x86_64 only.
255 // Check that malloc() returns an address that is neither the kernel's
256 // un-hinted mmap area, nor the current brk() area. The first malloc() may
257 // not be at a random address because TCMalloc will first exhaust any memory
258 // that it has allocated early on, before starting the sophisticated
260 void* default_mmap_heap_address
=
261 mmap(0, kPageSize
, PROT_READ
|PROT_WRITE
,
262 MAP_PRIVATE
|MAP_ANONYMOUS
, -1, 0);
263 ASSERT_NE(default_mmap_heap_address
,
264 static_cast<void*>(MAP_FAILED
));
265 ASSERT_EQ(munmap(default_mmap_heap_address
, kPageSize
), 0);
266 void* brk_heap_address
= sbrk(0);
267 ASSERT_NE(brk_heap_address
, reinterpret_cast<void*>(-1));
268 ASSERT_TRUE(brk_heap_address
!= NULL
);
269 // 1 MB should get us past what TCMalloc pre-allocated before initializing
270 // the sophisticated allocators.
271 size_t kAllocSize
= 1<<20;
272 scoped_ptr
<char, base::FreeDeleter
> ptr(
273 static_cast<char*>(malloc(kAllocSize
)));
274 ASSERT_TRUE(ptr
!= NULL
);
275 // If two pointers are separated by less than 512MB, they are considered
276 // to be in the same area.
277 // Our random pointer could be anywhere within 0x3fffffffffff (46bits),
278 // and we are checking that it's not withing 1GB (30 bits) from two
279 // addresses (brk and mmap heap). We have roughly one chance out of
281 const size_t kAreaRadius
= 1<<29;
282 bool in_default_mmap_heap
= ArePointersToSameArea(
283 ptr
.get(), default_mmap_heap_address
, kAreaRadius
);
284 EXPECT_FALSE(in_default_mmap_heap
);
286 bool in_default_brk_heap
= ArePointersToSameArea(
287 ptr
.get(), brk_heap_address
, kAreaRadius
);
288 EXPECT_FALSE(in_default_brk_heap
);
290 // In the implementation, we always mask our random addresses with
291 // kRandomMask, so we use it as an additional detection mechanism.
292 const uintptr_t kRandomMask
= 0x3fffffffffffULL
;
293 bool impossible_random_address
=
294 reinterpret_cast<uintptr_t>(ptr
.get()) & ~kRandomMask
;
295 EXPECT_FALSE(impossible_random_address
);
298 #endif // (defined(OS_LINUX) || defined(OS_CHROMEOS)) && defined(__x86_64__)