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.
7 #include "testing/gtest/include/gtest/gtest.h"
9 // TCMalloc header files.
10 #include "common.h" // For TCMalloc constants like page size, etc.
12 // TCMalloc implementation.
13 #include "debugallocation_shim.cc"
17 void* TCMallocDoMallocForTest(size_t size
) {
18 return do_malloc(size
);
21 void TCMallocDoFreeForTest(void* ptr
) {
25 size_t ExcludeSpaceForMarkForTest(size_t size
) {
26 return ExcludeSpaceForMark(size
);
31 TEST(TCMallocFreeCheck
, BadPointerInFirstPageOfTheLargeObject
) {
32 char* p
= reinterpret_cast<char*>(
33 TCMallocDoMallocForTest(ExcludeSpaceForMarkForTest(kMaxSize
+ 1)));
34 for (int offset
= 1; offset
< kPageSize
; offset
<<= 1) {
35 ASSERT_DEATH(TCMallocDoFreeForTest(p
+ offset
),
36 "Pointer is not pointing to the start of a span");
40 TEST(TCMallocFreeCheck
, BadPageAlignedPointerInsideLargeObject
) {
41 char* p
= reinterpret_cast<char*>(
42 TCMallocDoMallocForTest(ExcludeSpaceForMarkForTest(kMaxSize
+ 1)));
44 for (int offset
= kPageSize
; offset
< kMaxSize
; offset
+= kPageSize
) {
45 // Only the first and last page of a span are in heap map. So for others
46 // tcmalloc will give a general error of invalid pointer.
47 ASSERT_DEATH(TCMallocDoFreeForTest(p
+ offset
),
48 "Attempt to free invalid pointer");
50 ASSERT_DEATH(TCMallocDoFreeForTest(p
+ kMaxSize
),
51 "Pointer is not pointing to the start of a span");
54 TEST(TCMallocFreeCheck
, DoubleFreeLargeObject
) {
55 char* p
= reinterpret_cast<char*>(
56 TCMallocDoMallocForTest(ExcludeSpaceForMarkForTest(kMaxSize
+ 1)));
57 ASSERT_DEATH(TCMallocDoFreeForTest(p
); TCMallocDoFreeForTest(p
),
58 "Object was not in-use");
63 TEST(TCMallocFreeCheck
, DoubleFreeSmallObject
) {
65 size
<= ExcludeSpaceForMarkForTest(kMaxSize
);
67 char* p
= reinterpret_cast<char*>(TCMallocDoMallocForTest(size
));
68 ASSERT_DEATH(TCMallocDoFreeForTest(p
); TCMallocDoFreeForTest(p
),
69 "Circular loop in list detected");
73 TEST(TCMallocFreeCheck
, DoubleFreeSmallObject
) {
76 // When the object is small, tcmalloc validation can not distinguish normal
77 // memory corruption or double free, because there's not enough space in
78 // freed objects to keep the mark.
79 for (; size
<= ExcludeSpaceForMarkForTest(kMinClassSize
); size
<<= 1) {
80 char* p
= reinterpret_cast<char*>(TCMallocDoMallocForTest(size
));
81 ASSERT_DEATH(TCMallocDoFreeForTest(p
); TCMallocDoFreeForTest(p
),
85 for (; size
<= ExcludeSpaceForMarkForTest(kMaxSize
); size
<<= 1) {
86 char* p
= reinterpret_cast<char*>(TCMallocDoMallocForTest(size
));
87 ASSERT_DEATH(TCMallocDoFreeForTest(p
); TCMallocDoFreeForTest(p
),
88 "Attempt to double free");
93 int main(int argc
, char **argv
) {
94 testing::InitGoogleTest(&argc
, argv
);
95 return RUN_ALL_TESTS();