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