1 /*
2 * Copyright (c) 2021 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 #include "CommandLine_fuzzer.h"
17
18 extern int hiperf_fuzzer_main(const int argc, const char *argv[]);
19 namespace OHOS {
20 const static int32_t MAX_TEST_ARGS_NUMBER = 20;
21 const static size_t MAX_TEST_ARGS_LEN = 4096;
22
FuzzCommandLine(const char * subcommand,const uint8_t * data,size_t size)23 bool FuzzCommandLine(const char *subcommand, const uint8_t *data, size_t size)
24 {
25 char buf[DATA_MAX_SIZE] = { 0 };
26 if (memcpy_s(buf, sizeof(buf) - 1, data, size) != 0) { // 1 : make sure end of '\0'
27 return false;
28 }
29 const char *argptr = reinterpret_cast<const char *>(buf);
30 const char *argsdata = argptr;
31 std::vector<const char *> argv;
32
33 // argv[0]
34 argv.emplace_back("hiperf");
35
36 // argv[1]
37 if (subcommand != nullptr and subcommand[0] != '\0') {
38 argv.emplace_back(subcommand);
39 }
40
41 // argv[2]
42 argv.emplace_back(argptr);
43
44 // argv[*]
45 for (size_t i = 0; i < std::min(MAX_TEST_ARGS_LEN, size); i++) {
46 if (argsdata[i] == '\0') {
47 argv.emplace_back(argptr);
48 argptr = &argsdata[i + 1];
49 }
50 if (argv.size() > MAX_TEST_ARGS_NUMBER) {
51 break;
52 }
53 }
54 #ifdef DEBUG_HIPERF_FUZZ
55 std::cout << " size " << argv.size() << std::endl;
56 #endif
57 hiperf_fuzzer_main(static_cast<int>(argv.size()), argv.data());
58
59 return 0;
60 }
61 } // namespace OHOS
62
63 /* Fuzzer entry point */
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)64 extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
65 {
66 #ifdef DEBUG_HIPERF_FUZZ
67 ScopeDebugLevel mix(LEVEL_VERBOSE, true);
68 DebugLogger::GetInstance()->Disable(false);
69 #else
70 OHOS::Developtools::HiPerf::StdoutRecord noStdOut("/dev/null", "w");
71 #endif
72 /* Run your code on data */
73 OHOS::FuzzCommandLine("", data, size);
74 OHOS::FuzzCommandLine("stat", data, size);
75 OHOS::FuzzCommandLine("record", data, size);
76 OHOS::FuzzCommandLine("report", data, size);
77 OHOS::FuzzCommandLine("list", data, size);
78 OHOS::FuzzCommandLine("help", data, size);
79 return 0;
80 }
81