1 /*
2 * Copyright (c) 2023 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 "code_sign_attr_utils.h"
17
18 #include <fcntl.h>
19 #include <unistd.h>
20 #include <string.h>
21 #include <securec.h>
22 #include <sys/ioctl.h>
23
24 #include "errcode.h"
25 #include "log.h"
26
27 #define XPM_DEV_PATH "/dev/xpm"
28
29 #define XPM_SET_REGION _IOW('x', 0x01, struct XpmConfig)
30 #define XPM_SET_OWNERID _IOW('x', 0x02, struct XpmConfig)
31
XpmIoctl(uint32_t cmd,struct XpmConfig * config)32 static int XpmIoctl(uint32_t cmd, struct XpmConfig *config)
33 {
34 int fd = open(XPM_DEV_PATH, O_RDWR);
35 if (fd == -1) {
36 LOG_INFO("Open device file failed: %{public}s (ignore)", strerror(errno));
37 return CS_SUCCESS;
38 }
39
40 int ret = ioctl(fd, cmd, config);
41 if (ret == -1) {
42 LOG_ERROR("Ioctl cmd %{public}x failed: %{public}s (ignore)", cmd, strerror(errno));
43 } else {
44 LOG_DEBUG("Ioctl cmd %{public}x success", cmd);
45 }
46 close(fd);
47
48 return CS_SUCCESS;
49 }
50
InitXpmRegion(void)51 int InitXpmRegion(void)
52 {
53 struct XpmConfig config = {0};
54
55 config.regionAddr = 0;
56 config.regionLength = XPM_REGION_LEN;
57 return XpmIoctl(XPM_SET_REGION, &config);
58 }
59
SetXpmOwnerId(uint32_t idType,const char * ownerId)60 int SetXpmOwnerId(uint32_t idType, const char *ownerId)
61 {
62 struct XpmConfig config = {0};
63
64 if (idType >= PROCESS_OWNERID_MAX) {
65 LOG_ERROR("Input idType is invalid: %{public}u", idType);
66 return CS_ERR_PARAM_INVALID;
67 }
68
69 config.idType = idType;
70 if ((ownerId != NULL) && (strlen(ownerId) != 0)) {
71 if (memcpy_s(config.ownerId, sizeof(config.ownerId) - 1, ownerId, strlen(ownerId)) != EOK) {
72 LOG_ERROR("Memcpy ownerId failed, ownerId: %{public}s", ownerId);
73 return CS_ERR_MEMORY;
74 }
75 }
76
77 LOG_DEBUG("Set type = %{public}u, ownerId = %{public}s", idType, ownerId ? ownerId : "NULL");
78 return XpmIoctl(XPM_SET_OWNERID, &config);
79 }
80