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 "buffer/avsharedmemorybase.h"
17 #include <sys/mman.h>
18 #include <unistd.h>
19 #include "ashmem.h"
20 #include "common/status.h"
21 #include "common/log.h"
22 #include "scope_guard.h"
23 #include "securec.h"
24 
25 namespace {
26 constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { LOG_CORE, LOG_DOMAIN_FOUNDATION, "AVSharedMemoryBase" };
27 static std::atomic<uint64_t> g_uniqueSharedMemoryID = 0;
28 }
29 
30 namespace OHOS {
31 namespace Media {
32 struct AVSharedMemoryBaseImpl : public AVSharedMemoryBase {
33 public:
AVSharedMemoryBaseImplOHOS::Media::AVSharedMemoryBaseImpl34     AVSharedMemoryBaseImpl(int32_t fd, int32_t size, uint32_t flags, const std::string &name)
35         : AVSharedMemoryBase(fd, size, flags, name) {}
36 };
37 
CreateFromLocal(int32_t size,uint32_t flags,const std::string & name)38 std::shared_ptr<AVSharedMemory> AVSharedMemoryBase::CreateFromLocal(
39     int32_t size, uint32_t flags, const std::string &name)
40 {
41     std::shared_ptr<AVSharedMemoryBase> memory = std::make_shared<AVSharedMemoryBase>(size, flags, name);
42     int32_t ret = memory->Init();
43     if (ret != static_cast<int32_t>(Status::OK)) {
44         MEDIA_LOG_E("Create avsharedmemory failed, ret = %{public}d", ret);
45         return nullptr;
46     }
47 
48     return memory;
49 }
50 
CreateFromRemote(int32_t fd,int32_t size,uint32_t flags,const std::string & name)51 std::shared_ptr<AVSharedMemory> AVSharedMemoryBase::CreateFromRemote(
52     int32_t fd, int32_t size, uint32_t flags, const std::string &name)
53 {
54     std::shared_ptr<AVSharedMemoryBase> memory = std::make_shared<AVSharedMemoryBaseImpl>(fd, size, flags, name);
55     int32_t ret = memory->Init();
56     if (ret != static_cast<int32_t>(Status::OK)) {
57         MEDIA_LOG_E("Create avsharedmemory failed, ret = %{public}d", ret);
58         return nullptr;
59     }
60 
61     return memory;
62 }
63 
AVSharedMemoryBase(int32_t size,uint32_t flags,const std::string & name)64 AVSharedMemoryBase::AVSharedMemoryBase(int32_t size, uint32_t flags, const std::string &name)
65     : base_(nullptr), capacity_(size), flags_(flags), name_(name), fd_(-1), size_(0)
66 {
67     MEDIA_LOG_DD(LOGD_FREQUENCY, "enter ctor, instance: 0x%{public}06" PRIXPTR ", name = %{public}s",
68                FAKE_POINTER(this), name_.c_str());
69     uniqueSharedMemoryID_ = g_uniqueSharedMemoryID++;
70 }
71 
AVSharedMemoryBase(int32_t fd,int32_t size,uint32_t flags,const std::string & name)72 AVSharedMemoryBase::AVSharedMemoryBase(int32_t fd, int32_t size, uint32_t flags, const std::string &name)
73     : base_(nullptr), capacity_(size), flags_(flags), name_(name), fd_(dup(fd)), size_(0)
74 {
75     MEDIA_LOG_DD(LOGD_FREQUENCY, "enter ctor, instance: 0x%{public}06" PRIXPTR ", name = %{public}s",
76                FAKE_POINTER(this), name_.c_str());
77     uniqueSharedMemoryID_ = g_uniqueSharedMemoryID++;
78 }
79 
~AVSharedMemoryBase()80 AVSharedMemoryBase::~AVSharedMemoryBase()
81 {
82     MEDIA_LOG_DD(LOGD_FREQUENCY, "enter dtor, instance: 0x%{public}06" PRIXPTR ", name = %{public}s",
83                FAKE_POINTER(this), name_.c_str());
84     Close();
85 }
86 
Init(bool isMapVirAddr)87 int32_t AVSharedMemoryBase::Init(bool isMapVirAddr)
88 {
89     ON_SCOPE_EXIT(0) {
90         MEDIA_LOG_E("create avsharedmemory failed, name = %{public}s, size = %{public}d, "
91                     "flags = 0x%{public}x, fd = %{public}d",
92                     name_.c_str(), capacity_, flags_, fd_);
93         Close();
94     };
95 
96     FALSE_RETURN_V_MSG_E(capacity_ > 0, static_cast<int32_t>(Status::ERROR_INVALID_PARAMETER),
97                          "size is invalid, size = %{public}d", capacity_);
98 
99     bool isRemote = false;
100     if (fd_ > 0) {
101         int size = AshmemGetSize(fd_);
102         FALSE_RETURN_V_MSG_E(size == capacity_, static_cast<int32_t>(Status::ERROR_INVALID_PARAMETER),
103             "size not equal capacity_, size = %{public}d, capacity_ = %{public}d", size, capacity_);
104         isRemote = true;
105     } else {
106         fd_ = AshmemCreate(name_.c_str(), static_cast<size_t>(capacity_));
107         FALSE_RETURN_V_MSG_E(fd_ > 0, static_cast<int32_t>(Status::ERROR_INVALID_PARAMETER),
108                              "fd is invalid, fd = %{public}d", fd_);
109     }
110     if (isMapVirAddr) {
111         int32_t ret = MapMemory(isRemote);
112         FALSE_RETURN_V_MSG_E(ret == static_cast<int32_t>(Status::OK),
113                              static_cast<int32_t>(Status::ERROR_INVALID_PARAMETER),
114                              "MapMemory failed, ret = %{plublic}d", ret);
115     }
116     CANCEL_SCOPE_EXIT_GUARD(0);
117     return static_cast<int32_t>(Status::OK);
118 }
119 
MapMemory(bool isRemote)120 int32_t AVSharedMemoryBase::MapMemory(bool isRemote)
121 {
122 #ifdef MEDIA_OHOS
123     unsigned int prot = PROT_READ | PROT_WRITE;
124     if (isRemote && (flags_ & FLAGS_READ_ONLY)) {
125         prot &= ~PROT_WRITE;
126     }
127 
128     int result = AshmemSetProt(fd_, static_cast<int>(prot));
129     FALSE_RETURN_V_MSG_E(result >= 0, static_cast<int32_t>(Status::ERROR_INVALID_OPERATION),
130         "AshmemSetProt failed, result = %{public}d", result);
131 
132     void *addr = ::mmap(nullptr, static_cast<size_t>(capacity_), static_cast<int>(prot), MAP_SHARED, fd_, 0);
133     FALSE_RETURN_V_MSG_E(addr != MAP_FAILED, static_cast<int32_t>(Status::ERROR_INVALID_OPERATION),
134                          "mmap failed, please check params");
135 
136     base_ = reinterpret_cast<uint8_t*>(addr);
137 #endif
138     return static_cast<int32_t>(Status::OK);
139 }
140 
Close()141 void AVSharedMemoryBase::Close() noexcept
142 {
143 #ifdef MEDIA_OHOS
144     if (base_ != nullptr) {
145         (void)::munmap(base_, static_cast<size_t>(capacity_));
146         base_ = nullptr;
147         capacity_ = 0;
148         flags_ = 0;
149         size_ = 0;
150     }
151 #endif
152     if (fd_ > 0) {
153         (void)::close(fd_);
154         fd_ = -1;
155     }
156 }
157 
Write(const uint8_t * in,int32_t writeSize,int32_t position)158 int32_t AVSharedMemoryBase::Write(const uint8_t *in, int32_t writeSize, int32_t position)
159 {
160     FALSE_RETURN_V_MSG_E(in != nullptr, 0, "Input buffer is nullptr");
161     FALSE_RETURN_V_MSG_E(writeSize > 0, 0, "Input writeSize:%{public}d is invalid", writeSize);
162     int32_t start = 0;
163     if (position == INVALID_POSITION) {
164         start = size_;
165     } else {
166         start = std::min(position, capacity_);
167     }
168     int32_t unusedSize = capacity_ - start;
169     int32_t length = std::min(writeSize, unusedSize);
170     MEDIA_LOG_DD("write data,length:%{public}d, start:%{public}d, name:%{public}s", length, start, name_.c_str());
171     FALSE_RETURN_V_MSG_E((length + start) <= capacity_, 0, "Write out of bounds, length:%{public}d, "
172                             "start:%{public}d, capacity_:%{public}d", length, start, capacity_);
173     uint8_t *dstPtr = base_ + start;
174     FALSE_RETURN_V_MSG_E(dstPtr != nullptr, 0, "Inner dstPtr is nullptr");
175 
176     auto error = memcpy_s(dstPtr, length, in, length);
177     FALSE_RETURN_V_MSG_E(error == EOK, 0, "Inner memcpy_s failed,name:%{public}s, %{public}s",
178         name_.c_str(), strerror(error));
179     size_ = start + length;
180     return length;
181 }
182 
Read(uint8_t * out,int32_t readSize,int32_t position)183 int32_t AVSharedMemoryBase::Read(uint8_t *out, int32_t readSize, int32_t position)
184 {
185     FALSE_RETURN_V_MSG_E(out != nullptr, 0, "Input buffer is nullptr");
186     FALSE_RETURN_V_MSG_E(readSize > 0, 0, "Input readSize:%{public}d is invalid", readSize);
187     int32_t start = 0;
188     int32_t maxLength = size_;
189     if (position != INVALID_POSITION) {
190         start = std::min(position, size_);
191         maxLength = size_ - start;
192     }
193     int32_t length = std::min(readSize, maxLength);
194     FALSE_RETURN_V_MSG_E((length + start) <= capacity_, 0, "Read out of bounds, length:%{public}d, "
195                             "start:%{public}d, capacity_:%{public}d", length, start, capacity_);
196     uint8_t *srcPtr = base_ + start;
197     FALSE_RETURN_V_MSG_E(srcPtr != nullptr, 0, "Inner srcPtr is nullptr");
198     auto error = memcpy_s(out, length, srcPtr, length);
199     FALSE_RETURN_V_MSG_E(error == EOK, 0, "Inner memcpy_s failed,name:%{public}s, %{public}s",
200         name_.c_str(), strerror(error));
201     return length;
202 }
203 
ClearUsedSize()204 void AVSharedMemoryBase::ClearUsedSize()
205 {
206     size_ = 0;
207 }
208 
GetUsedSize() const209 int32_t AVSharedMemoryBase::GetUsedSize() const
210 {
211     return size_;
212 }
213 } // namespace Media
214 } // namespace OHOS
215