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