1/* 2 * Copyright (c) 2023-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 CODE_SIGN_BYTE_BUFFER_H 17#define CODE_SIGN_BYTE_BUFFER_H 18 19#include <memory> 20#include <climits> 21#include <cstdio> 22#include <cstdint> 23#include <cstdlib> 24#include <cstring> 25#include <securec.h> 26 27namespace OHOS { 28namespace Security { 29namespace CodeSign { 30class ByteBuffer { 31public: 32 ByteBuffer(): data(nullptr), size(0) 33 { 34 } 35 36 ByteBuffer(uint32_t bufferSize): data(nullptr), size(0) 37 { 38 Init(bufferSize); 39 } 40 41 ByteBuffer(const ByteBuffer &other): data(nullptr), size(0) 42 { 43 CopyFrom(other.GetBuffer(), other.GetSize()); 44 } 45 46 ~ByteBuffer() 47 { 48 if (data != nullptr) { 49 data.reset(nullptr); 50 data = nullptr; 51 } 52 size = 0; 53 } 54 bool CopyFrom(const uint8_t *srcData, uint32_t srcSize) 55 { 56 if (srcData == nullptr) { 57 return false; 58 } 59 if (!Resize(srcSize)) { 60 return false; 61 } 62 if (memcpy_s(data.get(), size, srcData, srcSize) != EOK) { 63 return false; 64 } 65 return true; 66 } 67 68 bool PutData(uint32_t pos, const uint8_t *srcData, uint32_t srcSize) 69 { 70 if (pos >= size) { 71 return false; 72 } 73 if (memcpy_s(data.get() + pos, size - pos, srcData, srcSize) != EOK) { 74 return false; 75 } 76 return true; 77 } 78 79 bool Resize(uint32_t newSize) 80 { 81 if (data != nullptr) { 82 data.reset(nullptr); 83 } 84 return Init(newSize); 85 } 86 87 uint8_t *GetBuffer() const 88 { 89 return data.get(); 90 } 91 92 uint32_t GetSize() const 93 { 94 return size; 95 } 96 97 bool Empty() const 98 { 99 return (size == 0) || (data == nullptr); 100 } 101private: 102 bool Init(uint32_t bufferSize) 103 { 104 if (bufferSize == 0) { 105 return false; 106 } 107 data = std::make_unique<uint8_t[]>(bufferSize); 108 if (data == nullptr) { 109 return false; 110 } 111 size = bufferSize; 112 return true; 113 } 114 115 std::unique_ptr<uint8_t[]> data; 116 uint32_t size; 117}; 118} 119} 120} 121#endif