• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2 * Copyright (c) 2025 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 #ifndef FUZZ_UTILS_H
16 #define FUZZ_UTILS_H
17 
18 #include <cstdint>
19 #include <securec.h>
20 #include "audio_log.h"
21 
22 namespace OHOS {
23 namespace AudioStandard {
24 
25 typedef void (*TestFuncs)();
26 class FuzzUtils {
27 public:
GetInstance()28     static FuzzUtils& GetInstance()
29     {
30         static FuzzUtils instance;
31         return instance;
32     }
33 
fuzzTest(const uint8_t * rawData,size_t size,std::vector<TestFuncs> & testFunctions)34     void fuzzTest(const uint8_t *rawData, size_t size, std::vector<TestFuncs> &testFunctions)
35     {
36         if (rawData == nullptr) {
37             return;
38         }
39 
40         rawData_ = rawData;
41         dataSize_ = size;
42         pos_ = 0;
43 
44         uint32_t code = GetData<uint32_t>();
45         uint32_t len = testFunctions.size();
46         if (len > 0) {
47             testFunctions[code % len]();
48         } else {
49             AUDIO_INFO_LOG("%{public}s: The len length is equal to 0", __func__);
50         }
51         return;
52     }
53 
54     template<class T>
GetData()55     T GetData()
56     {
57         T object {};
58         size_t objectSize = sizeof(object);
59         if (dataSize_ <= pos_) {
60             return object;
61         }
62         if (rawData_ == nullptr || objectSize > dataSize_ - pos_) {
63             return object;
64         }
65         errno_t ret = memcpy_s(&object, objectSize, rawData_ + pos_, objectSize);
66         if (ret != EOK) {
67             return {};
68         }
69         pos_ += objectSize;
70         return object;
71     }
72 
73 private:
74     FuzzUtils() = default;
75     ~FuzzUtils() = default;
76 
77     // Disable copy and move
78     FuzzUtils(const FuzzUtils&) = delete;
79     FuzzUtils& operator=(const FuzzUtils&) = delete;
80     FuzzUtils(FuzzUtils&&) = delete;
81     FuzzUtils& operator=(FuzzUtils&&) = delete;
82 
83     const uint8_t *rawData_ = nullptr;
84     size_t dataSize_ = 0;
85     size_t pos_ = 0;
86 };
87 
88 } // namespace AudioStandard
89 } // namespace OHOS
90 
91 #endif // FUZZ_UTILS_H