1 /*
2 * Copyright (c) 2022 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 <cstddef>
17 #include <cstdint>
18 #include <unistd.h>
19
20 #include "UsbSubscriberTest.h"
21 #include "hdf_log.h"
22 #include "usbasynccancel_fuzzer.h"
23 #include "v1_2/iusb_interface.h"
24
25 using namespace OHOS::HDI::Usb::V1_2;
26 using OHOS::HDI::Usb::V1_2::UsbDev;
27 using namespace OHOS::USB;
28
29 namespace OHOS {
30 constexpr int32_t BITS_PER_BYTE = 8;
31 constexpr int32_t NUM_THREE = 3;
32 constexpr int32_t NUM_TWO = 2;
33 constexpr int32_t NUM_ONE = 1;
34
Convert2Uint32(const uint8_t * ptr)35 uint32_t Convert2Uint32(const uint8_t *ptr)
36 {
37 if (ptr == nullptr) {
38 return 0;
39 }
40 /*
41 * Move the 0th digit 24 to the left, the first digit 16 to the left, the second digit 8 to the left,
42 * and the third digit no left
43 */
44 return (ptr[0] << BITS_PER_BYTE * NUM_THREE) | (ptr[NUM_ONE] << BITS_PER_BYTE * NUM_TWO) |
45 (ptr[NUM_TWO] << BITS_PER_BYTE) | (ptr[NUM_THREE]);
46 }
47
DoSomethingInterestingWithMyAPI(const uint8_t * rawData,size_t size)48 bool DoSomethingInterestingWithMyAPI(const uint8_t *rawData, size_t size)
49 {
50 if (rawData == nullptr) {
51 return false;
52 }
53 uint32_t endPoint = Convert2Uint32(rawData);
54 sptr<OHOS::HDI::Usb::V1_2::IUsbInterface> usbInterface = OHOS::HDI::Usb::V1_2::IUsbInterface::Get(false);
55 if (usbInterface == nullptr) {
56 HDF_LOGE("%{public}s:IUsbInterface::Get() failed.", __func__);
57 return false;
58 }
59 sptr<UsbSubscriberTest> subscriber = new UsbSubscriberTest();
60 int32_t ret = usbInterface->BindUsbdSubscriber(subscriber);
61 if (ret != HDF_SUCCESS) {
62 HDF_LOGE("%{public}s: bind usbd subscriber failed", __func__);
63 return ret;
64 }
65 sleep(1);
66 UsbDev dev;
67 dev.busNum = subscriber->busNum_;
68 dev.devAddr = subscriber->devAddr_;
69 ret = usbInterface->OpenDevice(dev);
70 if (ret != HDF_SUCCESS) {
71 HDF_LOGE("%{public}s: open device failed", __func__);
72 return ret;
73 }
74 usbInterface->UsbCancelTransfer(dev, endPoint);
75
76 return true;
77 }
78 } // namespace OHOS
79
80 /* Fuzzer entry point */
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)81 extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
82 {
83 /* Run your code on data */
84 OHOS::DoSomethingInterestingWithMyAPI(data, size);
85 return 0;
86 }
87