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 // This file contains intentional memory errors, some of which may lead to
6 // crashes if the test is ran without special memory testing tools. We use these
7 // errors to verify the sanity of the tools.
11 #include "base/atomicops.h"
12 #include "base/cfi_buildflags.h"
13 #include "base/debug/asan_invalid_access.h"
14 #include "base/debug/profiler.h"
15 #include "base/logging.h"
16 #include "base/sanitizer_buildflags.h"
17 #include "base/third_party/dynamic_annotations/dynamic_annotations.h"
18 #include "base/threading/thread.h"
19 #include "build/build_config.h"
20 #include "testing/gtest/include/gtest/gtest.h"
26 const base::subtle::Atomic32 kMagicValue = 42;
28 // Helper for memory accesses that can potentially corrupt memory or cause a
29 // crash during a native run.
30 #if defined(ADDRESS_SANITIZER)
31 #define HARMFUL_ACCESS(action, error_regexp) \
32 EXPECT_DEATH_IF_SUPPORTED(action, error_regexp)
33 #elif BUILDFLAG(IS_HWASAN)
34 #define HARMFUL_ACCESS(action, error_regexp) \
35 EXPECT_DEATH(action, "tag-mismatch")
37 #define HARMFUL_ACCESS(action, error_regexp)
38 #define HARMFUL_ACCESS_IS_NOOP
41 void DoReadUninitializedValue(char *ptr) {
42 // Comparison with 64 is to prevent clang from optimizing away the
43 // jump -- valgrind only catches jumps and conditional moves, but clang uses
44 // the borrow flag if the condition is just `*ptr == '\0'`. We no longer
45 // support valgrind, but this constant should be fine to keep as-is.
47 VLOG(1) << "Uninit condition is true";
49 VLOG(1) << "Uninit condition is false";
53 void ReadUninitializedValue(char *ptr) {
54 #if defined(MEMORY_SANITIZER)
55 EXPECT_DEATH(DoReadUninitializedValue(ptr),
56 "use-of-uninitialized-value");
58 DoReadUninitializedValue(ptr);
62 #ifndef HARMFUL_ACCESS_IS_NOOP
63 void ReadValueOutOfArrayBoundsLeft(char *ptr) {
65 VLOG(1) << "Reading a byte out of bounds: " << c;
68 void ReadValueOutOfArrayBoundsRight(char *ptr, size_t size) {
69 char c = ptr[size + 1];
70 VLOG(1) << "Reading a byte out of bounds: " << c;
73 void WriteValueOutOfArrayBoundsLeft(char *ptr) {
74 ptr[-1] = kMagicValue;
77 void WriteValueOutOfArrayBoundsRight(char *ptr, size_t size) {
78 ptr[size] = kMagicValue;
80 #endif // HARMFUL_ACCESS_IS_NOOP
82 void MakeSomeErrors(char *ptr, size_t size) {
83 ReadUninitializedValue(ptr);
85 HARMFUL_ACCESS(ReadValueOutOfArrayBoundsLeft(ptr),
86 "2 bytes to the left");
87 HARMFUL_ACCESS(ReadValueOutOfArrayBoundsRight(ptr, size),
88 "1 bytes to the right");
89 HARMFUL_ACCESS(WriteValueOutOfArrayBoundsLeft(ptr),
90 "1 bytes to the left");
91 HARMFUL_ACCESS(WriteValueOutOfArrayBoundsRight(ptr, size),
92 "0 bytes to the right");
97 // A memory leak detector should report an error in this test.
98 TEST(ToolsSanityTest, MemoryLeak) {
99 // Without the |volatile|, clang optimizes away the next two lines.
100 int* volatile leak = new int[256]; // Leak some memory intentionally.
101 leak[4] = 1; // Make sure the allocated memory is used.
104 // The following tests pass with Clang r170392, but not r172454, which
105 // makes AddressSanitizer detect errors in them. We disable these tests under
106 // AddressSanitizer until we fully switch to Clang r172454. After that the
107 // tests should be put back under the (defined(OS_IOS) || defined(OS_WIN))
109 // See also http://crbug.com/172614.
110 #if defined(ADDRESS_SANITIZER)
111 #define MAYBE_SingleElementDeletedWithBraces \
112 DISABLED_SingleElementDeletedWithBraces
113 #define MAYBE_ArrayDeletedWithoutBraces DISABLED_ArrayDeletedWithoutBraces
115 #define MAYBE_ArrayDeletedWithoutBraces ArrayDeletedWithoutBraces
116 #define MAYBE_SingleElementDeletedWithBraces SingleElementDeletedWithBraces
117 #endif // defined(ADDRESS_SANITIZER)
119 TEST(ToolsSanityTest, AccessesToNewMemory) {
120 char* foo = new char[16];
121 MakeSomeErrors(foo, 16);
124 HARMFUL_ACCESS(foo[5] = 0, "heap-use-after-free");
127 TEST(ToolsSanityTest, AccessesToMallocMemory) {
128 char* foo = reinterpret_cast<char*>(malloc(16));
129 MakeSomeErrors(foo, 16);
132 HARMFUL_ACCESS(foo[5] = 0, "heap-use-after-free");
135 TEST(ToolsSanityTest, AccessesToStack) {
138 ReadUninitializedValue(foo);
139 HARMFUL_ACCESS(ReadValueOutOfArrayBoundsLeft(foo),
140 "underflows this variable");
141 HARMFUL_ACCESS(ReadValueOutOfArrayBoundsRight(foo, 16),
142 "overflows this variable");
143 HARMFUL_ACCESS(WriteValueOutOfArrayBoundsLeft(foo),
144 "underflows this variable");
145 HARMFUL_ACCESS(WriteValueOutOfArrayBoundsRight(foo, 16),
146 "overflows this variable");
149 #if defined(ADDRESS_SANITIZER)
151 static int* allocateArray() {
152 // Clang warns about the mismatched new[]/delete if they occur in the same
157 // This test may corrupt memory if not compiled with AddressSanitizer.
158 TEST(ToolsSanityTest, MAYBE_ArrayDeletedWithoutBraces) {
159 // Without the |volatile|, clang optimizes away the next two lines.
160 int* volatile foo = allocateArray();
165 #if defined(ADDRESS_SANITIZER)
166 static int* allocateScalar() {
167 // Clang warns about the mismatched new/delete[] if they occur in the same
172 // This test may corrupt memory if not compiled with AddressSanitizer.
173 TEST(ToolsSanityTest, MAYBE_SingleElementDeletedWithBraces) {
174 // Without the |volatile|, clang optimizes away the next two lines.
175 int* volatile foo = allocateScalar();
181 TEST(ToolsSanityTest, DISABLED_AddressSanitizerNullDerefCrashTest) {
182 // Intentionally crash to make sure AddressSanitizer is running.
183 // This test should not be ran on bots.
184 int* volatile zero = NULL;
188 TEST(ToolsSanityTest, DISABLED_AddressSanitizerLocalOOBCrashTest) {
189 // Intentionally crash to make sure AddressSanitizer is instrumenting
190 // the local variables.
191 // This test should not be ran on bots.
193 // Work around the OOB warning reported by Clang.
194 int* volatile access = &array[5];
199 int g_asan_test_global_array[10];
202 TEST(ToolsSanityTest, DISABLED_AddressSanitizerGlobalOOBCrashTest) {
203 // Intentionally crash to make sure AddressSanitizer is instrumenting
204 // the global variables.
205 // This test should not be ran on bots.
207 // Work around the OOB warning reported by Clang.
208 int* volatile access = g_asan_test_global_array - 1;
212 #ifndef HARMFUL_ACCESS_IS_NOOP
213 TEST(ToolsSanityTest, AsanHeapOverflow) {
214 HARMFUL_ACCESS(debug::AsanHeapOverflow() ,"to the right");
217 TEST(ToolsSanityTest, AsanHeapUnderflow) {
218 HARMFUL_ACCESS(debug::AsanHeapUnderflow(), "to the left");
221 TEST(ToolsSanityTest, AsanHeapUseAfterFree) {
222 HARMFUL_ACCESS(debug::AsanHeapUseAfterFree(), "heap-use-after-free");
226 // The ASAN runtime doesn't detect heap corruption, this needs fixing before
227 // ASAN builds can ship to the wild. See https://crbug.com/818747.
228 TEST(ToolsSanityTest, DISABLED_AsanCorruptHeapBlock) {
229 HARMFUL_ACCESS(debug::AsanCorruptHeapBlock(), "");
232 TEST(ToolsSanityTest, DISABLED_AsanCorruptHeap) {
233 // This test will kill the process by raising an exception, there's no
234 // particular string to look for in the stack trace.
235 EXPECT_DEATH(debug::AsanCorruptHeap(), "");
238 #endif // !HARMFUL_ACCESS_IS_NOOP
242 // We use caps here just to ensure that the method name doesn't interfere with
243 // the wildcarded suppressions.
244 class TOOLS_SANITY_TEST_CONCURRENT_THREAD : public PlatformThread::Delegate {
246 explicit TOOLS_SANITY_TEST_CONCURRENT_THREAD(bool *value) : value_(value) {}
247 ~TOOLS_SANITY_TEST_CONCURRENT_THREAD() override = default;
248 void ThreadMain() override {
251 // Sleep for a few milliseconds so the two threads are more likely to live
252 // simultaneously. Otherwise we may miss the report due to mutex
253 // lock/unlock's inside thread creation code in pure-happens-before mode...
254 PlatformThread::Sleep(TimeDelta::FromMilliseconds(100));
260 class ReleaseStoreThread : public PlatformThread::Delegate {
262 explicit ReleaseStoreThread(base::subtle::Atomic32 *value) : value_(value) {}
263 ~ReleaseStoreThread() override = default;
264 void ThreadMain() override {
265 base::subtle::Release_Store(value_, kMagicValue);
267 // Sleep for a few milliseconds so the two threads are more likely to live
268 // simultaneously. Otherwise we may miss the report due to mutex
269 // lock/unlock's inside thread creation code in pure-happens-before mode...
270 PlatformThread::Sleep(TimeDelta::FromMilliseconds(100));
273 base::subtle::Atomic32 *value_;
276 class AcquireLoadThread : public PlatformThread::Delegate {
278 explicit AcquireLoadThread(base::subtle::Atomic32 *value) : value_(value) {}
279 ~AcquireLoadThread() override = default;
280 void ThreadMain() override {
281 // Wait for the other thread to make Release_Store
282 PlatformThread::Sleep(TimeDelta::FromMilliseconds(100));
283 base::subtle::Acquire_Load(value_);
286 base::subtle::Atomic32 *value_;
289 void RunInParallel(PlatformThread::Delegate *d1, PlatformThread::Delegate *d2) {
290 PlatformThreadHandle a;
291 PlatformThreadHandle b;
292 PlatformThread::Create(0, d1, &a);
293 PlatformThread::Create(0, d2, &b);
294 PlatformThread::Join(a);
295 PlatformThread::Join(b);
298 #if defined(THREAD_SANITIZER)
300 bool *shared = new bool(false);
301 TOOLS_SANITY_TEST_CONCURRENT_THREAD thread1(shared), thread2(shared);
302 RunInParallel(&thread1, &thread2);
303 EXPECT_TRUE(*shared);
305 // We're in a death test - crash.
312 #if defined(THREAD_SANITIZER)
313 // A data race detector should report an error in this test.
314 TEST(ToolsSanityTest, DataRace) {
315 // The suppression regexp must match that in base/debug/tsan_suppressions.cc.
316 EXPECT_DEATH(DataRace(), "1 race:base/tools_sanity_unittest.cc");
320 TEST(ToolsSanityTest, AnnotateBenignRace) {
322 ANNOTATE_BENIGN_RACE(&shared, "Intentional race - make sure doesn't show up");
323 TOOLS_SANITY_TEST_CONCURRENT_THREAD thread1(&shared), thread2(&shared);
324 RunInParallel(&thread1, &thread2);
328 TEST(ToolsSanityTest, AtomicsAreIgnored) {
329 base::subtle::Atomic32 shared = 0;
330 ReleaseStoreThread thread1(&shared);
331 AcquireLoadThread thread2(&shared);
332 RunInParallel(&thread1, &thread2);
333 EXPECT_EQ(kMagicValue, shared);
336 #if BUILDFLAG(CFI_ENFORCEMENT_TRAP)
338 #define CFI_ERROR_MSG "EXCEPTION_ILLEGAL_INSTRUCTION"
339 #elif defined(OS_ANDROID)
340 // TODO(pcc): Produce proper stack dumps on Android and test for the correct
342 #define CFI_ERROR_MSG "^$"
344 #define CFI_ERROR_MSG "ILL_ILLOPN"
346 #elif BUILDFLAG(CFI_ENFORCEMENT_DIAGNOSTIC)
347 #define CFI_ERROR_MSG "runtime error: control flow integrity check"
348 #endif // BUILDFLAG(CFI_ENFORCEMENT_TRAP || CFI_ENFORCEMENT_DIAGNOSTIC)
350 #if defined(CFI_ERROR_MSG)
354 virtual void f() { n_++; }
361 void f() override { n_--; }
366 void f() override { n_ += 2; }
369 NOINLINE void KillVptrAndCall(A *obj) {
370 *reinterpret_cast<void **>(obj) = 0;
374 TEST(ToolsSanityTest, BadVirtualCallNull) {
377 EXPECT_DEATH({ KillVptrAndCall(&a); KillVptrAndCall(&b); }, CFI_ERROR_MSG);
380 NOINLINE void OverwriteVptrAndCall(B *obj, A *vptr) {
381 *reinterpret_cast<void **>(obj) = *reinterpret_cast<void **>(vptr);
385 TEST(ToolsSanityTest, BadVirtualCallWrongType) {
389 EXPECT_DEATH({ OverwriteVptrAndCall(&b, &a); OverwriteVptrAndCall(&b, &c); },
393 // TODO(pcc): remove CFI_CAST_CHECK, see https://crbug.com/626794.
394 #if BUILDFLAG(CFI_CAST_CHECK)
395 TEST(ToolsSanityTest, BadDerivedCast) {
397 EXPECT_DEATH((void)(B*)&a, CFI_ERROR_MSG);
400 TEST(ToolsSanityTest, BadUnrelatedCast) {
410 EXPECT_DEATH((void)(B*)&a, CFI_ERROR_MSG);
412 #endif // BUILDFLAG(CFI_CAST_CHECK)
414 #endif // CFI_ERROR_MSG
417 #undef MAYBE_AccessesToNewMemory
418 #undef MAYBE_AccessesToMallocMemory
419 #undef MAYBE_ArrayDeletedWithoutBraces
420 #undef MAYBE_SingleElementDeletedWithBraces
421 #undef HARMFUL_ACCESS
422 #undef HARMFUL_ACCESS_IS_NOOP