1/*
2 * Copyright (c) 2022-2024 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
16#include "xpm_common.h"
17
18#include <cerrno>
19#include <cstdio>
20#include <cstdlib>
21#include <cstring>
22#include <fcntl.h>
23#include <unistd.h>
24#include <securec.h>
25#include <sys/mman.h>
26#include <sys/stat.h>
27
28#include "code_sign_attr_utils.h"
29#include "log.h"
30
31namespace OHOS {
32namespace Security {
33namespace CodeSign {
34struct XpmRegionArea {
35    uint64_t start;
36    uint64_t end;
37};
38
39const std::string XPM_PROC_PREFIX_PATH = "/proc/";
40const std::string XPM_PROC_SUFFIX_PATH = "/xpm_region";
41
42constexpr unsigned long XPM_PROC_LENGTH = 50;
43
44static int GetXpmRegion(struct XpmRegionArea &area)
45{
46    if (InitXpm(0, PROCESS_OWNERID_UNINIT, NULL) != 0) {
47        LOG_ERROR("init xpm region failed");
48        return -1;
49    }
50
51    pid_t pid = getpid();
52    std::string path = XPM_PROC_PREFIX_PATH + std::to_string(pid) + XPM_PROC_SUFFIX_PATH;
53    int fd = open(path.c_str(), O_RDWR);
54    if (fd < 0) {
55        LOG_ERROR("open xpm proc file failed(%{public}s)", strerror(errno));
56        return -1;
57    }
58
59    char xpmRegion[XPM_PROC_LENGTH] = {0};
60    int ret = read(fd, xpmRegion, sizeof(xpmRegion));
61    if (ret < 0) {
62        LOG_ERROR("read xpm proc file failed(%{public}s)", strerror(errno));
63        return -1;
64    }
65
66    ret = sscanf_s(xpmRegion, "%llx-%llx", &area.start, &area.end);
67    if (ret < 0) {
68        LOG_ERROR("sscanf xpm region string failed(%{public}s)", strerror(errno));
69        return -1;
70    }
71
72    close(fd);
73    return 0;
74}
75
76bool AllocXpmRegion()
77{
78    struct XpmRegionArea area = {0};
79
80    if (GetXpmRegion(area)) {
81        return false;
82    }
83    if (!area.start) {
84        return false;
85    }
86    if (!area.end) {
87        return false;
88    }
89
90    return true;
91}
92} // namespace CodeSign
93} // namespace Security
94} // namespace OHOS