1 /*
2 * Copyright (c) 2025 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 "usbserialwrite_fuzzer.h"
17
18 #include <cstddef>
19 #include <cstdint>
20 #include "hdf_log.h"
21 #include "usbserialcommonfunction_fuzzer.h"
22
23 using namespace OHOS::HDI::Usb::UsbSerialDdk::V1_0;
24
25 namespace OHOS {
26 constexpr size_t THRESHOLD = 10;
27
28 namespace USBSerial {
29
UsbSerialWriteFuzzTest(const uint8_t * data,size_t size)30 bool UsbSerialWriteFuzzTest(const uint8_t *data, size_t size)
31 {
32 sptr<IUsbSerialDdk> usbSerialInterface = IUsbSerialDdk::Get();
33 int32_t ret = usbSerialInterface->Init();
34 if (ret != HDF_SUCCESS) {
35 HDF_LOGE("%s: init failed, ret = %d", __func__, ret);
36 return false;
37 }
38
39 UsbSerialDeviceHandle* device = nullptr;
40 ret = UsbSerialFuzzTestHostModeInit(usbSerialInterface, device);
41 if (ret != HDF_SUCCESS) {
42 HDF_LOGE("%s: UsbSerial open device failed, ret = %d", __func__, ret);
43 return false;
44 }
45 std::vector<uint8_t> buff;
46 uint32_t bytesWritten = 0;
47 buff.assign(data, data + size); // copy data to buff
48 ret = usbSerialInterface->Write(*device, buff, bytesWritten);
49 ret = usbSerialInterface->Close(*device);
50 if (ret != HDF_SUCCESS) {
51 HDF_LOGE("%{public}s: close device failed", __func__);
52 usbSerialInterface->Release();
53 return false;
54 }
55 ret = usbSerialInterface->Release();
56 if (ret != HDF_SUCCESS) {
57 HDF_LOGE("%{public}s: release failed", __func__);
58 return false;
59 }
60 return true;
61 }
62 } // namespace USBSerial
63 } // namespace OHOS
64
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)65 extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
66 {
67 if (size < OHOS::THRESHOLD) {
68 return 0;
69 }
70 OHOS::USBSerial::UsbSerialWriteFuzzTest(data, size);
71 return 0;
72 }