1 /* 2 * Copyright (c) 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 #ifndef ASH_MEMORY_UTILS_H 17 #define ASH_MEMORY_UTILS_H 18 19 #include "ashmem.h" 20 #include "refbase.h" 21 22 namespace OHOS { 23 namespace HiviewDFX { 24 class AshMemoryUtils { 25 public: 26 template <class T> WriteBulkData(const std::vector<T> & src,sptr<Ashmem> ashmem,size_t ashSize,std::vector<uint32_t> & allSize)27 static bool WriteBulkData(const std::vector<T>& src, sptr<Ashmem> ashmem, size_t ashSize, 28 std::vector<uint32_t>& allSize) 29 { 30 uint32_t offset = 0; 31 for (auto& dataInfo : src) { 32 uint32_t dataSize = 0; 33 void* data = dataInfo.GetData(dataSize); 34 if (data == nullptr) { 35 continue; 36 } 37 if (offset + dataSize > ashSize) { 38 free(data); 39 break; 40 } 41 allSize.emplace_back(dataSize); 42 if (!ashmem->WriteToAshmem(data, dataSize, offset)) { 43 free(data); 44 return false; 45 } 46 free(data); 47 offset += dataSize; 48 } 49 return true; 50 } 51 52 template <class T> ReadBulkData(sptr<Ashmem> ashmem,const std::vector<uint32_t> & allSize,std::vector<T> & dest)53 static bool ReadBulkData(sptr<Ashmem> ashmem, const std::vector<uint32_t>& allSize, std::vector<T>& dest) 54 { 55 uint32_t offset = 0; 56 for (uint32_t i = 0; i < allSize.size(); i++) { 57 auto origin = ashmem->ReadFromAshmem(allSize[i], offset); 58 if (origin == nullptr) { 59 return false; 60 } 61 auto dataInfo = T::ParseData(reinterpret_cast<const char*>(origin), allSize[i]); 62 offset += allSize[i]; 63 dest.emplace_back(dataInfo); 64 } 65 return true; 66 } 67 68 static sptr<Ashmem> GetAshmem(const std::string& ashName, const uint32_t ashSize); 69 }; 70 } // namespace HiviewDFX 71 } // namespace OHOS 72 73 #endif // ASH_MEMORY_UTILS_H