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 <fuzzer/FuzzedDataProvider.h>
18 #include <stddef.h>
19 #include <stdint.h>
20 
21 #include "fuzz/helpers.h"
22 #include "hci/acl_manager.h"
23 #include "hci/fuzz/fuzz_hci_layer.h"
24 #include "hci/hci_layer.h"
25 #include "module.h"
26 #include "os/fake_timer/fake_timerfd.h"
27 
28 // TODO(b/369381361) Enfore -Wmissing-prototypes
29 #pragma GCC diagnostic ignored "-Wmissing-prototypes"
30 
31 using bluetooth::FuzzTestModuleRegistry;
32 using bluetooth::fuzz::GetArbitraryBytes;
33 using bluetooth::hci::AclManager;
34 using bluetooth::hci::HciLayer;
35 using bluetooth::hci::fuzz::FuzzHciLayer;
36 using bluetooth::os::fake_timer::fake_timerfd_advance;
37 using bluetooth::os::fake_timer::fake_timerfd_cap_at;
38 using bluetooth::os::fake_timer::fake_timerfd_reset;
39 
40 constexpr int32_t kMinTimeAdvanced = 0;
41 /**
42  * kMaxTotalTimeAdvanced value is referenced from
43  * kDefaultConfigSaveDelay defined in storage_module.cc
44  */
45 constexpr int32_t kMaxTotalTimeAdvanced = 3000;
46 
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)47 extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
48   FuzzedDataProvider dataProvider(data, size);
49 
50   static FuzzTestModuleRegistry moduleRegistry = FuzzTestModuleRegistry();
51   FuzzHciLayer* fuzzHci = moduleRegistry.Inject<FuzzHciLayer>(&HciLayer::Factory);
52   fuzzHci->TurnOnAutoReply(&dataProvider);
53   moduleRegistry.Start<AclManager>();
54   fuzzHci->TurnOffAutoReply();
55   uint64_t totalAdvanceTime = 0;
56 
57   while (dataProvider.remaining_bytes() > 0) {
58     const uint8_t action = dataProvider.ConsumeIntegralInRange(0, 2);
59 
60     switch (action) {
61       case 1: {
62         uint64_t advanceTime = dataProvider.ConsumeIntegralInRange<uint64_t>(kMinTimeAdvanced,
63                                                                              kMaxTotalTimeAdvanced);
64         totalAdvanceTime += advanceTime;
65         if (totalAdvanceTime < kMaxTotalTimeAdvanced) {
66           fake_timerfd_advance(advanceTime);
67         }
68         break;
69       }
70       case 2: {
71         fuzzHci->injectArbitrary(dataProvider);
72         break;
73       }
74     }
75   }
76 
77   moduleRegistry.WaitForIdleAndStopAll();
78   fake_timerfd_reset();
79   return 0;
80 }
81