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