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 #include "usbmgrcanceltransfer_fuzzer.h"
17
18 #include "usb_common_fuzz.h"
19 #include "usb_errors.h"
20
21 namespace OHOS {
22 const int32_t DEFAULT_ROLE_HOST = 1;
23 const int32_t BITS_PER_BYTE = 8;
24 const int32_t NUM_THREE = 3;
25 const int32_t NUM_TWO = 2;
26 const int32_t NUM_ONE = 1;
27 constexpr size_t THRESHOLD = 10;
28 namespace USB {
Convert2Uint32(const uint8_t * ptr)29 int32_t Convert2Uint32(const uint8_t *ptr)
30 {
31 if (ptr == nullptr) {
32 return 0;
33 }
34 /*
35 * Move the 0th digit 24 to the left, the first digit 16 to the left, the second digit 8 to the left,
36 * and the third digit no left
37 */
38 return (ptr[0] << BITS_PER_BYTE * NUM_THREE) | (ptr[NUM_ONE] << BITS_PER_BYTE * NUM_TWO) |
39 (ptr[NUM_TWO] << BITS_PER_BYTE) | (ptr[NUM_THREE]);
40 }
41
UsbMgrCancelTransferFuzzTest(const uint8_t * data,size_t size)42 bool UsbMgrCancelTransferFuzzTest(const uint8_t* data, size_t size)
43 {
44 if (data == nullptr || size < sizeof(int32_t)) {
45 return false;
46 }
47 int32_t endPoint = Convert2Uint32(data);
48
49 auto[res, pipe, interface] = UsbMgrPrepareFuzzEnv();
50 if (!res) {
51 USB_HILOGE(MODULE_USB_SERVICE, "prepare error");
52 return false;
53 }
54
55 auto &usbSrvClient = UsbSrvClient::GetInstance();
56
57 if (usbSrvClient.UsbCancelTransfer(const_cast<USBDevicePipe &>(pipe), endPoint)) {
58 return false;
59 }
60 return true;
61 }
62 } // USB
63 } // OHOS
64
65 /* Fuzzer entry point */
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)66 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
67 {
68 if (size < OHOS::THRESHOLD) {
69 return 0;
70 }
71 /* Run your code on data */
72 OHOS::USB::UsbMgrCancelTransferFuzzTest(data, size);
73 return 0;
74 }
75