1 /*
2 * Copyright (c) 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 "selinux_share_mem.h"
16 #include <errno.h>
17 #include <fcntl.h>
18 #include <sys/mman.h>
19 #include <sys/shm.h>
20 #include <unistd.h>
21 #include <stdio.h>
22
InitSharedMem(const char * fileName,uint32_t spaceSize,bool readOnly)23 void *InitSharedMem(const char *fileName, uint32_t spaceSize, bool readOnly)
24 {
25 if (fileName == NULL || spaceSize == 0) {
26 return NULL;
27 }
28 int mode = readOnly ? O_RDONLY : O_CREAT | O_RDWR | O_TRUNC;
29 int fd = open(fileName, mode, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
30 if (fd < 0) {
31 return NULL;
32 }
33
34 int prot = PROT_READ;
35 if (!readOnly) {
36 prot = PROT_READ | PROT_WRITE;
37 ftruncate(fd, spaceSize);
38 }
39 void *sharedMem = (void *)mmap(NULL, spaceSize, prot, MAP_SHARED, fd, 0);
40 if (sharedMem == MAP_FAILED) {
41 close(fd);
42 return NULL;
43 }
44 close(fd);
45 return sharedMem;
46 }
47
UnmapSharedMem(char * sharedMem,uint32_t dataSize)48 void UnmapSharedMem(char *sharedMem, uint32_t dataSize)
49 {
50 if (sharedMem == NULL || dataSize == 0) {
51 return;
52 }
53 munmap(sharedMem, dataSize);
54 }
55
WriteSharedMem(char * sharedMem,const char * data,uint32_t length)56 void WriteSharedMem(char *sharedMem, const char *data, uint32_t length)
57 {
58 if (sharedMem == NULL || data == NULL || length == 0) {
59 return;
60 }
61 memcpy(sharedMem, data, length);
62 msync(sharedMem, length, MS_SYNC);
63 }
64
ReadSharedMem(char * sharedMem,uint32_t length)65 char *ReadSharedMem(char *sharedMem, uint32_t length)
66 {
67 if (sharedMem == NULL) {
68 return NULL;
69 }
70 if (strlen(sharedMem) != length) {
71 return NULL;
72 }
73 return sharedMem;
74 }
75