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