1/*
2 * Copyright (c) Huawei Technologies Co., Ltd. 2022. All rights reserved.
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 <cstring>
16
17#include <gtest/gtest.h>
18
19#include "kernel_symbol_info.h"
20
21using namespace testing::ext;
22
23namespace OHOS {
24namespace Developtools {
25namespace Hiebpf {
26class KernelSymbolInfoTest : public ::testing::Test {
27public:
28    static void SetUpTestCase() {};
29    static void TearDownTestCase() {};
30
31    void SetUp() {}
32    void TearDown() {}
33};
34
35/**
36 * @tc.name: GetSymbolData
37 * @tc.desc: Test framework
38 * @tc.type: FUNC
39 */
40HWTEST_F(KernelSymbolInfoTest, GetSymbolData, TestSize.Level1)
41{
42    std::vector<uint8_t> buf;
43    uint32_t headSize = sizeof(uint64_t) + sizeof(uint64_t) + sizeof(uint32_t) + sizeof(uint32_t);
44    uint32_t size = KernelSymbolInfo::GetSymbolData(buf);
45    ASSERT_GE(size, headSize);
46    uint8_t *p = buf.data();
47    uint64_t vaddrStart =  *(reinterpret_cast<uint64_t *>(p));
48    p += sizeof(uint64_t);
49    uint64_t vaddrEnd =  *(reinterpret_cast<uint64_t *>(p));
50    p += sizeof(uint64_t);
51    uint32_t symTabLen =  *(reinterpret_cast<uint32_t *>(p));
52    p += sizeof(uint32_t);
53    uint32_t strTabLen =  *(reinterpret_cast<uint32_t *>(p));
54    p += sizeof(uint32_t);
55    ASSERT_GT(vaddrStart, 0);
56    ASSERT_GE(vaddrEnd, vaddrStart);
57    vaddrStart--;
58    ASSERT_EQ(size, headSize + symTabLen + strTabLen);
59
60    char *pStrTab = reinterpret_cast<char *>(p) + symTabLen;
61    const uint32_t symItemSize = sizeof(uint64_t) + sizeof(uint32_t) + sizeof(uint32_t);
62    while (symTabLen > symItemSize) {
63        uint64_t value =  *(reinterpret_cast<uint64_t *>(p));
64        p += sizeof(uint64_t);
65        ASSERT_GT(value, vaddrStart);
66        vaddrStart = value;
67
68        uint32_t symbolSize =  *(reinterpret_cast<uint32_t *>(p));
69        p += sizeof(uint32_t);
70        ASSERT_GE(vaddrEnd, value + symbolSize);
71
72        uint32_t symbolNameOffset =  *(reinterpret_cast<uint32_t *>(p));
73        p += sizeof(uint32_t);
74        std::string name(pStrTab + symbolNameOffset);
75        ASSERT_GE(strTabLen, symbolNameOffset + name.size() + 1);
76
77        symTabLen -= symItemSize;
78    }
79}
80} // namespace Hiebpf
81} // namespace Developtools
82} // namespace OHOS
83