1 /*
2 * Copyright (C) 2021-2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 #include <gtest/gtest.h>
16 #include <cinttypes>
17 #include <climits>
18 #include <cstdio>
19 #include <unistd.h>
20 #include <string>
21
22
23 using namespace testing::ext;
24 using namespace std;
25
26 class MallocEncodePointer : public testing::Test {
27 public:
28
29 static void SetUpTestCase();
30 static void TearDownTestCase();
31 void SetUp();
32 void TearDown();
33 private:
34 };
35
SetUp()36 void MallocEncodePointer::SetUp()
37 {
38 }
TearDown()39 void MallocEncodePointer::TearDown()
40 {
41 }
SetUpTestCase()42 void MallocEncodePointer::SetUpTestCase()
43 {
44 }
TearDownTestCase()45 void MallocEncodePointer::TearDownTestCase()
46 {
47 }
48
49
50 /*
51 * @tc.number CAM_FREE_FUN_0100
52 * @tc.name Apply part of the memory camfree reduction
53 * @tc.desc Test the basic features of CamFree
54 */
55 HWTEST_F(MallocEncodePointer, freelist0100, Function | MediumTest | Level1)
56 {
57 uintptr_t *c0 = (uintptr_t *)malloc(sizeof(uintptr_t) * 10);
58 if (!c0) {
59 printf("Malloc c0 failed: %s\n", strerror(errno));
60 }
61 /* Malloc dividing chunk to avoid combination of neighbouring freed chunk */
62 void *d0 = malloc(sizeof(uintptr_t) * 10);
63 if (!d0) {
64 printf("Malloc d0 failed: %s\n", strerror(errno));
65 }
66
67 uintptr_t *c1 = (uintptr_t *)malloc(sizeof(uintptr_t) * 10);
68 if (!c1) {
69 printf("Malloc c1 failed: %s\n", strerror(errno));
70 }
71 /* Malloc dividing chunk to avoid combination of neighbouring freed chunk */
72 void *d1 = malloc(sizeof(uintptr_t) * 10);
73 if (!d1) {
74 printf("Malloc d1 failed: %s\n", strerror(errno));
75 }
76
77
78 /* Free the chunk, with same size, they're put into the same bin */
79 /* -------- -------- --------
80 * | c0 | | c1 | | bin |
81 * -->| next |----->| next |----->| next |-----
82 * | | prev |<-----| prev |<-----| prev | |
83 * | ------- ------- ------- |
84 * --------------------------------------------
85 */
86 free(c0);
87 free(c1);
88
89 uintptr_t xoraddr = c0[0]; /* Get the next of c0 */
90 uintptr_t realaddr = reinterpret_cast<uintptr_t>(reinterpret_cast<char *>(c1) - sizeof(uintptr_t) * 2);
91 ASSERT_FALSE(xoraddr == realaddr) << "encoding pointer is equal to real pointer\n";
92
93 free(d0);
94 free(d1);
95 }
96
97