1//===-- sanitizer_allocator_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 ThreadSanitizer/AddressSanitizer runtime.
11//
12//===----------------------------------------------------------------------===//
13#include "sanitizer_common/sanitizer_common.h"
14#include "gtest/gtest.h"
15#include <stdlib.h>
16
17namespace __sanitizer {
18
19TEST(Allocator, Basic) {
20  char *p = (char*)InternalAlloc(10);
21  EXPECT_NE(p, (char*)0);
22  char *p2 = (char*)InternalAlloc(20);
23  EXPECT_NE(p2, (char*)0);
24  EXPECT_NE(p2, p);
25  for (int i = 0; i < 10; i++) {
26    p[i] = 42;
27    EXPECT_EQ(p, InternalAllocBlock(p + i));
28  }
29  for (int i = 0; i < 20; i++) {
30    ((char*)p2)[i] = 42;
31    EXPECT_EQ(p2, InternalAllocBlock(p2 + i));
32  }
33  InternalFree(p);
34  InternalFree(p2);
35}
36
37TEST(Allocator, Stress) {
38  const int kCount = 1000;
39  char *ptrs[kCount];
40  unsigned rnd = 42;
41  for (int i = 0; i < kCount; i++) {
42    uptr sz = rand_r(&rnd) % 1000;
43    char *p = (char*)InternalAlloc(sz);
44    EXPECT_NE(p, (char*)0);
45    for (uptr j = 0; j < sz; j++) {
46      p[j] = 42;
47      EXPECT_EQ(p, InternalAllocBlock(p + j));
48    }
49    ptrs[i] = p;
50  }
51  for (int i = 0; i < kCount; i++) {
52    InternalFree(ptrs[i]);
53  }
54}
55
56TEST(Allocator, ScopedBuffer) {
57  const int kSize = 512;
58  {
59    InternalScopedBuffer<int> int_buf(kSize);
60    EXPECT_EQ(sizeof(int) * kSize, int_buf.size());  // NOLINT
61  }
62  InternalScopedBuffer<char> char_buf(kSize);
63  EXPECT_EQ(sizeof(char) * kSize, char_buf.size());  // NOLINT
64  memset(char_buf.data(), 'c', kSize);
65  for (int i = 0; i < kSize; i++) {
66    EXPECT_EQ('c', char_buf[i]);
67  }
68}
69
70}  // namespace __sanitizer
71