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/third_party/dynamic_annotations/dynamic_annotations.h"
16 #include "base/threading/thread.h"
17 #include "build/build_config.h"
18 #include "testing/gtest/include/gtest/gtest.h"
24 const base::subtle::Atomic32 kMagicValue = 42;
26 // Helper for memory accesses that can potentially corrupt memory or cause a
27 // crash during a native run.
28 #if defined(ADDRESS_SANITIZER)
30 // EXPECT_DEATH is not supported on IOS.
31 #define HARMFUL_ACCESS(action,error_regexp) do { action; } while (0)
33 #define HARMFUL_ACCESS(action,error_regexp) EXPECT_DEATH(action,error_regexp)
36 #define HARMFUL_ACCESS(action, error_regexp)
37 #define HARMFUL_ACCESS_IS_NOOP
40 void DoReadUninitializedValue(char *ptr) {
41 // Comparison with 64 is to prevent clang from optimizing away the
42 // jump -- valgrind only catches jumps and conditional moves, but clang uses
43 // the borrow flag if the condition is just `*ptr == '\0'`. We no longer
44 // support valgrind, but this constant should be fine to keep as-is.
46 VLOG(1) << "Uninit condition is true";
48 VLOG(1) << "Uninit condition is false";
52 void ReadUninitializedValue(char *ptr) {
53 #if defined(MEMORY_SANITIZER)
54 EXPECT_DEATH(DoReadUninitializedValue(ptr),
55 "use-of-uninitialized-value");
57 DoReadUninitializedValue(ptr);
61 #ifndef HARMFUL_ACCESS_IS_NOOP
62 void ReadValueOutOfArrayBoundsLeft(char *ptr) {
64 VLOG(1) << "Reading a byte out of bounds: " << c;
67 void ReadValueOutOfArrayBoundsRight(char *ptr, size_t size) {
68 char c = ptr[size + 1];
69 VLOG(1) << "Reading a byte out of bounds: " << c;
72 void WriteValueOutOfArrayBoundsLeft(char *ptr) {
73 ptr[-1] = kMagicValue;
76 void WriteValueOutOfArrayBoundsRight(char *ptr, size_t size) {
77 ptr[size] = kMagicValue;
79 #endif // HARMFUL_ACCESS_IS_NOOP
81 void MakeSomeErrors(char *ptr, size_t size) {
82 ReadUninitializedValue(ptr);
84 HARMFUL_ACCESS(ReadValueOutOfArrayBoundsLeft(ptr),
85 "2 bytes to the left");
86 HARMFUL_ACCESS(ReadValueOutOfArrayBoundsRight(ptr, size),
87 "1 bytes to the right");
88 HARMFUL_ACCESS(WriteValueOutOfArrayBoundsLeft(ptr),
89 "1 bytes to the left");
90 HARMFUL_ACCESS(WriteValueOutOfArrayBoundsRight(ptr, size),
91 "0 bytes to the right");
96 // A memory leak detector should report an error in this test.
97 TEST(ToolsSanityTest, MemoryLeak) {
98 // Without the |volatile|, clang optimizes away the next two lines.
99 int* volatile leak = new int[256]; // Leak some memory intentionally.
100 leak[4] = 1; // Make sure the allocated memory is used.
103 #if (defined(ADDRESS_SANITIZER) && defined(OS_IOS))
104 // Because iOS doesn't support death tests, each of the following tests will
105 // crash the whole program under Asan.
106 #define MAYBE_AccessesToNewMemory DISABLED_AccessesToNewMemory
107 #define MAYBE_AccessesToMallocMemory DISABLED_AccessesToMallocMemory
109 #define MAYBE_AccessesToNewMemory AccessesToNewMemory
110 #define MAYBE_AccessesToMallocMemory AccessesToMallocMemory
111 #endif // (defined(ADDRESS_SANITIZER) && defined(OS_IOS))
113 // The following tests pass with Clang r170392, but not r172454, which
114 // makes AddressSanitizer detect errors in them. We disable these tests under
115 // AddressSanitizer until we fully switch to Clang r172454. After that the
116 // tests should be put back under the (defined(OS_IOS) || defined(OS_WIN))
118 // See also http://crbug.com/172614.
119 #if defined(ADDRESS_SANITIZER)
120 #define MAYBE_SingleElementDeletedWithBraces \
121 DISABLED_SingleElementDeletedWithBraces
122 #define MAYBE_ArrayDeletedWithoutBraces DISABLED_ArrayDeletedWithoutBraces
124 #define MAYBE_ArrayDeletedWithoutBraces ArrayDeletedWithoutBraces
125 #define MAYBE_SingleElementDeletedWithBraces SingleElementDeletedWithBraces
126 #endif // defined(ADDRESS_SANITIZER)
128 TEST(ToolsSanityTest, MAYBE_AccessesToNewMemory) {
129 char *foo = new char[10];
130 MakeSomeErrors(foo, 10);
133 HARMFUL_ACCESS(foo[5] = 0, "heap-use-after-free");
136 TEST(ToolsSanityTest, MAYBE_AccessesToMallocMemory) {
137 char *foo = reinterpret_cast<char*>(malloc(10));
138 MakeSomeErrors(foo, 10);
141 HARMFUL_ACCESS(foo[5] = 0, "heap-use-after-free");
144 #if defined(ADDRESS_SANITIZER)
146 static int* allocateArray() {
147 // Clang warns about the mismatched new[]/delete if they occur in the same
152 // This test may corrupt memory if not compiled with AddressSanitizer.
153 TEST(ToolsSanityTest, MAYBE_ArrayDeletedWithoutBraces) {
154 // Without the |volatile|, clang optimizes away the next two lines.
155 int* volatile foo = allocateArray();
160 #if defined(ADDRESS_SANITIZER)
161 static int* allocateScalar() {
162 // Clang warns about the mismatched new/delete[] if they occur in the same
167 // This test may corrupt memory if not compiled with AddressSanitizer.
168 TEST(ToolsSanityTest, MAYBE_SingleElementDeletedWithBraces) {
169 // Without the |volatile|, clang optimizes away the next two lines.
170 int* volatile foo = allocateScalar();
176 #if defined(ADDRESS_SANITIZER)
178 TEST(ToolsSanityTest, DISABLED_AddressSanitizerNullDerefCrashTest) {
179 // Intentionally crash to make sure AddressSanitizer is running.
180 // This test should not be ran on bots.
181 int* volatile zero = NULL;
185 TEST(ToolsSanityTest, DISABLED_AddressSanitizerLocalOOBCrashTest) {
186 // Intentionally crash to make sure AddressSanitizer is instrumenting
187 // the local variables.
188 // This test should not be ran on bots.
190 // Work around the OOB warning reported by Clang.
191 int* volatile access = &array[5];
196 int g_asan_test_global_array[10];
199 TEST(ToolsSanityTest, DISABLED_AddressSanitizerGlobalOOBCrashTest) {
200 // Intentionally crash to make sure AddressSanitizer is instrumenting
201 // the global variables.
202 // This test should not be ran on bots.
204 // Work around the OOB warning reported by Clang.
205 int* volatile access = g_asan_test_global_array - 1;
209 #ifndef HARMFUL_ACCESS_IS_NOOP
210 TEST(ToolsSanityTest, AsanHeapOverflow) {
211 HARMFUL_ACCESS(debug::AsanHeapOverflow() ,"to the right");
214 TEST(ToolsSanityTest, AsanHeapUnderflow) {
215 HARMFUL_ACCESS(debug::AsanHeapUnderflow(), "to the left");
218 TEST(ToolsSanityTest, AsanHeapUseAfterFree) {
219 HARMFUL_ACCESS(debug::AsanHeapUseAfterFree(), "heap-use-after-free");
223 // The ASAN runtime doesn't detect heap corruption, this needs fixing before
224 // ASAN builds can ship to the wild. See https://crbug.com/818747.
225 TEST(ToolsSanityTest, DISABLED_AsanCorruptHeapBlock) {
226 HARMFUL_ACCESS(debug::AsanCorruptHeapBlock(), "");
229 TEST(ToolsSanityTest, DISABLED_AsanCorruptHeap) {
230 // This test will kill the process by raising an exception, there's no
231 // particular string to look for in the stack trace.
232 EXPECT_DEATH(debug::AsanCorruptHeap(), "");
235 #endif // !HARMFUL_ACCESS_IS_NOOP
237 #endif // ADDRESS_SANITIZER
241 // We use caps here just to ensure that the method name doesn't interfere with
242 // the wildcarded suppressions.
243 class TOOLS_SANITY_TEST_CONCURRENT_THREAD : public PlatformThread::Delegate {
245 explicit TOOLS_SANITY_TEST_CONCURRENT_THREAD(bool *value) : value_(value) {}
246 ~TOOLS_SANITY_TEST_CONCURRENT_THREAD() override = default;
247 void ThreadMain() override {
250 // Sleep for a few milliseconds so the two threads are more likely to live
251 // simultaneously. Otherwise we may miss the report due to mutex
252 // lock/unlock's inside thread creation code in pure-happens-before mode...
253 PlatformThread::Sleep(TimeDelta::FromMilliseconds(100));
259 class ReleaseStoreThread : public PlatformThread::Delegate {
261 explicit ReleaseStoreThread(base::subtle::Atomic32 *value) : value_(value) {}
262 ~ReleaseStoreThread() override = default;
263 void ThreadMain() override {
264 base::subtle::Release_Store(value_, kMagicValue);
266 // Sleep for a few milliseconds so the two threads are more likely to live
267 // simultaneously. Otherwise we may miss the report due to mutex
268 // lock/unlock's inside thread creation code in pure-happens-before mode...
269 PlatformThread::Sleep(TimeDelta::FromMilliseconds(100));
272 base::subtle::Atomic32 *value_;
275 class AcquireLoadThread : public PlatformThread::Delegate {
277 explicit AcquireLoadThread(base::subtle::Atomic32 *value) : value_(value) {}
278 ~AcquireLoadThread() override = default;
279 void ThreadMain() override {
280 // Wait for the other thread to make Release_Store
281 PlatformThread::Sleep(TimeDelta::FromMilliseconds(100));
282 base::subtle::Acquire_Load(value_);
285 base::subtle::Atomic32 *value_;
288 void RunInParallel(PlatformThread::Delegate *d1, PlatformThread::Delegate *d2) {
289 PlatformThreadHandle a;
290 PlatformThreadHandle b;
291 PlatformThread::Create(0, d1, &a);
292 PlatformThread::Create(0, d2, &b);
293 PlatformThread::Join(a);
294 PlatformThread::Join(b);
297 #if defined(THREAD_SANITIZER)
299 bool *shared = new bool(false);
300 TOOLS_SANITY_TEST_CONCURRENT_THREAD thread1(shared), thread2(shared);
301 RunInParallel(&thread1, &thread2);
302 EXPECT_TRUE(*shared);
304 // We're in a death test - crash.
311 #if defined(THREAD_SANITIZER)
312 // A data race detector should report an error in this test.
313 TEST(ToolsSanityTest, DataRace) {
314 // The suppression regexp must match that in base/debug/tsan_suppressions.cc.
315 EXPECT_DEATH(DataRace(), "1 race:base/tools_sanity_unittest.cc");
319 TEST(ToolsSanityTest, AnnotateBenignRace) {
321 ANNOTATE_BENIGN_RACE(&shared, "Intentional race - make sure doesn't show up");
322 TOOLS_SANITY_TEST_CONCURRENT_THREAD thread1(&shared), thread2(&shared);
323 RunInParallel(&thread1, &thread2);
327 TEST(ToolsSanityTest, AtomicsAreIgnored) {
328 base::subtle::Atomic32 shared = 0;
329 ReleaseStoreThread thread1(&shared);
330 AcquireLoadThread thread2(&shared);
331 RunInParallel(&thread1, &thread2);
332 EXPECT_EQ(kMagicValue, shared);
335 #if BUILDFLAG(CFI_ENFORCEMENT_TRAP)
337 #define CFI_ERROR_MSG "EXCEPTION_ILLEGAL_INSTRUCTION"
338 #elif defined(OS_ANDROID)
339 // TODO(pcc): Produce proper stack dumps on Android and test for the correct
341 #define CFI_ERROR_MSG "^$"
343 #define CFI_ERROR_MSG "ILL_ILLOPN"
345 #elif BUILDFLAG(CFI_ENFORCEMENT_DIAGNOSTIC)
346 #define CFI_ERROR_MSG "runtime error: control flow integrity check"
347 #endif // BUILDFLAG(CFI_ENFORCEMENT_TRAP || CFI_ENFORCEMENT_DIAGNOSTIC)
349 #if defined(CFI_ERROR_MSG)
353 virtual void f() { n_++; }
360 void f() override { n_--; }
365 void f() override { n_ += 2; }
368 NOINLINE void KillVptrAndCall(A *obj) {
369 *reinterpret_cast<void **>(obj) = 0;
373 TEST(ToolsSanityTest, BadVirtualCallNull) {
376 EXPECT_DEATH({ KillVptrAndCall(&a); KillVptrAndCall(&b); }, CFI_ERROR_MSG);
379 NOINLINE void OverwriteVptrAndCall(B *obj, A *vptr) {
380 *reinterpret_cast<void **>(obj) = *reinterpret_cast<void **>(vptr);
384 TEST(ToolsSanityTest, BadVirtualCallWrongType) {
388 EXPECT_DEATH({ OverwriteVptrAndCall(&b, &a); OverwriteVptrAndCall(&b, &c); },
392 // TODO(pcc): remove CFI_CAST_CHECK, see https://crbug.com/626794.
393 #if BUILDFLAG(CFI_CAST_CHECK)
394 TEST(ToolsSanityTest, BadDerivedCast) {
396 EXPECT_DEATH((void)(B*)&a, CFI_ERROR_MSG);
399 TEST(ToolsSanityTest, BadUnrelatedCast) {
409 EXPECT_DEATH((void)(B*)&a, CFI_ERROR_MSG);
411 #endif // BUILDFLAG(CFI_CAST_CHECK)
413 #endif // CFI_ERROR_MSG
416 #undef MAYBE_AccessesToNewMemory
417 #undef MAYBE_AccessesToMallocMemory
418 #undef MAYBE_ArrayDeletedWithoutBraces
419 #undef MAYBE_SingleElementDeletedWithBraces
420 #undef HARMFUL_ACCESS
421 #undef HARMFUL_ACCESS_IS_NOOP