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 CLOUD_FUZZER_HELPER_H 17 #define CLOUD_FUZZER_HELPER_H 18 19 #include "securec.h" 20 #include <string> 21 22 namespace OHOS { 23 class FuzzData { 24 public: FuzzData(const uint8_t * data,size_t size)25 FuzzData(const uint8_t *data, size_t size) 26 { 27 baseData = data; 28 baseSize = size; 29 } 30 ResetData(size_t newSize)31 void ResetData(size_t newSize) 32 { 33 if (newSize <= baseSize) { 34 baseSize = newSize; 35 } 36 basePos = 0; 37 } 38 39 template<class T> GetData()40 T GetData() 41 { 42 T object{}; 43 size_t objectSize = sizeof(object); 44 if (baseData == nullptr || objectSize > baseSize - basePos) { 45 return object; 46 } 47 if (memcpy_s(&object, objectSize, baseData + basePos, objectSize) != EOK) { 48 return {}; 49 } 50 basePos = basePos + objectSize; 51 return object; 52 } 53 GetRemainSize()54 size_t GetRemainSize() const 55 { 56 return baseSize - basePos; 57 } 58 GetStringFromData(int len)59 std::string GetStringFromData(int len) 60 { 61 if (len <= 0 || baseData == nullptr || basePos >= baseSize) { 62 return ""; 63 } 64 65 std::string cstr; 66 for (int i = 0; i < len; ++i) { 67 if (basePos >= baseSize) { 68 basePos = 0; 69 } 70 char tmp = GetData<char>(); 71 if (tmp == '\0') { 72 cstr.push_back('1'); 73 } else { 74 cstr.push_back(tmp); 75 } 76 } 77 return cstr; 78 } 79 80 private: 81 const uint8_t *baseData{nullptr}; 82 size_t baseSize{0}; 83 size_t basePos{0}; 84 }; 85 } // namespace OHOS 86 #endif // CLOUD_FUZZER_HELPER_H 87