1 //===-- Unittests for freelist_malloc -------------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "src/__support/freelist_heap.h"
10 #include "src/stdlib/aligned_alloc.h"
11 #include "src/stdlib/calloc.h"
12 #include "src/stdlib/free.h"
13 #include "src/stdlib/malloc.h"
14 #include "test/UnitTest/Test.h"
16 using LIBC_NAMESPACE::freelist_heap
;
17 using LIBC_NAMESPACE::FreeListHeap
;
18 using LIBC_NAMESPACE::FreeListHeapBuffer
;
20 TEST(LlvmLibcFreeListMalloc
, Malloc
) {
21 constexpr size_t kAllocSize
= 256;
22 constexpr size_t kCallocNum
= 4;
23 constexpr size_t kCallocSize
= 64;
25 typedef FreeListHeap
<>::BlockType Block
;
27 void *ptr1
= LIBC_NAMESPACE::malloc(kAllocSize
);
28 auto *block
= Block::from_usable_space(ptr1
);
29 EXPECT_GE(block
->inner_size(), kAllocSize
);
31 LIBC_NAMESPACE::free(ptr1
);
32 ASSERT_NE(block
->next(), static_cast<Block
*>(nullptr));
33 ASSERT_EQ(block
->next()->next(), static_cast<Block
*>(nullptr));
34 size_t heap_size
= block
->inner_size();
36 void *ptr2
= LIBC_NAMESPACE::calloc(kCallocNum
, kCallocSize
);
37 ASSERT_EQ(ptr2
, ptr1
);
38 EXPECT_GE(block
->inner_size(), kCallocNum
* kCallocSize
);
40 for (size_t i
= 0; i
< kCallocNum
* kCallocSize
; ++i
)
41 EXPECT_EQ(reinterpret_cast<uint8_t *>(ptr2
)[i
], uint8_t(0));
43 LIBC_NAMESPACE::free(ptr2
);
44 EXPECT_EQ(block
->inner_size(), heap_size
);
46 constexpr size_t ALIGN
= kAllocSize
;
47 void *ptr3
= LIBC_NAMESPACE::aligned_alloc(ALIGN
, kAllocSize
);
48 EXPECT_NE(ptr3
, static_cast<void *>(nullptr));
49 EXPECT_EQ(reinterpret_cast<uintptr_t>(ptr3
) % ALIGN
, size_t(0));
50 auto *aligned_block
= reinterpret_cast<Block
*>(ptr3
);
51 EXPECT_GE(aligned_block
->inner_size(), kAllocSize
);
53 LIBC_NAMESPACE::free(ptr3
);
54 EXPECT_EQ(block
->inner_size(), heap_size
);