1 /******************************************************************************
2  *
3  *  Copyright (C) 2014 Google, Inc.
4  *
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at:
8  *
9  *  http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an "AS IS" BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  *  limitations under the License.
16  *
17  ******************************************************************************/
18 
19 #include <gtest/gtest.h>
20 
21 extern "C" {
22 #include "allocation_tracker.h"
23 
24 void allocation_tracker_uninit(void);
25 }
26 
27 static const allocator_id_t allocator_id = 5;
28 
TEST(AllocationTrackerTest,test_uninit_no_bad_effects)29 TEST(AllocationTrackerTest, test_uninit_no_bad_effects) {
30   void *dummy_allocation = malloc(4);
31 
32   // Ensure uninitialized state (previous tests may have called init)
33   allocation_tracker_uninit();
34 
35   EXPECT_EQ(4U, allocation_tracker_resize_for_canary(4));
36   allocation_tracker_notify_alloc(allocator_id, dummy_allocation, 4);
37   EXPECT_EQ(0U, allocation_tracker_expect_no_allocations()); // should not have registered an allocation
38   allocation_tracker_notify_free(allocator_id, dummy_allocation);
39   EXPECT_EQ(0U, allocation_tracker_expect_no_allocations());
40 
41   free(dummy_allocation);
42 }
43 
TEST(AllocationTrackerTest,test_canaries_on)44 TEST(AllocationTrackerTest, test_canaries_on) {
45   allocation_tracker_uninit();
46   allocation_tracker_init();
47 
48   size_t with_canary_size = allocation_tracker_resize_for_canary(4);
49   EXPECT_TRUE(with_canary_size > 4);
50 
51   void *dummy_allocation = malloc(with_canary_size);
52   void *useable_ptr = allocation_tracker_notify_alloc(allocator_id, dummy_allocation, 4);
53   EXPECT_TRUE(useable_ptr > dummy_allocation);
54   EXPECT_EQ(4U, allocation_tracker_expect_no_allocations()); // should have registered the allocation
55   void *freeable_ptr = allocation_tracker_notify_free(allocator_id, useable_ptr);
56   EXPECT_EQ(dummy_allocation, freeable_ptr);
57   EXPECT_EQ(0U, allocation_tracker_expect_no_allocations());
58 
59   free(dummy_allocation);
60 }
61