asan_interface_test.cc revision 4b6eec3b3e1fd8ed26aa7ed684c16bc87f0ed625
1//===-- asan_interface_test.cc ----------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file is a part of AddressSanitizer, an address sanity checker.
11//
12//===----------------------------------------------------------------------===//
13#include <pthread.h>
14#include <stdio.h>
15#include <string.h>
16
17#include <vector>
18
19#include "asan_test_config.h"
20#include "asan_test_utils.h"
21#include "asan_interface.h"
22
23TEST(AddressSanitizerInterface, GetEstimatedAllocatedSize) {
24  EXPECT_EQ(1, __asan_get_estimated_allocated_size(0));
25  const size_t sizes[] = { 1, 30, 1<<30 };
26  for (size_t i = 0; i < 3; i++) {
27    EXPECT_EQ(sizes[i], __asan_get_estimated_allocated_size(sizes[i]));
28  }
29}
30
31static const char* kGetAllocatedSizeErrorMsg =
32  "attempting to call __asan_get_allocated_size()";
33
34TEST(AddressSanitizerInterface, GetAllocatedSizeAndOwnershipTest) {
35  const size_t kArraySize = 100;
36  char *array = Ident((char*)malloc(kArraySize));
37  int *int_ptr = Ident(new int);
38
39  // Allocated memory is owned by allocator. Allocated size should be
40  // equal to requested size.
41  EXPECT_EQ(true, __asan_get_ownership(array));
42  EXPECT_EQ(kArraySize, __asan_get_allocated_size(array));
43  EXPECT_EQ(true, __asan_get_ownership(int_ptr));
44  EXPECT_EQ(sizeof(int), __asan_get_allocated_size(int_ptr));
45
46  // We cannot call GetAllocatedSize from the memory we didn't map,
47  // and from the interior pointers (not returned by previous malloc).
48  void *wild_addr = (void*)0x1;
49  EXPECT_EQ(false, __asan_get_ownership(wild_addr));
50  EXPECT_DEATH(__asan_get_allocated_size(wild_addr), kGetAllocatedSizeErrorMsg);
51  EXPECT_EQ(false, __asan_get_ownership(array + kArraySize / 2));
52  EXPECT_DEATH(__asan_get_allocated_size(array + kArraySize / 2),
53               kGetAllocatedSizeErrorMsg);
54
55  // NULL is not owned, but is a valid argument for __asan_get_allocated_size().
56  EXPECT_EQ(false, __asan_get_ownership(NULL));
57  EXPECT_EQ(0, __asan_get_allocated_size(NULL));
58
59  // When memory is freed, it's not owned, and call to GetAllocatedSize
60  // is forbidden.
61  free(array);
62  EXPECT_EQ(false, __asan_get_ownership(array));
63  EXPECT_DEATH(__asan_get_allocated_size(array), kGetAllocatedSizeErrorMsg);
64
65  delete int_ptr;
66}
67
68TEST(AddressSanitizerInterface, GetCurrentAllocatedBytesTest) {
69  size_t before_malloc, after_malloc, after_free;
70  char *array;
71  const size_t kMallocSize = 100;
72  before_malloc = __asan_get_current_allocated_bytes();
73
74  array = Ident((char*)malloc(kMallocSize));
75  after_malloc = __asan_get_current_allocated_bytes();
76  EXPECT_EQ(before_malloc + kMallocSize, after_malloc);
77
78  free(array);
79  after_free = __asan_get_current_allocated_bytes();
80  EXPECT_EQ(before_malloc, after_free);
81}
82
83static void DoDoubleFree() {
84  int *x = Ident(new int);
85  delete Ident(x);
86  delete Ident(x);
87}
88
89// This test is run in a separate process, so that large malloced
90// chunk won't remain in the free lists after the test.
91// Note: use ASSERT_* instead of EXPECT_* here.
92static void RunGetHeapSizeTestAndDie() {
93  size_t old_heap_size, new_heap_size, heap_growth;
94  // We unlikely have have chunk of this size in free list.
95  static const size_t kLargeMallocSize = 1 << 29;  // 512M
96  old_heap_size = __asan_get_heap_size();
97  fprintf(stderr, "allocating %zu bytes:\n", kLargeMallocSize);
98  free(Ident(malloc(kLargeMallocSize)));
99  new_heap_size = __asan_get_heap_size();
100  heap_growth = new_heap_size - old_heap_size;
101  fprintf(stderr, "heap growth after first malloc: %zu\n", heap_growth);
102  ASSERT_GE(heap_growth, kLargeMallocSize);
103  ASSERT_LE(heap_growth, 2 * kLargeMallocSize);
104
105  // Now large chunk should fall into free list, and can be
106  // allocated without increasing heap size.
107  old_heap_size = new_heap_size;
108  free(Ident(malloc(kLargeMallocSize)));
109  heap_growth = __asan_get_heap_size() - old_heap_size;
110  fprintf(stderr, "heap growth after second malloc: %zu\n", heap_growth);
111  ASSERT_LT(heap_growth, kLargeMallocSize);
112
113  // Test passed. Now die with expected double-free.
114  DoDoubleFree();
115}
116
117TEST(AddressSanitizerInterface, GetHeapSizeTest) {
118  EXPECT_DEATH(RunGetHeapSizeTestAndDie(), "double-free");
119}
120
121// Note: use ASSERT_* instead of EXPECT_* here.
122static void DoLargeMallocForGetFreeBytesTestAndDie() {
123  size_t old_free_bytes, new_free_bytes;
124  static const size_t kLargeMallocSize = 1 << 29;  // 512M
125  // If we malloc and free a large memory chunk, it will not fall
126  // into quarantine and will be available for future requests.
127  old_free_bytes = __asan_get_free_bytes();
128  fprintf(stderr, "allocating %zu bytes:\n", kLargeMallocSize);
129  fprintf(stderr, "free bytes before malloc: %zu\n", old_free_bytes);
130  free(Ident(malloc(kLargeMallocSize)));
131  new_free_bytes = __asan_get_free_bytes();
132  fprintf(stderr, "free bytes after malloc and free: %zu\n", new_free_bytes);
133  ASSERT_GE(new_free_bytes, old_free_bytes + kLargeMallocSize);
134  // Test passed.
135  DoDoubleFree();
136}
137
138TEST(AddressSanitizerInterface, GetFreeBytesTest) {
139  static const size_t kNumOfChunks = 100;
140  static const size_t kChunkSize = 100;
141  char *chunks[kNumOfChunks];
142  size_t i;
143  size_t old_free_bytes, new_free_bytes;
144  // Allocate a small chunk. Now allocator probably has a lot of these
145  // chunks to fulfill future requests. So, future requests will decrease
146  // the number of free bytes.
147  chunks[0] = Ident((char*)malloc(kChunkSize));
148  old_free_bytes = __asan_get_free_bytes();
149  for (i = 1; i < kNumOfChunks; i++) {
150    chunks[i] = Ident((char*)malloc(kChunkSize));
151    new_free_bytes = __asan_get_free_bytes();
152    EXPECT_LT(new_free_bytes, old_free_bytes);
153    old_free_bytes = new_free_bytes;
154  }
155  EXPECT_DEATH(DoLargeMallocForGetFreeBytesTestAndDie(), "double-free");
156}
157
158static const size_t kManyThreadsMallocSizes[] = {5, 1UL<<10, 1UL<<20, 357};
159static const size_t kManyThreadsIterations = 250;
160static const size_t kManyThreadsNumThreads = 200;
161
162void *ManyThreadsWithStatsWorker(void *arg) {
163  for (size_t iter = 0; iter < kManyThreadsIterations; iter++) {
164    for (size_t size_index = 0; size_index < 4; size_index++) {
165      free(Ident(malloc(kManyThreadsMallocSizes[size_index])));
166    }
167  }
168  return 0;
169}
170
171TEST(AddressSanitizerInterface, ManyThreadsWithStatsStressTest) {
172  size_t before_test, after_test, i;
173  pthread_t threads[kManyThreadsNumThreads];
174  before_test = __asan_get_current_allocated_bytes();
175  for (i = 0; i < kManyThreadsNumThreads; i++) {
176    pthread_create(&threads[i], 0,
177                   (void* (*)(void *x))ManyThreadsWithStatsWorker, (void*)i);
178  }
179  for (i = 0; i < kManyThreadsNumThreads; i++) {
180    pthread_join(threads[i], 0);
181  }
182  after_test = __asan_get_current_allocated_bytes();
183  // ASan stats also reflect memory usage of internal ASan RTL structs,
184  // so we can't check for equality here.
185  EXPECT_LT(after_test, before_test + (1UL<<20));
186}
187
188TEST(AddressSanitizerInterface, ExitCode) {
189  int original_exit_code = __asan_set_error_exit_code(7);
190  EXPECT_EXIT(DoDoubleFree(), ::testing::ExitedWithCode(7), "");
191  EXPECT_EQ(7, __asan_set_error_exit_code(8));
192  EXPECT_EXIT(DoDoubleFree(), ::testing::ExitedWithCode(8), "");
193  EXPECT_EQ(8, __asan_set_error_exit_code(original_exit_code));
194  EXPECT_EXIT(DoDoubleFree(),
195              ::testing::ExitedWithCode(original_exit_code), "");
196}
197
198static void MyDeathCallback() {
199  fprintf(stderr, "MyDeathCallback\n");
200}
201
202TEST(AddressSanitizerInterface, DeathCallbackTest) {
203  __asan_set_death_callback(MyDeathCallback);
204  EXPECT_DEATH(DoDoubleFree(), "MyDeathCallback");
205  __asan_set_death_callback(NULL);
206}
207
208static const char* kUseAfterPoisonErrorMessage = "use-after-poison";
209
210#define ACCESS(ptr, offset) Ident(*(ptr + offset))
211
212#define DIE_ON_ACCESS(ptr, offset) \
213    EXPECT_DEATH(Ident(*(ptr + offset)), kUseAfterPoisonErrorMessage)
214
215TEST(AddressSanitizerInterface, SimplePoisonMemoryRegionTest) {
216  char *array = Ident((char*)malloc(120));
217  // poison array[40..80)
218  ASAN_POISON_MEMORY_REGION(array + 40, 40);
219  ACCESS(array, 39);
220  ACCESS(array, 80);
221  DIE_ON_ACCESS(array, 40);
222  DIE_ON_ACCESS(array, 60);
223  DIE_ON_ACCESS(array, 79);
224  ASAN_UNPOISON_MEMORY_REGION(array + 40, 40);
225  // access previously poisoned memory.
226  ACCESS(array, 40);
227  ACCESS(array, 79);
228  free(array);
229}
230
231TEST(AddressSanitizerInterface, OverlappingPoisonMemoryRegionTest) {
232  char *array = Ident((char*)malloc(120));
233  // Poison [0..40) and [80..120)
234  ASAN_POISON_MEMORY_REGION(array, 40);
235  ASAN_POISON_MEMORY_REGION(array + 80, 40);
236  DIE_ON_ACCESS(array, 20);
237  ACCESS(array, 60);
238  DIE_ON_ACCESS(array, 100);
239  // Poison whole array - [0..120)
240  ASAN_POISON_MEMORY_REGION(array, 120);
241  DIE_ON_ACCESS(array, 60);
242  // Unpoison [24..96)
243  ASAN_UNPOISON_MEMORY_REGION(array + 24, 72);
244  DIE_ON_ACCESS(array, 23);
245  ACCESS(array, 24);
246  ACCESS(array, 60);
247  ACCESS(array, 95);
248  DIE_ON_ACCESS(array, 96);
249  free(array);
250}
251
252TEST(AddressSanitizerInterface, PushAndPopWithPoisoningTest) {
253  // Vector of capacity 20
254  char *vec = Ident((char*)malloc(20));
255  ASAN_POISON_MEMORY_REGION(vec, 20);
256  for (size_t i = 0; i < 7; i++) {
257    // Simulate push_back.
258    ASAN_UNPOISON_MEMORY_REGION(vec + i, 1);
259    ACCESS(vec, i);
260    DIE_ON_ACCESS(vec, i + 1);
261  }
262  for (size_t i = 7; i > 0; i--) {
263    // Simulate pop_back.
264    ASAN_POISON_MEMORY_REGION(vec + i - 1, 1);
265    DIE_ON_ACCESS(vec, i - 1);
266    if (i > 1) ACCESS(vec, i - 2);
267  }
268  free(vec);
269}
270
271// Make sure that each aligned block of size "2^granularity" doesn't have
272// "true" value before "false" value.
273static void MakeShadowValid(bool *shadow, int length, int granularity) {
274  bool can_be_poisoned = true;
275  for (int i = length - 1; i >= 0; i--) {
276    can_be_poisoned &= shadow[i];
277    shadow[i] &= can_be_poisoned;
278    if (i % (1 << granularity) == 0) {
279      can_be_poisoned = true;
280    }
281  }
282}
283
284TEST(AddressSanitizerInterface, PoisoningStressTest) {
285  const size_t kSize = 24;
286  bool expected[kSize];
287  char *arr = Ident((char*)malloc(kSize));
288  for (size_t l1 = 0; l1 < kSize; l1++) {
289    for (size_t s1 = 1; l1 + s1 <= kSize; s1++) {
290      for (size_t l2 = 0; l2 < kSize; l2++) {
291        for (size_t s2 = 1; l2 + s2 <= kSize; s2++) {
292          // Poison [l1, l1+s1), [l2, l2+s2) and check result.
293          ASAN_UNPOISON_MEMORY_REGION(arr, kSize);
294          ASAN_POISON_MEMORY_REGION(arr + l1, s1);
295          ASAN_POISON_MEMORY_REGION(arr + l2, s2);
296          memset(expected, false, kSize);
297          memset(expected + l1, true, s1);
298          MakeShadowValid(expected, 24, /*granularity*/ 3);
299          memset(expected + l2, true, s2);
300          MakeShadowValid(expected, 24, /*granularity*/ 3);
301          for (size_t i = 0; i < kSize; i++) {
302            ASSERT_EQ(expected[i], __asan_address_is_poisoned(arr + i));
303          }
304          // Unpoison [l1, l1+s1) and [l2, l2+s2) and check result.
305          ASAN_POISON_MEMORY_REGION(arr, kSize);
306          ASAN_UNPOISON_MEMORY_REGION(arr + l1, s1);
307          ASAN_UNPOISON_MEMORY_REGION(arr + l2, s2);
308          memset(expected, true, kSize);
309          memset(expected + l1, false, s1);
310          MakeShadowValid(expected, 24, /*granularity*/ 3);
311          memset(expected + l2, false, s2);
312          MakeShadowValid(expected, 24, /*granularity*/ 3);
313          for (size_t i = 0; i < kSize; i++) {
314            ASSERT_EQ(expected[i], __asan_address_is_poisoned(arr + i));
315          }
316        }
317      }
318    }
319  }
320}
321
322static const char *kInvalidPoisonMessage = "invalid-poison-memory-range";
323static const char *kInvalidUnpoisonMessage = "invalid-unpoison-memory-range";
324
325TEST(AddressSanitizerInterface, DISABLED_InvalidPoisonAndUnpoisonCallsTest) {
326  char *array = Ident((char*)malloc(120));
327  ASAN_UNPOISON_MEMORY_REGION(array, 120);
328  // Try to unpoison not owned memory
329  EXPECT_DEATH(ASAN_UNPOISON_MEMORY_REGION(array, 121),
330               kInvalidUnpoisonMessage);
331  EXPECT_DEATH(ASAN_UNPOISON_MEMORY_REGION(array - 1, 120),
332               kInvalidUnpoisonMessage);
333
334  ASAN_POISON_MEMORY_REGION(array, 120);
335  // Try to poison not owned memory.
336  EXPECT_DEATH(ASAN_POISON_MEMORY_REGION(array, 121), kInvalidPoisonMessage);
337  EXPECT_DEATH(ASAN_POISON_MEMORY_REGION(array - 1, 120),
338               kInvalidPoisonMessage);
339  free(array);
340}
341
342static void ErrorReportCallbackOneToZ(const char *report) {
343  int len = strlen(report);
344  char *dup = (char*)malloc(len);
345  strcpy(dup, report);
346  for (int i = 0; i < len; i++) {
347    if (dup[i] == '1') dup[i] = 'Z';
348  }
349  write(2, dup, len);
350  free(dup);
351}
352
353TEST(AddressSanitizerInterface, SetErrorReportCallbackTest) {
354  __asan_set_error_report_callback(ErrorReportCallbackOneToZ);
355  char *array = Ident((char*)malloc(120));
356  EXPECT_DEATH(ACCESS(array, 120), "size Z");
357  __asan_set_error_report_callback(NULL);
358}
359
360TEST(AddressSanitizerInterface, GetOwnershipStressTest) {
361  std::vector<char *> pointers;
362  std::vector<size_t> sizes;
363  const size_t kNumMallocs =
364      (__WORDSIZE <= 32 || ASAN_LOW_MEMORY) ? 1 << 10 : 1 << 14;
365  for (size_t i = 0; i < kNumMallocs; i++) {
366    size_t size = i * 100 + 1;
367    pointers.push_back((char*)malloc(size));
368    sizes.push_back(size);
369  }
370  for (size_t i = 0; i < 4000000; i++) {
371    EXPECT_FALSE(__asan_get_ownership(&pointers));
372    EXPECT_FALSE(__asan_get_ownership((void*)0x1234));
373    size_t idx = i % kNumMallocs;
374    EXPECT_TRUE(__asan_get_ownership(pointers[idx]));
375    EXPECT_EQ(sizes[idx], __asan_get_allocated_size(pointers[idx]));
376  }
377  for (size_t i = 0, n = pointers.size(); i < n; i++)
378    free(pointers[i]);
379}
380