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