1 /*
2  * Copyright 2019 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <stddef.h>
18 #include <stdint.h>
19 #include "fuzz/helpers.h"
20 #include "hal/fuzz/fuzz_hci_hal.h"
21 #include "hci/fuzz/hci_layer_fuzz_client.h"
22 #include "hci/hci_layer.h"
23 #include "module.h"
24 #include "os/fuzz/fake_timerfd.h"
25 #include "os/log.h"
26 
27 #include <fuzzer/FuzzedDataProvider.h>
28 
29 using bluetooth::FuzzTestModuleRegistry;
30 using bluetooth::fuzz::GetArbitraryBytes;
31 using bluetooth::hal::HciHal;
32 using bluetooth::hal::fuzz::FuzzHciHal;
33 using bluetooth::hci::fuzz::HciLayerFuzzClient;
34 using bluetooth::os::fuzz::fake_timerfd_advance;
35 using bluetooth::os::fuzz::fake_timerfd_cap_at;
36 using bluetooth::os::fuzz::fake_timerfd_reset;
37 
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)38 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
39   FuzzedDataProvider dataProvider(data, size);
40   fake_timerfd_cap_at(1999);  // prevent command timeouts
41 
42   static FuzzTestModuleRegistry moduleRegistry = FuzzTestModuleRegistry();
43   FuzzHciHal* fuzzHal = moduleRegistry.Inject<FuzzHciHal>(&HciHal::Factory);
44   HciLayerFuzzClient* fuzzClient = moduleRegistry.Start<HciLayerFuzzClient>();
45 
46   while (dataProvider.remaining_bytes() > 0) {
47     const uint8_t action = dataProvider.ConsumeIntegralInRange(0, 5);
48     switch (action) {
49       case 1:
50         fake_timerfd_advance(dataProvider.ConsumeIntegral<uint64_t>());
51         break;
52       case 2:
53         fuzzHal->injectArbitrary(dataProvider);
54         break;
55       case 3:
56         fuzzClient->injectArbitrary(dataProvider);
57         break;
58     }
59   }
60 
61   moduleRegistry.WaitForIdleAndStopAll();
62   fake_timerfd_reset();
63   return 0;
64 }
65