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 <cstdint>
19 #include <string>
20 #include "securec.h"
21 
22 namespace OHOS {
23 
24 constexpr uint32_t BOOL_MODULO_NUM = 2;
25 
26 using namespace std;
27 class FuzzData {
28 public:
FuzzData(const uint8_t * data,const size_t size)29     explicit FuzzData(const uint8_t *data, const size_t size) : 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 
GenerateRandomInt32()70     int32_t GenerateRandomInt32()
71     {
72         return GetData<int32_t>();
73     }
74 
GenerateRandomEnmu(T enmuMax)75     template <class T> T GenerateRandomEnmu(T enmuMax)
76     {
77         return static_cast<T>(GetData<uint32_t>() % (static_cast<uint32_t>(enmuMax) + 1));
78     }
79 
GenerateRandomBool()80     bool GenerateRandomBool()
81     {
82         return (GetData<uint32_t>() % BOOL_MODULO_NUM) == 0;
83     }
84 
GetSize()85     size_t GetSize() const
86     {
87         return size_;
88     }
89 
90 public:
91     size_t pos_;
92 
93 private:
94     const uint8_t *data_;
95     const size_t size_;
96 };
97 } // namespace OHOS
98 #endif // FUZZ_DATA_H