1// Copyright 2014 The Android Open Source Project
2//
3// This software is licensed under the terms of the GNU General Public
4// License version 2, as published by the Free Software Foundation, and
5// may be copied, distributed, and modified under those terms.
6//
7// This program is distributed in the hope that it will be useful,
8// but WITHOUT ANY WARRANTY; without even the implied warranty of
9// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10// GNU General Public License for more details.
11
12#include "android/base/memory/MallocUsableSize.h"
13
14#include <stdlib.h>
15
16#include <gtest/gtest.h>
17
18namespace android {
19namespace base {
20
21#if USE_MALLOC_USABLE_SIZE
22
23static size_t computeSize(size_t index) {
24    return 3 + index * 17;
25}
26
27TEST(MallocUsableSize, UseMallocUsableSize) {
28    const size_t kCount = 1000;
29    void* blocks[kCount];
30    for (size_t n = 0; n < kCount; ++n) {
31        blocks[n] = ::malloc(computeSize(n));
32        EXPECT_TRUE(blocks[n]);
33    }
34
35    for (size_t n = 0; n < kCount; ++n) {
36        size_t size = computeSize(n);
37        EXPECT_LE(size, ::malloc_usable_size(blocks[n]))
38                << "For block " << n << " of " << size << " bytes";
39    }
40
41    for (size_t n = kCount; n > 0; --n) {
42        ::free(blocks[n - 1U]);
43    }
44}
45
46#else  // !USE_MALLOC_USABLE_SIZE
47
48TEST(MallocUsableSize, DoNotUseMallocUsableSize) {
49#ifdef __linux__
50    EXPECT_TRUE(false) << "Linux should have malloc_usable_size";
51#elif defined(__APPLE__)
52    EXPECT_TRUE(false) << "Darwin should have malloc_size";
53#elif defined(__FreeBSD__)
54    EXPECT_TRUE(false) << "FreeBSD should have malloc_size";
55#endif
56}
57
58#endif  // !USE_MALLOC_USABLE_SIZE
59
60}  // namespace base
61}  // namespace android
62