[M73 Dev][Tizen] Fix compilation errors for TV profile
[platform/framework/web/chromium-efl.git] / base / tools_sanity_unittest.cc
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.
4 //
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.
8
9 #include <stddef.h>
10
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"
19
20 namespace base {
21
22 namespace {
23
24 const base::subtle::Atomic32 kMagicValue = 42;
25
26 // Helper for memory accesses that can potentially corrupt memory or cause a
27 // crash during a native run.
28 #if defined(ADDRESS_SANITIZER)
29 #if defined(OS_IOS)
30 // EXPECT_DEATH is not supported on IOS.
31 #define HARMFUL_ACCESS(action,error_regexp) do { action; } while (0)
32 #else
33 #define HARMFUL_ACCESS(action,error_regexp) EXPECT_DEATH(action,error_regexp)
34 #endif  // !OS_IOS
35 #else
36 #define HARMFUL_ACCESS(action, error_regexp)
37 #define HARMFUL_ACCESS_IS_NOOP
38 #endif
39
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.
45   if (*ptr == 64) {
46     VLOG(1) << "Uninit condition is true";
47   } else {
48     VLOG(1) << "Uninit condition is false";
49   }
50 }
51
52 void ReadUninitializedValue(char *ptr) {
53 #if defined(MEMORY_SANITIZER)
54   EXPECT_DEATH(DoReadUninitializedValue(ptr),
55                "use-of-uninitialized-value");
56 #else
57   DoReadUninitializedValue(ptr);
58 #endif
59 }
60
61 #ifndef HARMFUL_ACCESS_IS_NOOP
62 void ReadValueOutOfArrayBoundsLeft(char *ptr) {
63   char c = ptr[-2];
64   VLOG(1) << "Reading a byte out of bounds: " << c;
65 }
66
67 void ReadValueOutOfArrayBoundsRight(char *ptr, size_t size) {
68   char c = ptr[size + 1];
69   VLOG(1) << "Reading a byte out of bounds: " << c;
70 }
71
72 void WriteValueOutOfArrayBoundsLeft(char *ptr) {
73   ptr[-1] = kMagicValue;
74 }
75
76 void WriteValueOutOfArrayBoundsRight(char *ptr, size_t size) {
77   ptr[size] = kMagicValue;
78 }
79 #endif  // HARMFUL_ACCESS_IS_NOOP
80
81 void MakeSomeErrors(char *ptr, size_t size) {
82   ReadUninitializedValue(ptr);
83
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");
92 }
93
94 }  // namespace
95
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.
101 }
102
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
108 #else
109 #define MAYBE_AccessesToNewMemory AccessesToNewMemory
110 #define MAYBE_AccessesToMallocMemory AccessesToMallocMemory
111 #endif  // (defined(ADDRESS_SANITIZER) && defined(OS_IOS))
112
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))
117 // clause above.
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
123 #else
124 #define MAYBE_ArrayDeletedWithoutBraces ArrayDeletedWithoutBraces
125 #define MAYBE_SingleElementDeletedWithBraces SingleElementDeletedWithBraces
126 #endif  // defined(ADDRESS_SANITIZER)
127
128 TEST(ToolsSanityTest, MAYBE_AccessesToNewMemory) {
129   char *foo = new char[10];
130   MakeSomeErrors(foo, 10);
131   delete [] foo;
132   // Use after delete.
133   HARMFUL_ACCESS(foo[5] = 0, "heap-use-after-free");
134 }
135
136 TEST(ToolsSanityTest, MAYBE_AccessesToMallocMemory) {
137   char *foo = reinterpret_cast<char*>(malloc(10));
138   MakeSomeErrors(foo, 10);
139   free(foo);
140   // Use after free.
141   HARMFUL_ACCESS(foo[5] = 0, "heap-use-after-free");
142 }
143
144 #if defined(ADDRESS_SANITIZER)
145
146 static int* allocateArray() {
147   // Clang warns about the mismatched new[]/delete if they occur in the same
148   // function.
149   return new int[10];
150 }
151
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();
156   delete foo;
157 }
158 #endif
159
160 #if defined(ADDRESS_SANITIZER)
161 static int* allocateScalar() {
162   // Clang warns about the mismatched new/delete[] if they occur in the same
163   // function.
164   return new int;
165 }
166
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();
171   (void) foo;
172   delete [] foo;
173 }
174 #endif
175
176 #if defined(ADDRESS_SANITIZER)
177
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;
182   *zero = 0;
183 }
184
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.
189   int array[5];
190   // Work around the OOB warning reported by Clang.
191   int* volatile access = &array[5];
192   *access = 43;
193 }
194
195 namespace {
196 int g_asan_test_global_array[10];
197 }  // namespace
198
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.
203
204   // Work around the OOB warning reported by Clang.
205   int* volatile access = g_asan_test_global_array - 1;
206   *access = 43;
207 }
208
209 #ifndef HARMFUL_ACCESS_IS_NOOP
210 TEST(ToolsSanityTest, AsanHeapOverflow) {
211   HARMFUL_ACCESS(debug::AsanHeapOverflow() ,"to the right");
212 }
213
214 TEST(ToolsSanityTest, AsanHeapUnderflow) {
215   HARMFUL_ACCESS(debug::AsanHeapUnderflow(), "to the left");
216 }
217
218 TEST(ToolsSanityTest, AsanHeapUseAfterFree) {
219   HARMFUL_ACCESS(debug::AsanHeapUseAfterFree(), "heap-use-after-free");
220 }
221
222 #if defined(OS_WIN)
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(), "");
227 }
228
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(), "");
233 }
234 #endif  // OS_WIN
235 #endif  // !HARMFUL_ACCESS_IS_NOOP
236
237 #endif  // ADDRESS_SANITIZER
238
239 namespace {
240
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 {
244  public:
245   explicit TOOLS_SANITY_TEST_CONCURRENT_THREAD(bool *value) : value_(value) {}
246   ~TOOLS_SANITY_TEST_CONCURRENT_THREAD() override = default;
247   void ThreadMain() override {
248     *value_ = true;
249
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));
254   }
255  private:
256   bool *value_;
257 };
258
259 class ReleaseStoreThread : public PlatformThread::Delegate {
260  public:
261   explicit ReleaseStoreThread(base::subtle::Atomic32 *value) : value_(value) {}
262   ~ReleaseStoreThread() override = default;
263   void ThreadMain() override {
264     base::subtle::Release_Store(value_, kMagicValue);
265
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));
270   }
271  private:
272   base::subtle::Atomic32 *value_;
273 };
274
275 class AcquireLoadThread : public PlatformThread::Delegate {
276  public:
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_);
283   }
284  private:
285   base::subtle::Atomic32 *value_;
286 };
287
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);
295 }
296
297 #if defined(THREAD_SANITIZER)
298 void DataRace() {
299   bool *shared = new bool(false);
300   TOOLS_SANITY_TEST_CONCURRENT_THREAD thread1(shared), thread2(shared);
301   RunInParallel(&thread1, &thread2);
302   EXPECT_TRUE(*shared);
303   delete shared;
304   // We're in a death test - crash.
305   CHECK(0);
306 }
307 #endif
308
309 }  // namespace
310
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");
316 }
317 #endif
318
319 TEST(ToolsSanityTest, AnnotateBenignRace) {
320   bool shared = false;
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);
324   EXPECT_TRUE(shared);
325 }
326
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);
333 }
334
335 #if BUILDFLAG(CFI_ENFORCEMENT_TRAP)
336 #if defined(OS_WIN)
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
340 // si_code here.
341 #define CFI_ERROR_MSG "^$"
342 #else
343 #define CFI_ERROR_MSG "ILL_ILLOPN"
344 #endif
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)
348
349 #if defined(CFI_ERROR_MSG)
350 class A {
351  public:
352   A(): n_(0) {}
353   virtual void f() { n_++; }
354  protected:
355   int n_;
356 };
357
358 class B: public A {
359  public:
360   void f() override { n_--; }
361 };
362
363 class C: public B {
364  public:
365   void f() override { n_ += 2; }
366 };
367
368 NOINLINE void KillVptrAndCall(A *obj) {
369   *reinterpret_cast<void **>(obj) = 0;
370   obj->f();
371 }
372
373 TEST(ToolsSanityTest, BadVirtualCallNull) {
374   A a;
375   B b;
376   EXPECT_DEATH({ KillVptrAndCall(&a); KillVptrAndCall(&b); }, CFI_ERROR_MSG);
377 }
378
379 NOINLINE void OverwriteVptrAndCall(B *obj, A *vptr) {
380   *reinterpret_cast<void **>(obj) = *reinterpret_cast<void **>(vptr);
381   obj->f();
382 }
383
384 TEST(ToolsSanityTest, BadVirtualCallWrongType) {
385   A a;
386   B b;
387   C c;
388   EXPECT_DEATH({ OverwriteVptrAndCall(&b, &a); OverwriteVptrAndCall(&b, &c); },
389                CFI_ERROR_MSG);
390 }
391
392 // TODO(pcc): remove CFI_CAST_CHECK, see https://crbug.com/626794.
393 #if BUILDFLAG(CFI_CAST_CHECK)
394 TEST(ToolsSanityTest, BadDerivedCast) {
395   A a;
396   EXPECT_DEATH((void)(B*)&a, CFI_ERROR_MSG);
397 }
398
399 TEST(ToolsSanityTest, BadUnrelatedCast) {
400   class A {
401     virtual void f() {}
402   };
403
404   class B {
405     virtual void f() {}
406   };
407
408   A a;
409   EXPECT_DEATH((void)(B*)&a, CFI_ERROR_MSG);
410 }
411 #endif  // BUILDFLAG(CFI_CAST_CHECK)
412
413 #endif  // CFI_ERROR_MSG
414
415 #undef 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
422
423 }  // namespace base