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