1 /*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include <shared/chunk_allocator.h>
18
19 #include <gtest/gtest.h>
20
21 static constexpr size_t kAllocSize = 128;
22 static constexpr size_t kSlotCount = 5;
23
24 typedef nanoapp_testing::ChunkAllocator<kAllocSize, kSlotCount> DA;
25
ExpectGoodAlloc(const DA & da,const void * ptr)26 static void ExpectGoodAlloc(const DA &da, const void *ptr) {
27 EXPECT_NE(nullptr, ptr);
28 EXPECT_TRUE(da.contains(ptr));
29 }
30
TEST(ChunkAllocatorTests,SimpleAlloc)31 TEST(ChunkAllocatorTests, SimpleAlloc) {
32 DA da;
33 void *ptr = da.alloc(kAllocSize);
34 ExpectGoodAlloc(da, ptr);
35 EXPECT_TRUE(da.free(ptr));
36 }
37
TEST(ChunkAllocatorTests,AllocsAfterFree)38 TEST(ChunkAllocatorTests, AllocsAfterFree) {
39 DA da;
40 void *ptrs[kSlotCount];
41 for (size_t i = 0; i < kSlotCount; i++) {
42 ptrs[i] = da.alloc(kAllocSize);
43 ExpectGoodAlloc(da, ptrs[i]);
44 // Also confirm we're not doubly allocating the same pointer.
45 for (size_t j = 0; j < i; j++) {
46 EXPECT_NE(ptrs[j], ptrs[i]);
47 }
48 }
49 // Out of slots, allocation should fail.
50 EXPECT_EQ(nullptr, da.alloc(kAllocSize));
51
52 constexpr size_t kFreeIndex = kSlotCount / 2;
53 EXPECT_TRUE(da.free(ptrs[kFreeIndex]));
54 ptrs[kFreeIndex] = nullptr;
55
56 // Now our allocation should succeed.
57 void *newPtr = da.alloc(kAllocSize);
58 ExpectGoodAlloc(da, newPtr);
59 for (size_t i = 0; i < kSlotCount; i++) {
60 EXPECT_NE(newPtr, ptrs[i]);
61 }
62 }
63
TEST(ChunkAllocatorTests,ContainsIsFalseForBadPtrs)64 TEST(ChunkAllocatorTests, ContainsIsFalseForBadPtrs) {
65 DA da;
66 uint8_t *ptr = static_cast<uint8_t *>(da.alloc(kAllocSize));
67 ASSERT_NE(nullptr, ptr);
68 EXPECT_FALSE(da.contains(ptr - 1));
69 EXPECT_FALSE(da.contains(ptr + 1));
70 EXPECT_FALSE(da.contains(nullptr));
71 }
72
TEST(ChunkAllocatorTests,FailLargeAllocations)73 TEST(ChunkAllocatorTests, FailLargeAllocations) {
74 DA da;
75 EXPECT_EQ(nullptr, da.alloc(kAllocSize + 1));
76 EXPECT_EQ(nullptr, da.alloc(kAllocSize * 2));
77 }
78
TEST(ChunkAllocatorTests,SucceedSmallAllocations)79 TEST(ChunkAllocatorTests, SucceedSmallAllocations) {
80 DA da;
81 ExpectGoodAlloc(da, da.alloc(kAllocSize - 1));
82 ExpectGoodAlloc(da, da.alloc(1));
83 ExpectGoodAlloc(da, da.alloc(0));
84 }
85