1 // Copyright 2020 Google LLC
2 //
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 #include <fuzzer/FuzzedDataProvider.h>
15
16 #include <algorithm>
17 #include <cstddef>
18 #include <cstdint>
19
20 #include "libusb/libusb.h"
21 #include "libusb/libusbi.h"
22
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)23 extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
24 struct libusb_transfer *transfer = NULL;
25 FuzzedDataProvider stream(data, size);
26 uint8_t bmRequestType = stream.ConsumeIntegral<uint8_t>();
27 uint8_t bRequest = stream.ConsumeIntegral<uint8_t>();
28 uint16_t wValue = stream.ConsumeIntegral<uint16_t>();
29 uint16_t wIndex = stream.ConsumeIntegral<uint16_t>();
30 uint16_t wLength = stream.ConsumeIntegral<uint16_t>();
31 std::string input = stream.ConsumeRandomLengthString();
32 const char *d = input.c_str();
33
34 transfer = libusb_alloc_transfer(0);
35 if (!transfer) {
36 return LIBUSB_ERROR_NO_MEM;
37 }
38
39 libusb_fill_control_setup((unsigned char *)d, bmRequestType, bRequest, wValue, wIndex, wLength);
40
41 // Cleanup.
42 // We cannot call libusb_free_transfer as no callbacks has occurred. Calling
43 // libusb_free_transfer without this will trigger false positive errors.
44 struct usbi_transfer *itransfer = LIBUSB_TRANSFER_TO_USBI_TRANSFER(transfer);
45 usbi_mutex_destroy(&itransfer->lock);
46 size_t priv_size = PTR_ALIGN(usbi_backend.transfer_priv_size);
47 unsigned char *ptr = (unsigned char *)itransfer - priv_size;
48 free(ptr);
49
50 return 0;
51 }
52