1// Copyright (c) 2013 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#include <fcntl.h>
6#include <stddef.h>
7#include <stdio.h>
8#include <stdlib.h>
9#include <string.h>
10#include <sys/stat.h>
11#include <sys/types.h>
12
13#include <algorithm>
14#include <limits>
15
16#include "base/files/file_util.h"
17#include "base/logging.h"
18#include "base/memory/scoped_ptr.h"
19#include "build/build_config.h"
20#include "testing/gtest/include/gtest/gtest.h"
21
22#if defined(OS_POSIX)
23#include <sys/mman.h>
24#include <unistd.h>
25#endif
26
27using std::nothrow;
28using std::numeric_limits;
29
30namespace {
31
32// This function acts as a compiler optimization barrier. We use it to
33// prevent the compiler from making an expression a compile-time constant.
34// We also use it so that the compiler doesn't discard certain return values
35// as something we don't need (see the comment with calloc below).
36template <typename Type>
37NOINLINE Type HideValueFromCompiler(volatile Type value) {
38#if defined(__GNUC__)
39  // In a GCC compatible compiler (GCC or Clang), make this compiler barrier
40  // more robust than merely using "volatile".
41  __asm__ volatile ("" : "+r" (value));
42#endif  // __GNUC__
43  return value;
44}
45
46// Tcmalloc and Windows allocator shim support setting malloc limits.
47// - NO_TCMALLOC (should be defined if compiled with use_allocator!="tcmalloc")
48// - ADDRESS_SANITIZER and SYZYASAN because they have their own memory allocator
49// - IOS does not use tcmalloc
50// - OS_MACOSX does not use tcmalloc
51// - Windows allocator shim defines ALLOCATOR_SHIM
52#if (!defined(NO_TCMALLOC) || defined(ALLOCATOR_SHIM)) &&                     \
53    !defined(ADDRESS_SANITIZER) && !defined(OS_IOS) && !defined(OS_MACOSX) && \
54    !defined(SYZYASAN)
55#define MALLOC_OVERFLOW_TEST(function) function
56#else
57#define MALLOC_OVERFLOW_TEST(function) DISABLED_##function
58#endif
59
60#if defined(OS_LINUX) && defined(__x86_64__)
61// Detect runtime TCMalloc bypasses.
62bool IsTcMallocBypassed() {
63  // This should detect a TCMalloc bypass from Valgrind.
64  char* g_slice = getenv("G_SLICE");
65  if (g_slice && !strcmp(g_slice, "always-malloc"))
66    return true;
67  return false;
68}
69#endif
70
71// There are platforms where these tests are known to fail. We would like to
72// be able to easily check the status on the bots, but marking tests as
73// FAILS_ is too clunky.
74void OverflowTestsSoftExpectTrue(bool overflow_detected) {
75  if (!overflow_detected) {
76#if defined(OS_LINUX) || defined(OS_ANDROID) || defined(OS_MACOSX)
77    // Sadly, on Linux, Android, and OSX we don't have a good story yet. Don't
78    // fail the test, but report.
79    printf("Platform has overflow: %s\n",
80           !overflow_detected ? "yes." : "no.");
81#else
82    // Otherwise, fail the test. (Note: EXPECT are ok in subfunctions, ASSERT
83    // aren't).
84    EXPECT_TRUE(overflow_detected);
85#endif
86  }
87}
88
89#if defined(OS_IOS) || defined(OS_WIN) || defined(OS_MACOSX)
90#define MAYBE_NewOverflow DISABLED_NewOverflow
91#else
92#define MAYBE_NewOverflow NewOverflow
93#endif
94// Test array[TooBig][X] and array[X][TooBig] allocations for int overflows.
95// IOS doesn't honor nothrow, so disable the test there.
96// Crashes on Windows Dbg builds, disable there as well.
97// Fails on Mac 10.8 http://crbug.com/227092
98TEST(SecurityTest, MAYBE_NewOverflow) {
99  const size_t kArraySize = 4096;
100  // We want something "dynamic" here, so that the compiler doesn't
101  // immediately reject crazy arrays.
102  const size_t kDynamicArraySize = HideValueFromCompiler(kArraySize);
103  // numeric_limits are still not constexpr until we switch to C++11, so we
104  // use an ugly cast.
105  const size_t kMaxSizeT = ~static_cast<size_t>(0);
106  ASSERT_EQ(numeric_limits<size_t>::max(), kMaxSizeT);
107  const size_t kArraySize2 = kMaxSizeT / kArraySize + 10;
108  const size_t kDynamicArraySize2 = HideValueFromCompiler(kArraySize2);
109  {
110    scoped_ptr<char[][kArraySize]> array_pointer(new (nothrow)
111        char[kDynamicArraySize2][kArraySize]);
112    OverflowTestsSoftExpectTrue(!array_pointer);
113  }
114  // On windows, the compiler prevents static array sizes of more than
115  // 0x7fffffff (error C2148).
116#if defined(OS_WIN) && defined(ARCH_CPU_64_BITS)
117  ALLOW_UNUSED_LOCAL(kDynamicArraySize);
118#else
119  {
120    scoped_ptr<char[][kArraySize2]> array_pointer(new (nothrow)
121        char[kDynamicArraySize][kArraySize2]);
122    OverflowTestsSoftExpectTrue(!array_pointer);
123  }
124#endif  // !defined(OS_WIN) || !defined(ARCH_CPU_64_BITS)
125}
126
127#if defined(OS_LINUX) && defined(__x86_64__)
128// Check if ptr1 and ptr2 are separated by less than size chars.
129bool ArePointersToSameArea(void* ptr1, void* ptr2, size_t size) {
130  ptrdiff_t ptr_diff = reinterpret_cast<char*>(std::max(ptr1, ptr2)) -
131                       reinterpret_cast<char*>(std::min(ptr1, ptr2));
132  return static_cast<size_t>(ptr_diff) <= size;
133}
134
135// Check if TCMalloc uses an underlying random memory allocator.
136TEST(SecurityTest, MALLOC_OVERFLOW_TEST(RandomMemoryAllocations)) {
137  if (IsTcMallocBypassed())
138    return;
139  size_t kPageSize = 4096;  // We support x86_64 only.
140  // Check that malloc() returns an address that is neither the kernel's
141  // un-hinted mmap area, nor the current brk() area. The first malloc() may
142  // not be at a random address because TCMalloc will first exhaust any memory
143  // that it has allocated early on, before starting the sophisticated
144  // allocators.
145  void* default_mmap_heap_address =
146      mmap(0, kPageSize, PROT_READ|PROT_WRITE,
147           MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
148  ASSERT_NE(default_mmap_heap_address,
149            static_cast<void*>(MAP_FAILED));
150  ASSERT_EQ(munmap(default_mmap_heap_address, kPageSize), 0);
151  void* brk_heap_address = sbrk(0);
152  ASSERT_NE(brk_heap_address, reinterpret_cast<void*>(-1));
153  ASSERT_TRUE(brk_heap_address != NULL);
154  // 1 MB should get us past what TCMalloc pre-allocated before initializing
155  // the sophisticated allocators.
156  size_t kAllocSize = 1<<20;
157  scoped_ptr<char, base::FreeDeleter> ptr(
158      static_cast<char*>(malloc(kAllocSize)));
159  ASSERT_TRUE(ptr != NULL);
160  // If two pointers are separated by less than 512MB, they are considered
161  // to be in the same area.
162  // Our random pointer could be anywhere within 0x3fffffffffff (46bits),
163  // and we are checking that it's not withing 1GB (30 bits) from two
164  // addresses (brk and mmap heap). We have roughly one chance out of
165  // 2^15 to flake.
166  const size_t kAreaRadius = 1<<29;
167  bool in_default_mmap_heap = ArePointersToSameArea(
168      ptr.get(), default_mmap_heap_address, kAreaRadius);
169  EXPECT_FALSE(in_default_mmap_heap);
170
171  bool in_default_brk_heap = ArePointersToSameArea(
172      ptr.get(), brk_heap_address, kAreaRadius);
173  EXPECT_FALSE(in_default_brk_heap);
174
175  // In the implementation, we always mask our random addresses with
176  // kRandomMask, so we use it as an additional detection mechanism.
177  const uintptr_t kRandomMask = 0x3fffffffffffULL;
178  bool impossible_random_address =
179      reinterpret_cast<uintptr_t>(ptr.get()) & ~kRandomMask;
180  EXPECT_FALSE(impossible_random_address);
181}
182
183#endif  // defined(OS_LINUX) && defined(__x86_64__)
184
185}  // namespace
186