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 FUZZ_DATA_H 17 #define FUZZ_DATA_H 18 #include <string> 19 #include "securec.h" 20 21 namespace OHOS { 22 using namespace std; 23 namespace { 24 static constexpr uint32_t BOOL_MODULO_NUM = 2; 25 } 26 class FuzzData { 27 public: FuzzData(const uint8_t * data,const size_t size)28 explicit FuzzData(const uint8_t *data, const size_t size) 29 :pos_(0), data_(data), size_(size) {} 30 GetData()31 template <class T> T GetData() 32 { 33 T object{}; 34 size_t objectSize = sizeof(object); 35 if (data_ == nullptr || objectSize > size_ - pos_) { 36 return object; 37 } 38 errno_t ret = memcpy_s(&object, objectSize, data_ + pos_, objectSize); 39 if (ret != EOK) { 40 return {}; 41 } 42 pos_ += objectSize; 43 return object; 44 } 45 GetStringFromData(size_t pos,size_t strlen)46 std::string GetStringFromData(size_t pos, size_t strlen) 47 { 48 if (pos > size_) { 49 return "test"; 50 } 51 char cstr[strlen + 1]; 52 cstr[strlen] = '\0'; 53 pos_ = pos; 54 for (size_t i = 0; i < strlen; i++) { 55 char tmp = GetData<char>(); 56 if (tmp == '\0') { 57 tmp = '1'; 58 } 59 cstr[i] = tmp; 60 } 61 std::string str(cstr); 62 return str; 63 } 64 GenerateRandomString()65 std::string GenerateRandomString() 66 { 67 return GetStringFromData(0, (GetData<uint32_t>() % size_)); 68 } 69 GenerateRandomEnmu(T enmuMax)70 template <class T> T GenerateRandomEnmu(T enmuMax) 71 { 72 return static_cast<T>(GetData<uint32_t>() % (static_cast<uint32_t>(enmuMax) + 1)); 73 } 74 GenerateRandomBool()75 bool GenerateRandomBool() 76 { 77 return (GetData<uint32_t>() % BOOL_MODULO_NUM) == 0; 78 } 79 80 public: 81 size_t pos_; 82 83 private: 84 const uint8_t *data_; 85 const size_t size_; 86 }; 87 } // OHOS 88 #endif // FUZZ_DATA_H