• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
19 #include "hdf_log.h"
20 #include "message_parcel.h"
21 #include "usb_impl.h"
22 #include "usbdevice_fuzzer.h"
23 #include "v1_0/usb_interface_stub.h"
24 
25 using namespace OHOS::HDI::Usb::V1_0;
26 
27 namespace OHOS {
28 constexpr size_t THRESHOLD = 10;
29 constexpr int32_t OFFSET = 4;
30 const std::u16string USB_INTERFACE_TOKEN = u"ohos.hdi.usb.v1_0.IUsbInterface";
31 
Convert2Uint32(const uint8_t * ptr)32 uint32_t Convert2Uint32(const uint8_t *ptr)
33 {
34     if (ptr == nullptr) {
35         return 0;
36     }
37     /*
38      * Move the 0th digit 24 to the left, the first digit 16 to the left, the second digit 8 to the left,
39      * and the third digit no left
40      */
41     return (ptr[0] << 24) | (ptr[1] << 16) | (ptr[2] << 8) | (ptr[3]);
42 }
43 
DoSomethingInterestingWithMyAPI(const uint8_t * rawData,size_t size)44 bool DoSomethingInterestingWithMyAPI(const uint8_t *rawData, size_t size)
45 {
46     if (rawData == nullptr) {
47         return false;
48     }
49     uint32_t code = Convert2Uint32(rawData);
50     rawData = rawData + OFFSET;
51     size = size - OFFSET;
52 
53     MessageParcel data;
54     data.WriteInterfaceToken(USB_INTERFACE_TOKEN);
55     data.WriteBuffer(rawData, size);
56     data.RewindRead(0);
57     MessageParcel reply;
58     MessageOption option;
59 
60     sptr<IUsbInterface> g_usbInterface = IUsbInterface::Get(false);
61     if (g_usbInterface == nullptr) {
62         HDF_LOGE("%{public}s:IUsbInterface::Get() failed.", __func__);
63         return false;
64     }
65     sptr<UsbInterfaceStub> impl = new UsbInterfaceStub(g_usbInterface);
66     if (impl == nullptr) {
67         HDF_LOGE("%{public}s:new UsbInterfaceStub failed.", __func__);
68         return false;
69     }
70     impl->OnRemoteRequest(code, data, reply, option);
71 
72     return true;
73 }
74 } // namespace OHOS
75 
76 /* Fuzzer entry point */
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)77 extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
78 {
79     if (size < OHOS::THRESHOLD) {
80         return 0;
81     }
82 
83     /* Run your code on data */
84     OHOS::DoSomethingInterestingWithMyAPI(data, size);
85     return 0;
86 }
87