1 /*
2 * Copyright (c) 2022 Shenzhen Kaihong DID 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 "ashmem_wrapper.h"
17 #include <sys/mman.h>
18 #include <unistd.h>
19 #include "ashmem.h"
20 #include "hdf_base.h"
21 #include "hdf_log.h"
22
23 #define HDF_LOG_TAG codec_hdi_share_mem
24
25 using namespace OHOS;
26
27 #ifdef __cplusplus
28 extern "C"
29 {
30 #endif
31
AshmemCreateFd(const char * name,int32_t size)32 int32_t AshmemCreateFd(const char *name, int32_t size)
33 {
34 if (size <= 0) {
35 HDF_LOGE("%{public}s: Failed to create invalid size: %{public}d", __func__, size);
36 return HDF_FAILURE;
37 }
38 int32_t fd = AshmemCreate(name, size);
39 if (fd < 0) {
40 HDF_LOGE("%{public}s: Failed to create fd = %{public}d", __func__, fd);
41 }
42 return fd;
43 }
44
MapAshmemFd(int32_t fd,int32_t size)45 uint8_t* MapAshmemFd(int32_t fd, int32_t size)
46 {
47 if (fd < 0) {
48 HDF_LOGE("%{public}s: Failed to map invalid fd: %{public}d", __func__, fd);
49 return nullptr;
50 }
51 if (size <= 0) {
52 HDF_LOGE("%{public}s: Failed to map invalid size: %{public}d", __func__, size);
53 return nullptr;
54 }
55 uint8_t *addr = static_cast<uint8_t *>(mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0));
56 return addr;
57 }
58
UnmapAshmemFd(uint8_t * addr,int32_t size)59 void UnmapAshmemFd(uint8_t *addr, int32_t size)
60 {
61 if (addr == nullptr) {
62 HDF_LOGE("%{public}s: invalid nullptr addr!", __func__);
63 return;
64 }
65 munmap(static_cast<void *>(addr), size);
66 }
67
CloseAshmemFd(int32_t fd)68 int32_t CloseAshmemFd(int32_t fd)
69 {
70 return close(fd);
71 }
72
73 #ifdef __cplusplus
74 }
75 #endif
76