1 /*
2  *  Copyright 2021 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 <bluetooth/log.h>
18 #include <fcntl.h>
19 #include <gmock/gmock.h>
20 #include <gtest/gtest.h>
21 #include <unistd.h>
22 
23 #include <cstddef>
24 #include <cstdint>
25 #include <cstdio>
26 #include <future>
27 #include <map>
28 #include <optional>
29 #include <vector>
30 
31 #include "btif/include/btif_hh.h"
32 #include "hal/hci_hal.h"
33 #include "hci/acl_manager.h"
34 #include "hci/acl_manager/classic_acl_connection.h"
35 #include "hci/acl_manager/connection_management_callbacks.h"
36 #include "hci/acl_manager/le_acl_connection.h"
37 #include "hci/acl_manager/le_connection_management_callbacks.h"
38 #include "hci/acl_manager_mock.h"
39 #include "hci/address.h"
40 #include "hci/address_with_type.h"
41 #include "hci/controller_interface_mock.h"
42 #include "hci/distance_measurement_manager_mock.h"
43 #include "hci/le_advertising_manager_mock.h"
44 #include "hci/le_scanning_manager_mock.h"
45 #include "include/hardware/ble_scanner.h"
46 #include "main/shim/acl.h"
47 #include "main/shim/acl_interface.h"
48 #include "main/shim/ble_scanner_interface_impl.h"
49 #include "main/shim/dumpsys.h"
50 #include "main/shim/helpers.h"
51 #include "main/shim/le_advertising_manager.h"
52 #include "main/shim/le_scanning_manager.h"
53 #include "main/shim/utils.h"
54 #include "os/handler.h"
55 #include "os/queue.h"
56 #include "os/thread.h"
57 #include "packet/packet_view.h"
58 #include "stack/btm/btm_int_types.h"
59 #include "stack/btm/btm_sec_cb.h"
60 #include "stack/include/bt_hdr.h"
61 #include "stack/include/bt_types.h"
62 #include "stack/include/hci_error_code.h"
63 #include "stack/l2cap/l2c_int.h"
64 #include "test/common/jni_thread.h"
65 #include "test/common/main_handler.h"
66 #include "test/common/mock_functions.h"
67 #include "test/mock/mock_main_shim_entry.h"
68 #include "types/ble_address_with_type.h"
69 #include "types/hci_role.h"
70 #include "types/raw_address.h"
71 
72 // TODO(b/369381361) Enfore -Wmissing-prototypes
73 #pragma GCC diagnostic ignored "-Wmissing-prototypes"
74 
75 using ::testing::_;
76 
77 using namespace bluetooth;
78 using namespace testing;
79 using HciHandle = uint16_t;
80 
81 namespace test = bluetooth::hci::testing;
82 
83 const uint8_t kMaxLeAcceptlistSize = 16;
84 const uint8_t kMaxAddressResolutionSize = kMaxLeAcceptlistSize;
85 
86 tL2C_CB l2cb;
87 tBTM_CB btm_cb;
88 tBTM_SEC_CB btm_sec_cb;
89 btif_hh_cb_t btif_hh_cb;
90 
91 struct bluetooth::hci::LeScanningManager::impl : public bluetooth::hci::LeAddressManagerCallback {};
92 
93 namespace {
94 const hci::Address kAddress = {{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}};
95 const hci::ClassOfDevice kCod = {{0x11, 0x22, 0x33}};
96 constexpr double kMaxAbsoluteError = .0000001;
97 constexpr double kTicksInMs = 20479.375;
98 constexpr double kTicksInSec = 20.479375;
99 constexpr uint16_t kTicks = 32767;
100 
101 std::map<std::string, std::promise<uint16_t>> mock_function_handle_promise_map;
102 
103 // Utility to provide a file descriptor for /dev/null when possible, but
104 // defaulting to STDERR when not possible.
105 class DevNullOrStdErr {
106 public:
DevNullOrStdErr()107   DevNullOrStdErr() { fd_ = open("/dev/null", O_CLOEXEC | O_WRONLY); }
~DevNullOrStdErr()108   ~DevNullOrStdErr() {
109     if (fd_ != -1) {
110       close(fd_);
111     }
112     fd_ = -1;
113   }
Fd() const114   int Fd() const { return (fd_ == -1) ? STDERR_FILENO : fd_; }
115 
116 private:
117   int fd_{-1};
118 };
119 
120 }  // namespace
121 
122 bluetooth::common::TimestamperInMilliseconds timestamper_in_milliseconds;
123 
mock_on_send_data_upwards(BT_HDR *)124 void mock_on_send_data_upwards(BT_HDR*) {}
125 
mock_on_packets_completed(uint16_t,uint16_t)126 void mock_on_packets_completed(uint16_t /*handle*/, uint16_t /*num_packets*/) {}
127 
mock_connection_classic_on_connected(const RawAddress &,uint16_t,uint8_t,bool)128 void mock_connection_classic_on_connected(const RawAddress& /*bda*/, uint16_t /*handle*/,
129                                           uint8_t /*enc_mode*/, bool /*locally_initiated*/) {}
130 
mock_connection_classic_on_failed(const RawAddress &,tHCI_STATUS,bool)131 void mock_connection_classic_on_failed(const RawAddress& /*bda*/, tHCI_STATUS /*status*/,
132                                        bool /*locally_initiated*/) {}
133 
mock_connection_classic_on_disconnected(tHCI_STATUS,uint16_t handle,tHCI_STATUS)134 void mock_connection_classic_on_disconnected(tHCI_STATUS /*status*/, uint16_t handle,
135                                              tHCI_STATUS /*reason*/) {
136   ASSERT_TRUE(mock_function_handle_promise_map.find(__func__) !=
137               mock_function_handle_promise_map.end());
138   mock_function_handle_promise_map[__func__].set_value(handle);
139 }
mock_connection_le_on_connected(const tBLE_BD_ADDR &,uint16_t,tHCI_ROLE,uint16_t,uint16_t,uint16_t,const RawAddress &,const RawAddress &,tBLE_ADDR_TYPE,bool)140 void mock_connection_le_on_connected(const tBLE_BD_ADDR& /*address_with_type*/, uint16_t /*handle*/,
141                                      tHCI_ROLE /*role*/, uint16_t /*conn_interval*/,
142                                      uint16_t /*conn_latency*/, uint16_t /*conn_timeout*/,
143                                      const RawAddress& /*local_rpa*/,
144                                      const RawAddress& /*peer_rpa*/,
145                                      tBLE_ADDR_TYPE /*peer_addr_type*/,
146                                      bool /*can_read_discoverable_characteristics*/) {}
mock_connection_le_on_failed(const tBLE_BD_ADDR &,uint16_t,bool,tHCI_STATUS)147 void mock_connection_le_on_failed(const tBLE_BD_ADDR& /*address_with_type*/, uint16_t /*handle*/,
148                                   bool /*enhanced*/, tHCI_STATUS /*status*/) {}
149 static std::promise<uint16_t> mock_connection_le_on_disconnected_promise;
mock_connection_le_on_disconnected(tHCI_STATUS,uint16_t handle,tHCI_STATUS)150 void mock_connection_le_on_disconnected(tHCI_STATUS /*status*/, uint16_t handle,
151                                         tHCI_STATUS /*reason*/) {
152   mock_connection_le_on_disconnected_promise.set_value(handle);
153 }
154 
mock_link_classic_on_read_remote_extended_features_complete(uint16_t,uint8_t,uint8_t,uint64_t)155 void mock_link_classic_on_read_remote_extended_features_complete(uint16_t /*handle*/,
156                                                                  uint8_t /*current_page_number*/,
157                                                                  uint8_t /*max_page_number*/,
158                                                                  uint64_t /*features*/) {}
159 
160 shim::acl_interface_t acl_interface{
161         .on_send_data_upwards = mock_on_send_data_upwards,
162         .on_packets_completed = mock_on_packets_completed,
163 
164         .connection.classic.on_connected = mock_connection_classic_on_connected,
165         .connection.classic.on_failed = mock_connection_classic_on_failed,
166         .connection.classic.on_disconnected = mock_connection_classic_on_disconnected,
167         .connection.classic.on_connect_request = nullptr,
168 
169         .connection.le.on_connected = mock_connection_le_on_connected,
170         .connection.le.on_failed = mock_connection_le_on_failed,
171         .connection.le.on_disconnected = mock_connection_le_on_disconnected,
172 
173         .link.classic.on_authentication_complete = nullptr,
174         .link.classic.on_central_link_key_complete = nullptr,
175         .link.classic.on_change_connection_link_key_complete = nullptr,
176         .link.classic.on_encryption_change = nullptr,
177         .link.classic.on_flow_specification_complete = nullptr,
178         .link.classic.on_flush_occurred = nullptr,
179         .link.classic.on_mode_change = nullptr,
180         .link.classic.on_packet_type_changed = nullptr,
181         .link.classic.on_qos_setup_complete = nullptr,
182         .link.classic.on_read_afh_channel_map_complete = nullptr,
183         .link.classic.on_read_automatic_flush_timeout_complete = nullptr,
184         .link.classic.on_sniff_subrating = nullptr,
185         .link.classic.on_read_clock_complete = nullptr,
186         .link.classic.on_read_clock_offset_complete = nullptr,
187         .link.classic.on_read_failed_contact_counter_complete = nullptr,
188         .link.classic.on_read_link_policy_settings_complete = nullptr,
189         .link.classic.on_read_link_quality_complete = nullptr,
190         .link.classic.on_read_link_supervision_timeout_complete = nullptr,
191         .link.classic.on_read_remote_version_information_complete = nullptr,
192         .link.classic.on_read_remote_extended_features_complete =
193                 mock_link_classic_on_read_remote_extended_features_complete,
194         .link.classic.on_read_rssi_complete = nullptr,
195         .link.classic.on_read_transmit_power_level_complete = nullptr,
196         .link.classic.on_role_change = nullptr,
197         .link.classic.on_role_discovery_complete = nullptr,
198 
199         .link.le.on_connection_update = nullptr,
200         .link.le.on_parameter_update_request = nullptr,
201         .link.le.on_data_length_change = nullptr,
202         .link.le.on_read_remote_version_information_complete = nullptr,
203 };
204 
GetMockAclInterface()205 const shim::acl_interface_t& GetMockAclInterface() { return acl_interface; }
206 
207 struct hci_packet_parser_t;
hci_packet_parser_get_interface()208 const hci_packet_parser_t* hci_packet_parser_get_interface() { return nullptr; }
209 struct hci_t;
210 struct packet_fragmenter_t;
packet_fragmenter_get_interface()211 const packet_fragmenter_t* packet_fragmenter_get_interface() { return nullptr; }
212 
213 template <typename T>
214 class MockEnQueue : public os::IQueueEnqueue<T> {
215   using EnqueueCallback = base::Callback<std::unique_ptr<T>()>;
216 
RegisterEnqueue(os::Handler *,EnqueueCallback)217   void RegisterEnqueue(os::Handler* /*handler*/, EnqueueCallback /*callback*/) override {}
UnregisterEnqueue()218   void UnregisterEnqueue() override {}
219 };
220 
221 template <typename T>
222 class MockDeQueue : public os::IQueueDequeue<T> {
223   using DequeueCallback = base::Callback<void()>;
224 
RegisterDequeue(os::Handler *,DequeueCallback)225   void RegisterDequeue(os::Handler* /*handler*/, DequeueCallback /*callback*/) override {}
UnregisterDequeue()226   void UnregisterDequeue() override {}
TryDequeue()227   std::unique_ptr<T> TryDequeue() override { return nullptr; }
228 };
229 
230 class MockClassicAclConnection : public bluetooth::hci::acl_manager::ClassicAclConnection {
231 public:
MockClassicAclConnection(const hci::Address & address,uint16_t handle)232   MockClassicAclConnection(const hci::Address& address, uint16_t handle) {
233     address_ = address;  // ClassicAclConnection
234     handle_ = handle;    // AclConnection
235   }
236 
RegisterCallbacks(hci::acl_manager::ConnectionManagementCallbacks * callbacks,os::Handler * handler)237   void RegisterCallbacks(hci::acl_manager::ConnectionManagementCallbacks* callbacks,
238                          os::Handler* handler) override {
239     callbacks_ = callbacks;
240     handler_ = handler;
241   }
242 
243   // Returns the bidi queue for this mock connection
GetAclQueueEnd() const244   AclConnection::QueueUpEnd* GetAclQueueEnd() const override { return &mock_acl_queue_; }
245 
246   mutable common::BidiQueueEnd<hci::BasePacketBuilder, packet::PacketView<hci::kLittleEndian>>
247           mock_acl_queue_{&tx_, &rx_};
248 
249   MockEnQueue<hci::BasePacketBuilder> tx_;
250   MockDeQueue<packet::PacketView<hci::kLittleEndian>> rx_;
251 
ReadRemoteVersionInformation()252   bool ReadRemoteVersionInformation() override { return true; }
ReadRemoteSupportedFeatures()253   bool ReadRemoteSupportedFeatures() override { return true; }
254 
255   std::function<void(uint8_t)> read_remote_extended_features_function_{};
256 
ReadRemoteExtendedFeatures(uint8_t page_number)257   bool ReadRemoteExtendedFeatures(uint8_t page_number) override {
258     if (read_remote_extended_features_function_) {
259       read_remote_extended_features_function_(page_number);
260     }
261     return true;
262   }
263 
Disconnect(hci::DisconnectReason)264   bool Disconnect(hci::DisconnectReason /*reason*/) override {
265     disconnect_cnt_++;
266     disconnect_promise_.set_value(handle_);
267     return true;
268   }
269 
270   std::promise<uint16_t> disconnect_promise_;
271 
272   hci::acl_manager::ConnectionManagementCallbacks* callbacks_{nullptr};
273   os::Handler* handler_{nullptr};
274 
275   int disconnect_cnt_{0};
276 };
277 
278 class MockLeAclConnection : public bluetooth::hci::acl_manager::LeAclConnection {
279 public:
MockLeAclConnection(uint16_t handle,hci::acl_manager::RoleSpecificData role_specific_data,hci::AddressWithType remote_address)280   MockLeAclConnection(uint16_t handle, hci::acl_manager::RoleSpecificData role_specific_data,
281                       hci::AddressWithType remote_address) {
282     handle_ = handle;
283     role_specific_data_ = role_specific_data;
284     remote_address_ = remote_address;
285   }
286 
RegisterCallbacks(hci::acl_manager::LeConnectionManagementCallbacks * callbacks,os::Handler * handler)287   void RegisterCallbacks(hci::acl_manager::LeConnectionManagementCallbacks* callbacks,
288                          os::Handler* handler) override {
289     callbacks_ = callbacks;
290     handler_ = handler;
291   }
292 
293   // Returns the bidi queue for this mock connection
GetAclQueueEnd() const294   AclConnection::QueueUpEnd* GetAclQueueEnd() const override { return &mock_acl_queue_; }
295 
296   mutable common::BidiQueueEnd<hci::BasePacketBuilder, packet::PacketView<hci::kLittleEndian>>
297           mock_acl_queue_{&tx_, &rx_};
298 
299   MockEnQueue<hci::BasePacketBuilder> tx_;
300   MockDeQueue<packet::PacketView<hci::kLittleEndian>> rx_;
301 
ReadRemoteVersionInformation()302   bool ReadRemoteVersionInformation() override { return true; }
LeReadRemoteFeatures()303   bool LeReadRemoteFeatures() override { return true; }
304 
Disconnect(hci::DisconnectReason)305   void Disconnect(hci::DisconnectReason /*reason*/) override {
306     disconnect_cnt_++;
307     disconnect_promise_.set_value(handle_);
308   }
309 
310   std::promise<uint16_t> disconnect_promise_;
311 
312   hci::acl_manager::LeConnectionManagementCallbacks* callbacks_{nullptr};
313   os::Handler* handler_{nullptr};
314 
315   hci::LeAclConnectionInterface* le_acl_connection_interface_{nullptr};
316 
317   int disconnect_cnt_{0};
318 };
319 
320 namespace bluetooth {
321 namespace shim {
322 namespace testing {
323 extern os::Handler* mock_handler_;
324 
325 }  // namespace testing
326 }  // namespace shim
327 
328 namespace hal {
__anon937e4e8f0202() 329 const ModuleFactory HciHal::Factory = ModuleFactory([]() { return nullptr; });
330 }  // namespace hal
331 
332 }  // namespace bluetooth
333 
334 class MainShimTest : public testing::Test {
335 public:
336 protected:
SetUp()337   void SetUp() override {
338     main_thread_start_up();
339     post_on_bt_main([]() { log::info("Main thread started"); });
340 
341     thread_ = new os::Thread("acl_thread", os::Thread::Priority::NORMAL);
342     handler_ = new os::Handler(thread_);
343 
344     /* extern */ test::mock_controller_ = new bluetooth::hci::testing::MockControllerInterface();
345     /* extern */ test::mock_acl_manager_ = new bluetooth::hci::testing::MockAclManager();
346     /* extern */ test::mock_le_scanning_manager_ =
347             new bluetooth::hci::testing::MockLeScanningManager();
348     /* extern */ test::mock_le_advertising_manager_ =
349             new bluetooth::hci::testing::MockLeAdvertisingManager();
350     /* extern */ test::mock_distance_measurement_manager_ =
351             new bluetooth::hci::testing::MockDistanceMeasurementManager();
352   }
TearDown()353   void TearDown() override {
354     delete test::mock_controller_;
355     test::mock_controller_ = nullptr;
356     delete test::mock_acl_manager_;
357     test::mock_acl_manager_ = nullptr;
358     delete test::mock_le_advertising_manager_;
359     test::mock_le_advertising_manager_ = nullptr;
360     delete test::mock_le_scanning_manager_;
361     test::mock_le_scanning_manager_ = nullptr;
362     delete test::mock_distance_measurement_manager_;
363     test::mock_distance_measurement_manager_ = nullptr;
364 
365     handler_->Clear();
366     delete handler_;
367     delete thread_;
368 
369     post_on_bt_main([]() { log::info("Main thread stopped"); });
370     main_thread_shut_down();
371     reset_mock_function_count_map();
372   }
373   os::Thread* thread_{nullptr};
374   os::Handler* handler_{nullptr};
375 
376   // Convenience method to create ACL objects
MakeAcl()377   std::unique_ptr<shim::Acl> MakeAcl() {
378     EXPECT_CALL(*test::mock_acl_manager_, RegisterCallbacks(_, _)).Times(1);
379     EXPECT_CALL(*test::mock_acl_manager_, RegisterLeCallbacks(_, _)).Times(1);
380     EXPECT_CALL(*test::mock_controller_, RegisterCompletedMonitorAclPacketsCallback(_)).Times(1);
381     EXPECT_CALL(*test::mock_controller_, UnregisterCompletedMonitorAclPacketsCallback).Times(1);
382     return std::make_unique<shim::Acl>(handler_, GetMockAclInterface(), kMaxLeAcceptlistSize,
383                                        kMaxAddressResolutionSize);
384   }
385 };
386 
387 class MainShimTestWithClassicConnection : public MainShimTest {
388 protected:
SetUp()389   void SetUp() override {
390     MainShimTest::SetUp();
391     hci::Address address({0x11, 0x22, 0x33, 0x44, 0x55, 0x66});
392 
393     acl_ = MakeAcl();
394 
395     // Create connection
396     EXPECT_CALL(*test::mock_acl_manager_, CreateConnection(_)).Times(1);
397     acl_->CreateClassicConnection(address);
398 
399     // Respond with a mock connection created
400     auto connection = std::make_unique<MockClassicAclConnection>(address, 123);
401     ASSERT_EQ(123, connection->GetHandle());
402     ASSERT_EQ(hci::Address({0x11, 0x22, 0x33, 0x44, 0x55, 0x66}), connection->GetAddress());
403     raw_connection_ = connection.get();
404 
405     acl_->OnConnectSuccess(std::move(connection));
406     ASSERT_EQ(nullptr, connection);
407     ASSERT_NE(nullptr, raw_connection_->callbacks_);
408   }
409 
TearDown()410   void TearDown() override {
411     // Specify local disconnect request
412     auto tx_disconnect_future = raw_connection_->disconnect_promise_.get_future();
413     acl_->DisconnectClassic(123, HCI_SUCCESS, {});
414 
415     // Wait for disconnect to be received
416     uint16_t result = tx_disconnect_future.get();
417     ASSERT_EQ(123, result);
418 
419     // Now emulate the remote disconnect response
420     auto handle_promise = std::promise<uint16_t>();
421     auto rx_disconnect_future = handle_promise.get_future();
422     mock_function_handle_promise_map["mock_connection_classic_on_disconnected"] =
423             std::move(handle_promise);
424     raw_connection_->callbacks_->OnDisconnection(hci::ErrorCode::SUCCESS);
425 
426     result = rx_disconnect_future.get();
427     ASSERT_EQ(123, result);
428 
429     // *Our* task completing indicates reactor is done
430     std::promise<void> done;
431     auto future = done.get_future();
432     handler_->Call([](std::promise<void> done) { done.set_value(); }, std::move(done));
433     future.wait();
434 
435     acl_.reset();
436 
437     MainShimTest::TearDown();
438   }
439   std::unique_ptr<shim::Acl> acl_;
440   MockClassicAclConnection* raw_connection_{nullptr};
441 };
442 
TEST_F(MainShimTest,Nop)443 TEST_F(MainShimTest, Nop) {}
444 
TEST_F(MainShimTest,Acl_Lifecycle)445 TEST_F(MainShimTest, Acl_Lifecycle) {
446   auto acl = MakeAcl();
447   acl.reset();
448   acl = MakeAcl();
449 }
450 
TEST_F(MainShimTest,helpers)451 TEST_F(MainShimTest, helpers) {
452   uint8_t reason = 0;
453   do {
454     hci::ErrorCode gd_error_code = static_cast<hci::ErrorCode>(reason);
455     tHCI_STATUS legacy_code = ToLegacyHciErrorCode(gd_error_code);
456     ASSERT_EQ(reason, static_cast<uint8_t>(ToLegacyHciErrorCode(gd_error_code)));
457     ASSERT_EQ(reason, static_cast<uint8_t>(legacy_code));
458   } while (++reason != 0);
459 }
460 
TEST_F(MainShimTest,connect_and_disconnect)461 TEST_F(MainShimTest, connect_and_disconnect) {
462   hci::Address address({0x11, 0x22, 0x33, 0x44, 0x55, 0x66});
463 
464   auto acl = MakeAcl();
465 
466   // Create connection
467   EXPECT_CALL(*test::mock_acl_manager_, CreateConnection(_)).Times(1);
468   acl->CreateClassicConnection(address);
469 
470   // Respond with a mock connection created
471   auto connection = std::make_unique<MockClassicAclConnection>(address, 123);
472   ASSERT_EQ(123, connection->GetHandle());
473   ASSERT_EQ(hci::Address({0x11, 0x22, 0x33, 0x44, 0x55, 0x66}), connection->GetAddress());
474   MockClassicAclConnection* raw_connection = connection.get();
475 
476   acl->OnConnectSuccess(std::move(connection));
477   ASSERT_EQ(nullptr, connection);
478 
479   // Specify local disconnect request
480   auto tx_disconnect_future = raw_connection->disconnect_promise_.get_future();
481   acl->DisconnectClassic(123, HCI_SUCCESS, {});
482 
483   // Wait for disconnect to be received
484   uint16_t result = tx_disconnect_future.get();
485   ASSERT_EQ(123, result);
486 
487   // Now emulate the remote disconnect response
488   auto handle_promise = std::promise<uint16_t>();
489   auto rx_disconnect_future = handle_promise.get_future();
490   mock_function_handle_promise_map["mock_connection_classic_on_disconnected"] =
491           std::move(handle_promise);
492   raw_connection->callbacks_->OnDisconnection(hci::ErrorCode::SUCCESS);
493 
494   result = rx_disconnect_future.get();
495   ASSERT_EQ(123, result);
496 
497   // *Our* task completing indicates reactor is done
498   std::promise<void> done;
499   auto future = done.get_future();
500   handler_->Call([](std::promise<void> done) { done.set_value(); }, std::move(done));
501   future.wait();
502 
503   connection.reset();
504 }
505 
TEST_F(MainShimTest,is_flushable)506 TEST_F(MainShimTest, is_flushable) {
507   {
508     alignas(BT_HDR) std::byte hdr_data[sizeof(BT_HDR) + sizeof(HciDataPreamble)]{};
509     BT_HDR* bt_hdr = reinterpret_cast<BT_HDR*>(hdr_data);
510 
511     ASSERT_TRUE(!IsPacketFlushable(bt_hdr));
512     HciDataPreamble* hci = ToPacketData<HciDataPreamble>(bt_hdr);
513     hci->SetFlushable();
514     ASSERT_TRUE(IsPacketFlushable(bt_hdr));
515   }
516 
517   {
518     const size_t offset = 1024;
519     alignas(BT_HDR) std::byte hdr_data[sizeof(BT_HDR) + sizeof(HciDataPreamble) + offset]{};
520     BT_HDR* bt_hdr = reinterpret_cast<BT_HDR*>(hdr_data);
521 
522     ASSERT_TRUE(!IsPacketFlushable(bt_hdr));
523     HciDataPreamble* hci = ToPacketData<HciDataPreamble>(bt_hdr);
524     hci->SetFlushable();
525     ASSERT_TRUE(IsPacketFlushable(bt_hdr));
526   }
527 
528   {
529     const size_t offset = 1024;
530     alignas(BT_HDR) std::byte hdr_data[sizeof(BT_HDR) + sizeof(HciDataPreamble) + offset]{};
531     BT_HDR* bt_hdr = reinterpret_cast<BT_HDR*>(hdr_data);
532 
533     uint8_t* p = ToPacketData<uint8_t>(bt_hdr);
534     UINT16_TO_STREAM(p, 0x123 | (L2CAP_PKT_START_NON_FLUSHABLE << L2CAP_PKT_TYPE_SHIFT));
535     ASSERT_TRUE(!IsPacketFlushable(bt_hdr));
536 
537     p = ToPacketData<uint8_t>(bt_hdr);
538     UINT16_TO_STREAM(p, 0x123 | (L2CAP_PKT_START << L2CAP_PKT_TYPE_SHIFT));
539     ASSERT_TRUE(IsPacketFlushable(bt_hdr));
540   }
541 }
542 
TEST_F(MainShimTest,BleScannerInterfaceImpl_nop)543 TEST_F(MainShimTest, BleScannerInterfaceImpl_nop) {
544   auto* ble = static_cast<bluetooth::shim::BleScannerInterfaceImpl*>(
545           bluetooth::shim::get_ble_scanner_instance());
546   ASSERT_NE(nullptr, ble);
547 }
548 
549 class TestScanningCallbacks : public ::ScanningCallbacks {
550 public:
~TestScanningCallbacks()551   ~TestScanningCallbacks() {}
OnScannerRegistered(const bluetooth::Uuid,uint8_t,uint8_t)552   void OnScannerRegistered(const bluetooth::Uuid /*app_uuid*/, uint8_t /*scannerId*/,
553                            uint8_t /*status*/) override {}
OnSetScannerParameterComplete(uint8_t,uint8_t)554   void OnSetScannerParameterComplete(uint8_t /*scannerId*/, uint8_t /*status*/) override {}
OnScanResult(uint16_t,uint8_t,RawAddress,uint8_t,uint8_t,uint8_t,int8_t,int8_t,uint16_t,std::vector<uint8_t>)555   void OnScanResult(uint16_t /*event_type*/, uint8_t /*addr_type*/, RawAddress /*bda*/,
556                     uint8_t /*primary_phy*/, uint8_t /*secondary_phy*/, uint8_t /*advertising_sid*/,
557                     int8_t /*tx_power*/, int8_t /*rssi*/, uint16_t /*periodic_adv_int*/,
558                     std::vector<uint8_t> /*adv_data*/) override {}
OnTrackAdvFoundLost(AdvertisingTrackInfo)559   void OnTrackAdvFoundLost(AdvertisingTrackInfo /*advertising_track_info*/) override {}
OnBatchScanReports(int,int,int,int,std::vector<uint8_t>)560   void OnBatchScanReports(int /*client_if*/, int /*status*/, int /*report_format*/,
561                           int /*num_records*/, std::vector<uint8_t> /*data*/) override {}
OnBatchScanThresholdCrossed(int)562   void OnBatchScanThresholdCrossed(int /*client_if*/) override {}
OnPeriodicSyncStarted(int,uint8_t,uint16_t,uint8_t,uint8_t,RawAddress,uint8_t,uint16_t)563   void OnPeriodicSyncStarted(int /*reg_id*/, uint8_t /*status*/, uint16_t /*sync_handle*/,
564                              uint8_t /*advertising_sid*/, uint8_t /*address_type*/,
565                              RawAddress /*address*/, uint8_t /*phy*/,
566                              uint16_t /*interval*/) override {}
OnPeriodicSyncReport(uint16_t,int8_t,int8_t,uint8_t,std::vector<uint8_t>)567   void OnPeriodicSyncReport(uint16_t /*sync_handle*/, int8_t /*tx_power*/, int8_t /*rssi*/,
568                             uint8_t /*status*/, std::vector<uint8_t> /*data*/) override {}
OnPeriodicSyncLost(uint16_t)569   void OnPeriodicSyncLost(uint16_t /*sync_handle*/) override {}
OnPeriodicSyncTransferred(int,uint8_t,RawAddress)570   void OnPeriodicSyncTransferred(int /*pa_source*/, uint8_t /*status*/,
571                                  RawAddress /*address*/) override {}
OnBigInfoReport(uint16_t,bool)572   void OnBigInfoReport(uint16_t /*sync_handle*/, bool /*encrypted*/) override {}
573 };
574 
TEST_F(MainShimTest,DISABLED_BleScannerInterfaceImpl_OnScanResult)575 TEST_F(MainShimTest, DISABLED_BleScannerInterfaceImpl_OnScanResult) {
576   auto* ble = static_cast<bluetooth::shim::BleScannerInterfaceImpl*>(
577           bluetooth::shim::get_ble_scanner_instance());
578 
579   EXPECT_CALL(*hci::testing::mock_le_scanning_manager_, RegisterScanningCallback(_)).Times(1);
580   ;
581   bluetooth::shim::init_scanning_manager();
582 
583   TestScanningCallbacks cb;
584   ble->RegisterCallbacks(&cb);
585 
586   //  Simulate scan results from the lower layers
587   for (int i = 0; i < 2048; i++) {
588     uint16_t event_type = 0;
589     uint8_t address_type = BLE_ADDR_ANONYMOUS;
590     bluetooth::hci::Address address;
591     uint8_t primary_phy = 0;
592     uint8_t secondary_phy = 0;
593     uint8_t advertising_sid = 0;
594     int8_t tx_power = 0;
595     int8_t rssi = 0;
596     uint16_t periodic_advertising_interval = 0;
597     std::vector<uint8_t> advertising_data;
598 
599     ble->OnScanResult(event_type, address_type, address, primary_phy, secondary_phy,
600                       advertising_sid, tx_power, rssi, periodic_advertising_interval,
601                       advertising_data);
602   }
603 
604   ASSERT_EQ(2 * 2048UL, do_in_jni_thread_task_queue.size());
605   ASSERT_EQ(0, get_func_call_count("btm_ble_process_adv_addr"));
606 
607   run_all_jni_thread_task();
608 }
609 
TEST_F(MainShimTest,DISABLED_LeShimAclConnection_local_disconnect)610 TEST_F(MainShimTest, DISABLED_LeShimAclConnection_local_disconnect) {
611   auto acl = MakeAcl();
612   EXPECT_CALL(*test::mock_acl_manager_, CreateLeConnection(_, _)).Times(1);
613 
614   hci::AddressWithType local_address(hci::Address{{0x01, 0x02, 0x03, 0x04, 0x05, 0x6}},
615                                      hci::AddressType::RANDOM_DEVICE_ADDRESS);
616   hci::AddressWithType remote_address(hci::Address{{0x01, 0x02, 0x03, 0x04, 0x05, 0x6}},
617                                       hci::AddressType::RANDOM_DEVICE_ADDRESS);
618 
619   // Allow LE connections to be accepted
620   std::promise<bool> promise;
621   auto future = promise.get_future();
622   acl->AcceptLeConnectionFrom(remote_address, true, std::move(promise));
623   ASSERT_TRUE(future.get());
624 
625   // Simulate LE connection successful
626   uint16_t handle = 0x1234;
627   auto connection = std::make_unique<MockLeAclConnection>(
628           handle, hci::acl_manager::DataAsPeripheral{local_address, std::nullopt, true},
629           remote_address);
630   auto raw_connection = connection.get();
631   acl->OnLeConnectSuccess(remote_address, std::move(connection));
632   ASSERT_EQ(nullptr, connection);
633   ASSERT_NE(nullptr, raw_connection->callbacks_);
634 
635   // Initiate local LE disconnect
636   mock_connection_le_on_disconnected_promise = std::promise<uint16_t>();
637   auto disconnect_future = mock_connection_le_on_disconnected_promise.get_future();
638   {
639     raw_connection->disconnect_promise_ = std::promise<uint16_t>();
640     auto future = raw_connection->disconnect_promise_.get_future();
641     acl->DisconnectLe(0x1234, HCI_SUCCESS, __func__);
642     uint16_t result = future.get();
643     ASSERT_EQ(0x1234, result);
644   }
645   raw_connection->callbacks_->OnDisconnection(hci::ErrorCode::SUCCESS);
646 
647   ASSERT_EQ(0x1234, disconnect_future.get());
648 }
649 
TEST_F(MainShimTestWithClassicConnection,nop)650 TEST_F(MainShimTestWithClassicConnection, nop) {}
651 
TEST_F(MainShimTestWithClassicConnection,read_extended_feature)652 TEST_F(MainShimTestWithClassicConnection, read_extended_feature) {
653   int read_remote_extended_feature_call_count = 0;
654   raw_connection_->read_remote_extended_features_function_ =
655           [&read_remote_extended_feature_call_count](uint8_t /*page_number*/) {
656             read_remote_extended_feature_call_count++;
657           };
658 
659   // Handle typical case
660   {
661     read_remote_extended_feature_call_count = 0;
662     const uint8_t max_page = 3;
663     raw_connection_->callbacks_->OnReadRemoteExtendedFeaturesComplete(1, max_page,
664                                                                       0xabcdef9876543210);
665     raw_connection_->callbacks_->OnReadRemoteExtendedFeaturesComplete(2, max_page,
666                                                                       0xbcdef9876543210a);
667     raw_connection_->callbacks_->OnReadRemoteExtendedFeaturesComplete(3, max_page,
668                                                                       0xcdef9876543210ab);
669     ASSERT_EQ(static_cast<int>(max_page) - 1, read_remote_extended_feature_call_count);
670   }
671 
672   // Handle extreme case
673   {
674     read_remote_extended_feature_call_count = 0;
675     const uint8_t max_page = 255;
676     for (int page = 1; page < static_cast<int>(max_page) + 1; page++) {
677       raw_connection_->callbacks_->OnReadRemoteExtendedFeaturesComplete(
678               static_cast<uint8_t>(page), max_page, 0xabcdef9876543210);
679     }
680     ASSERT_EQ(static_cast<int>(max_page - 1), read_remote_extended_feature_call_count);
681   }
682 
683   // Handle case where device returns max page of zero
684   {
685     read_remote_extended_feature_call_count = 0;
686     const uint8_t max_page = 0;
687     raw_connection_->callbacks_->OnReadRemoteExtendedFeaturesComplete(1, max_page,
688                                                                       0xabcdef9876543210);
689     ASSERT_EQ(0, read_remote_extended_feature_call_count);
690   }
691 
692   raw_connection_->read_remote_extended_features_function_ = {};
693 }
694 
TEST_F(MainShimTest,acl_dumpsys)695 TEST_F(MainShimTest, acl_dumpsys) { MakeAcl()->Dump(std::make_unique<DevNullOrStdErr>()->Fd()); }
696 
TEST_F(MainShimTest,ticks_to_milliseconds)697 TEST_F(MainShimTest, ticks_to_milliseconds) {
698   ASSERT_THAT(kTicksInMs, DoubleNear(ticks_to_milliseconds(kTicks), kMaxAbsoluteError));
699 }
700 
TEST_F(MainShimTest,ticks_to_seconds)701 TEST_F(MainShimTest, ticks_to_seconds) {
702   ASSERT_THAT(kTicksInSec, DoubleNear(ticks_to_seconds(kTicks), kMaxAbsoluteError));
703 }
704 
TEST_F(MainShimTest,DumpConnectionHistory)705 TEST_F(MainShimTest, DumpConnectionHistory) {
706   auto acl = MakeAcl();
707   acl->DumpConnectionHistory(STDOUT_FILENO);
708 }
709 
TEST_F(MainShimTest,OnConnectRequest)710 TEST_F(MainShimTest, OnConnectRequest) {
711   acl_interface.connection.classic.on_connect_request = [](const RawAddress& bda,
712                                                            const hci::ClassOfDevice& cod) {
713     ASSERT_STREQ(kAddress.ToString().c_str(), bda.ToString().c_str());
714     ASSERT_STREQ(kCod.ToString().c_str(), cod.ToString().c_str());
715   };
716   auto acl = MakeAcl();
717   acl->OnConnectRequest(kAddress, kCod);
718 }
719 
720 void DumpsysNeighbor(int fd);
TEST_F(MainShimTest,DumpsysNeighbor)721 TEST_F(MainShimTest, DumpsysNeighbor) {
722   btm_cb.neighbor = {};
723 
724   btm_cb.neighbor.inquiry_history_->Push({
725           .status = tBTM_INQUIRY_CMPL::CANCELED,
726           .hci_status = HCI_SUCCESS,
727           .num_resp = 45,
728           .resp_type = {20, 30, 40},
729           .start_time_ms = 1,
730   });
731 
732   btm_cb.neighbor.inquiry_history_->Push({
733           .status = tBTM_INQUIRY_CMPL::CANCELED,
734           .hci_status = HCI_SUCCESS,
735           .num_resp = 123,
736           .resp_type = {50, 60, 70},
737           .start_time_ms = 0,
738   });
739 
740   DumpsysNeighbor(STDOUT_FILENO);
741 }
742 
743 // test for b/277590580
744 
745 using bluetooth::hci::GapData;
TEST(MainShimRegressionTest,OOB_In_StartAdvertisingSet)746 TEST(MainShimRegressionTest, OOB_In_StartAdvertisingSet) {
747   std::vector<uint8_t> raw_data = {10, 0, 0, 0, 0};
748   std::vector<GapData> res;
749 
750   bluetooth::shim::parse_gap_data(raw_data, res);
751 
752   ASSERT_EQ(res.size(), (size_t)0);
753 }
754