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