1 /******************************************************************************
2  *
3  *  Copyright 2016 The Android Open Source Project
4  *
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at:
8  *
9  *  http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an "AS IS" BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  *  limitations under the License.
16  *
17  ******************************************************************************/
18 
19 #include <array>
20 #include <gmock/gmock.h>
21 #include <gtest/gtest.h>
22 
23 #include "device/include/controller.h"
24 #include "stack/btm/ble_advertiser_hci_interface.h"
25 #include "stack/include/ble_advertiser.h"
26 
27 using ::testing::Args;
28 using ::testing::Contains;
29 using ::testing::ElementsAreArray;
30 using ::testing::Exactly;
31 using ::testing::Field;
32 using ::testing::IsEmpty;
33 using ::testing::SaveArg;
34 using ::testing::SizeIs;
35 using ::testing::_;
36 using base::Bind;
37 using status_cb = BleAdvertiserHciInterface::status_cb;
38 using parameters_cb = BleAdvertiserHciInterface::parameters_cb;
39 using SetEnableData = BleAdvertiserHciInterface::SetEnableData;
40 
41 const int num_adv_instances = 16;
42 
43 /* Below are methods that must be implemented if we don't want to compile the
44  * whole stack. They will be removed, or changed into mocks one by one in the
45  * future, as the refactoring progresses */
BTM_BleLocalPrivacyEnabled()46 bool BTM_BleLocalPrivacyEnabled() { return true; }
BTM_ReadDiscoverability(uint16_t * p_window,uint16_t * p_interval)47 uint16_t BTM_ReadDiscoverability(uint16_t* p_window, uint16_t* p_interval) {
48   return true;
49 }
btm_acl_update_conn_addr(uint16_t conn_handle,const RawAddress & address)50 void btm_acl_update_conn_addr(uint16_t conn_handle, const RawAddress& address) {
51 }
btm_gen_resolvable_private_addr(base::Callback<void (const RawAddress & rpa)> cb)52 void btm_gen_resolvable_private_addr(
53     base::Callback<void(const RawAddress& rpa)> cb) {
54   cb.Run(RawAddress::kEmpty);
55 }
56 
57 alarm_callback_t last_alarm_cb = nullptr;
58 void* last_alarm_data = nullptr;
alarm_set_on_mloop(alarm_t * alarm,uint64_t interval_ms,alarm_callback_t cb,void * data)59 void alarm_set_on_mloop(alarm_t* alarm, uint64_t interval_ms,
60                         alarm_callback_t cb, void* data) {
61   last_alarm_cb = cb;
62   last_alarm_data = data;
63 }
64 
alarm_cancel(alarm_t * alarm)65 void alarm_cancel(alarm_t* alarm) {}
alarm_new_periodic(const char * name)66 alarm_t* alarm_new_periodic(const char* name) { return nullptr; }
alarm_new(const char * name)67 alarm_t* alarm_new(const char* name) { return nullptr; }
alarm_free(alarm_t * alarm)68 void alarm_free(alarm_t* alarm) {}
controller_get_interface()69 const controller_t* controller_get_interface() { return nullptr; }
70 
btm_get_next_private_addrress_interval_ms()71 uint64_t btm_get_next_private_addrress_interval_ms() { return 15 * 60 * 1000; }
72 
73 namespace {
DoNothing(uint8_t)74 void DoNothing(uint8_t) {}
75 
DoNothing2(uint8_t,uint8_t)76 void DoNothing2(uint8_t, uint8_t) {}
77 
TriggerRandomAddressUpdate()78 void TriggerRandomAddressUpdate() {
79   // Call to StartAdvertisingSet set the last_alarm_cb to random address timeout
80   // callback. Call it now in order to trigger address update
81   last_alarm_cb(last_alarm_data);
82 }
83 
84 constexpr uint8_t INTERMEDIATE =
85     0x00;                           // Intermediate fragment of fragmented data
86 constexpr uint8_t FIRST = 0x01;     // First fragment of fragmented data
87 constexpr uint8_t LAST = 0x02;      // Last fragment of fragmented data
88 constexpr uint8_t COMPLETE = 0x03;  // Complete extended advertising data
89 
90 class AdvertiserHciMock : public BleAdvertiserHciInterface {
91  public:
92   AdvertiserHciMock() = default;
93   ~AdvertiserHciMock() override = default;
94 
95   MOCK_METHOD1(ReadInstanceCount,
96                void(base::Callback<void(uint8_t /* inst_cnt*/)>));
97   MOCK_METHOD1(SetAdvertisingEventObserver,
98                void(AdvertisingEventObserver* observer));
99   MOCK_METHOD6(SetAdvertisingData,
100                void(uint8_t, uint8_t, uint8_t, uint8_t, uint8_t*, status_cb));
101   MOCK_METHOD6(SetScanResponseData,
102                void(uint8_t, uint8_t, uint8_t, uint8_t, uint8_t*, status_cb));
103   MOCK_METHOD3(SetRandomAddress, void(uint8_t, const RawAddress&, status_cb));
104   MOCK_METHOD3(Enable, void(uint8_t, std::vector<SetEnableData>, status_cb));
105   MOCK_METHOD5(SetPeriodicAdvertisingParameters,
106                void(uint8_t, uint16_t, uint16_t, uint16_t, status_cb));
107   MOCK_METHOD5(SetPeriodicAdvertisingData,
108                void(uint8_t, uint8_t, uint8_t, uint8_t*, status_cb));
109   MOCK_METHOD3(SetPeriodicAdvertisingEnable, void(uint8_t, uint8_t, status_cb));
110   MOCK_METHOD2(RemoveAdvertisingSet, void(uint8_t, status_cb));
111   MOCK_METHOD1(ClearAdvertisingSets, void(status_cb));
112 
113   MOCK_METHOD9(SetParameters1,
114                void(uint8_t, uint16_t, uint32_t, uint32_t, uint8_t, uint8_t,
115                     const RawAddress&, uint8_t, const RawAddress&));
116   MOCK_METHOD8(SetParameters2, void(uint8_t, int8_t, uint8_t, uint8_t, uint8_t,
117                                     uint8_t, uint8_t, parameters_cb));
118 
SetParameters(uint8_t handle,uint16_t properties,uint32_t adv_int_min,uint32_t adv_int_max,uint8_t channel_map,uint8_t own_address_type,const RawAddress & own_address,uint8_t peer_address_type,const RawAddress & peer_address,uint8_t filter_policy,int8_t tx_power,uint8_t primary_phy,uint8_t secondary_max_skip,uint8_t secondary_phy,uint8_t advertising_sid,uint8_t scan_request_notify_enable,parameters_cb cmd_complete)119   void SetParameters(uint8_t handle, uint16_t properties, uint32_t adv_int_min,
120                      uint32_t adv_int_max, uint8_t channel_map,
121                      uint8_t own_address_type, const RawAddress& own_address,
122                      uint8_t peer_address_type, const RawAddress& peer_address,
123                      uint8_t filter_policy, int8_t tx_power,
124                      uint8_t primary_phy, uint8_t secondary_max_skip,
125                      uint8_t secondary_phy, uint8_t advertising_sid,
126                      uint8_t scan_request_notify_enable,
127                      parameters_cb cmd_complete) override {
128     SetParameters1(handle, properties, adv_int_min, adv_int_max, channel_map,
129                    own_address_type, own_address, peer_address_type,
130                    peer_address);
131     SetParameters2(filter_policy, tx_power, primary_phy, secondary_max_skip,
132                    secondary_phy, advertising_sid, scan_request_notify_enable,
133                    cmd_complete);
134   };
135 
QuirkAdvertiserZeroHandle()136   bool QuirkAdvertiserZeroHandle() override { return false; }
137 
138  private:
139   DISALLOW_COPY_AND_ASSIGN(AdvertiserHciMock);
140 };
141 
142 }  // namespace
143 
144 class BleAdvertisingManagerTest : public testing::Test {
145  protected:
146   int reg_inst_id = -1;
147   int reg_status = -1;
148   int set_params_status = -1;
149   int set_data_status = -1;
150   int enable_status = -1;
151   int start_advertising_status = -1;
152   int start_advertising_set_advertiser_id = -1;
153   int start_advertising_set_tx_power = -1;
154   int start_advertising_set_status = -1;
155 
156   std::unique_ptr<AdvertiserHciMock> hci_mock;
157 
SetUp()158   void SetUp() override {
159     hci_mock.reset(new AdvertiserHciMock());
160 
161     base::Callback<void(uint8_t)> inst_cnt_Cb;
162     EXPECT_CALL(*hci_mock, ReadInstanceCount(_))
163         .Times(Exactly(1))
164         .WillOnce(SaveArg<0>(&inst_cnt_Cb));
165 
166     BleAdvertisingManager::Initialize(hci_mock.get());
167     ::testing::Mock::VerifyAndClearExpectations(hci_mock.get());
168 
169     // we are a truly gracious fake controller, let the command succeed!
170     inst_cnt_Cb.Run(num_adv_instances);
171   }
172 
TearDown()173   void TearDown() override {
174     BleAdvertisingManager::CleanUp();
175     hci_mock.reset();
176   }
177 
178  public:
RegistrationCb(uint8_t inst_id,uint8_t status)179   void RegistrationCb(uint8_t inst_id, uint8_t status) {
180     reg_inst_id = inst_id;
181     reg_status = status;
182   }
183 
SetParametersCb(uint8_t status,int8_t tx_power)184   void SetParametersCb(uint8_t status, int8_t tx_power) {
185     set_params_status = status;
186   }
SetDataCb(uint8_t status)187   void SetDataCb(uint8_t status) { set_data_status = status; }
EnableCb(uint8_t status)188   void EnableCb(uint8_t status) { enable_status = status; }
StartAdvertisingCb(uint8_t status)189   void StartAdvertisingCb(uint8_t status) { start_advertising_status = status; }
StartAdvertisingSetCb(uint8_t advertiser_id,int8_t tx_power,uint8_t status)190   void StartAdvertisingSetCb(uint8_t advertiser_id, int8_t tx_power,
191                              uint8_t status) {
192     start_advertising_set_advertiser_id = advertiser_id;
193     start_advertising_set_tx_power = tx_power;
194     start_advertising_set_status = status;
195   }
196 };
197 
TEST_F(BleAdvertisingManagerTest,test_registration)198 TEST_F(BleAdvertisingManagerTest, test_registration) {
199   for (int i = 0; i < num_adv_instances; i++) {
200     BleAdvertisingManager::Get()->RegisterAdvertiser(Bind(
201         &BleAdvertisingManagerTest::RegistrationCb, base::Unretained(this)));
202     EXPECT_EQ(BTM_BLE_MULTI_ADV_SUCCESS, reg_status);
203     EXPECT_EQ(i, reg_inst_id);
204   }
205 
206   // This call should return an error - no more advertisers left.
207   BleAdvertisingManager::Get()->RegisterAdvertiser(
208       Bind(&BleAdvertisingManagerTest::RegistrationCb, base::Unretained(this)));
209   EXPECT_EQ(ADVERTISE_FAILED_TOO_MANY_ADVERTISERS, reg_status);
210   // Don't bother checking inst_id, it doesn't matter
211 
212   status_cb remove_cb;
213   EXPECT_CALL(*hci_mock, RemoveAdvertisingSet(_, _))
214       .Times(1)
215       .WillOnce(SaveArg<1>(&remove_cb));
216   BleAdvertisingManager::Get()->Unregister(5);
217   remove_cb.Run(0);
218 
219   // One advertiser was freed, so should be able to register one now
220   BleAdvertisingManager::Get()->RegisterAdvertiser(
221       Bind(&BleAdvertisingManagerTest::RegistrationCb, base::Unretained(this)));
222   EXPECT_EQ(BTM_BLE_MULTI_ADV_SUCCESS, reg_status);
223   EXPECT_EQ(5, reg_inst_id);
224 }
225 
226 /* This test verifies that the following flow is working correctly: register,
227  * set parameters, set data, enable, ... (advertise) ..., unregister*/
TEST_F(BleAdvertisingManagerTest,test_android_flow)228 TEST_F(BleAdvertisingManagerTest, test_android_flow) {
229   BleAdvertisingManager::Get()->RegisterAdvertiser(
230       Bind(&BleAdvertisingManagerTest::RegistrationCb, base::Unretained(this)));
231   EXPECT_EQ(BTM_BLE_MULTI_ADV_SUCCESS, reg_status);
232   int advertiser_id = reg_inst_id;
233 
234   parameters_cb set_params_cb;
235   tBTM_BLE_ADV_PARAMS params;
236   EXPECT_CALL(*hci_mock, SetParameters1(advertiser_id, _, _, _, _, _, _, _, _))
237       .Times(1);
238   EXPECT_CALL(*hci_mock, SetParameters2(_, _, _, _, _, _, _, _))
239       .Times(1)
240       .WillOnce(SaveArg<7>(&set_params_cb));
241   BleAdvertisingManager::Get()->SetParameters(
242       advertiser_id, &params,
243       Bind(&BleAdvertisingManagerTest::SetParametersCb,
244            base::Unretained(this)));
245   ::testing::Mock::VerifyAndClearExpectations(hci_mock.get());
246 
247   // we are a truly gracious fake controller, let the command succeed!
248   set_params_cb.Run(0, 0);
249   EXPECT_EQ(BTM_BLE_MULTI_ADV_SUCCESS, set_params_status);
250 
251   status_cb set_data_cb;
252   EXPECT_CALL(*hci_mock, SetAdvertisingData(advertiser_id, _, _, _, _, _))
253       .Times(1)
254       .WillOnce(SaveArg<5>(&set_data_cb));
255   BleAdvertisingManager::Get()->SetData(
256       advertiser_id, false, std::vector<uint8_t>(),
257       Bind(&BleAdvertisingManagerTest::SetDataCb, base::Unretained(this)));
258   ::testing::Mock::VerifyAndClearExpectations(hci_mock.get());
259 
260   set_data_cb.Run(0);
261   EXPECT_EQ(BTM_BLE_MULTI_ADV_SUCCESS, set_data_status);
262 
263   status_cb enable_cb;
264   EXPECT_CALL(*hci_mock,
265               Enable(0x01 /* enable */,
266                      AllOf(SizeIs(1), Contains(Field(&SetEnableData::handle,
267                                                      advertiser_id))),
268                      _))
269       .Times(1)
270       .WillOnce(SaveArg<2>(&enable_cb));
271   BleAdvertisingManager::Get()->Enable(
272       advertiser_id, true,
273       Bind(&BleAdvertisingManagerTest::EnableCb, base::Unretained(this)), 0, 0,
274       base::Callback<void(uint8_t)>());
275   ::testing::Mock::VerifyAndClearExpectations(hci_mock.get());
276 
277   enable_cb.Run(0);
278   EXPECT_EQ(BTM_BLE_MULTI_ADV_SUCCESS, enable_status);
279 
280   /* fake controller should be advertising */
281 
282   EXPECT_CALL(*hci_mock,
283               Enable(0x00 /* disable */,
284                      AllOf(SizeIs(1), Contains(Field(&SetEnableData::handle,
285                                                      advertiser_id))),
286                      _))
287       .Times(1)
288       .WillOnce(SaveArg<2>(&enable_cb));
289   status_cb remove_cb;
290   EXPECT_CALL(*hci_mock, RemoveAdvertisingSet(_, _))
291       .Times(1)
292       .WillOnce(SaveArg<1>(&remove_cb));
293   BleAdvertisingManager::Get()->Unregister(advertiser_id);
294   ::testing::Mock::VerifyAndClearExpectations(hci_mock.get());
295 
296   enable_cb.Run(0);
297   remove_cb.Run(0);
298 }
299 
300 /* This test verifies that when advertising data is set, tx power and flags will
301  * be properly filled. */
TEST_F(BleAdvertisingManagerTest,test_adv_data_filling)302 TEST_F(BleAdvertisingManagerTest, test_adv_data_filling) {
303   BleAdvertisingManager::Get()->RegisterAdvertiser(
304       Bind(&BleAdvertisingManagerTest::RegistrationCb, base::Unretained(this)));
305   EXPECT_EQ(BTM_BLE_MULTI_ADV_SUCCESS, reg_status);
306   int advertiser_id = reg_inst_id;
307 
308   parameters_cb set_params_cb;
309   tBTM_BLE_ADV_PARAMS params;
310   params.advertising_event_properties =
311       BleAdvertisingManager::advertising_prop_legacy_connectable;
312   params.tx_power = -15;
313   EXPECT_CALL(*hci_mock, SetParameters1(advertiser_id, _, _, _, _, _, _, _, _))
314       .Times(1);
315   EXPECT_CALL(*hci_mock, SetParameters2(_, params.tx_power, _, _, _, _, _, _))
316       .Times(1)
317       .WillOnce(SaveArg<7>(&set_params_cb));
318   BleAdvertisingManager::Get()->SetParameters(
319       advertiser_id, &params,
320       Bind(&BleAdvertisingManagerTest::SetParametersCb,
321            base::Unretained(this)));
322   ::testing::Mock::VerifyAndClearExpectations(hci_mock.get());
323 
324   // let the set parameters command succeed!
325   set_params_cb.Run(0, 0);
326   EXPECT_EQ(BTM_BLE_MULTI_ADV_SUCCESS, set_params_status);
327 
328   status_cb set_data_cb;
329   /* verify that flags will be added, and tx power filled, if call to SetData
330    * contained only tx power, and the advertisement is connectable */
331   uint8_t expected_adv_data[] = {
332       0x02 /* len */,         0x01 /* flags */,
333       0x02 /* flags value */, 0x02 /* len */,
334       0x0A /* tx_power */,    static_cast<uint8_t>(params.tx_power)};
335   EXPECT_CALL(*hci_mock, SetAdvertisingData(advertiser_id, _, _, _, _, _))
336       .With(Args<4, 3>(ElementsAreArray(expected_adv_data)))
337       .Times(1)
338       .WillOnce(SaveArg<5>(&set_data_cb));
339   BleAdvertisingManager::Get()->SetData(
340       advertiser_id, false,
341       std::vector<uint8_t>({0x02 /* len */, 0x0A /* tx_power */, 0x00}),
342       Bind(&BleAdvertisingManagerTest::SetDataCb, base::Unretained(this)));
343   ::testing::Mock::VerifyAndClearExpectations(hci_mock.get());
344 
345   set_data_cb.Run(0);
346   EXPECT_EQ(BTM_BLE_MULTI_ADV_SUCCESS, set_data_status);
347 }
348 
349 /* This test verifies that when advertising is non-connectable, flags will not
350  * be added. */
TEST_F(BleAdvertisingManagerTest,test_adv_data_not_filling)351 TEST_F(BleAdvertisingManagerTest, test_adv_data_not_filling) {
352   BleAdvertisingManager::Get()->RegisterAdvertiser(
353       Bind(&BleAdvertisingManagerTest::RegistrationCb, base::Unretained(this)));
354   EXPECT_EQ(BTM_BLE_MULTI_ADV_SUCCESS, reg_status);
355   int advertiser_id = reg_inst_id;
356 
357   parameters_cb set_params_cb;
358   tBTM_BLE_ADV_PARAMS params;
359   params.advertising_event_properties =
360       BleAdvertisingManager::advertising_prop_legacy_non_connectable;
361   params.tx_power = -15;
362   EXPECT_CALL(*hci_mock, SetParameters1(advertiser_id, _, _, _, _, _, _, _, _))
363       .Times(1);
364   EXPECT_CALL(*hci_mock,
365               SetParameters2(_, (uint8_t)params.tx_power, _, _, _, _, _, _))
366       .Times(1)
367       .WillOnce(SaveArg<7>(&set_params_cb));
368   BleAdvertisingManager::Get()->SetParameters(
369       advertiser_id, &params,
370       Bind(&BleAdvertisingManagerTest::SetParametersCb,
371            base::Unretained(this)));
372   ::testing::Mock::VerifyAndClearExpectations(hci_mock.get());
373 
374   // let the set parameters command succeed!
375   set_params_cb.Run(0, -15);
376   EXPECT_EQ(BTM_BLE_MULTI_ADV_SUCCESS, set_params_status);
377 
378   status_cb set_data_cb;
379   /* verify that flags will not be added */
380   uint8_t expected_adv_data[] = {
381       0x02 /* len */, 0xFF /* manufacturer specific */, 0x01 /* data */};
382   EXPECT_CALL(*hci_mock, SetAdvertisingData(advertiser_id, _, _, _, _, _))
383       .With(Args<4, 3>(ElementsAreArray(expected_adv_data)))
384       .Times(1)
385       .WillOnce(SaveArg<5>(&set_data_cb));
386   BleAdvertisingManager::Get()->SetData(
387       advertiser_id, false, std::vector<uint8_t>({0x02 /* len */, 0xFF, 0x01}),
388       Bind(&BleAdvertisingManagerTest::SetDataCb, base::Unretained(this)));
389   ::testing::Mock::VerifyAndClearExpectations(hci_mock.get());
390 
391   set_data_cb.Run(0);
392   EXPECT_EQ(BTM_BLE_MULTI_ADV_SUCCESS, set_data_status);
393 }
394 
TEST_F(BleAdvertisingManagerTest,test_reenabling)395 TEST_F(BleAdvertisingManagerTest, test_reenabling) {
396   BleAdvertisingManager::Get()->RegisterAdvertiser(
397       Bind(&BleAdvertisingManagerTest::RegistrationCb, base::Unretained(this)));
398   EXPECT_EQ(BTM_BLE_MULTI_ADV_SUCCESS, reg_status);
399   EXPECT_EQ(0, reg_inst_id);
400 
401   uint8_t advertiser_id = reg_inst_id;
402   status_cb enable_cb;
403   EXPECT_CALL(*hci_mock,
404               Enable(0x01 /* enable */,
405                      AllOf(SizeIs(1), Contains(Field(&SetEnableData::handle,
406                                                      advertiser_id))),
407                      _))
408       .Times(1)
409       .WillOnce(SaveArg<2>(&enable_cb));
410   BleAdvertisingManager::Get()->Enable(advertiser_id, true, Bind(DoNothing), 0,
411                                        0, Bind(DoNothing));
412   enable_cb.Run(0);
413   ::testing::Mock::VerifyAndClearExpectations(hci_mock.get());
414 
415   EXPECT_CALL(*hci_mock,
416               Enable(0x01 /* enable */,
417                      AllOf(SizeIs(1), Contains(Field(&SetEnableData::handle,
418                                                      advertiser_id))),
419                      _))
420       .Times(1)
421       .WillOnce(SaveArg<2>(&enable_cb));
422   BleAdvertisingManager::Get()->OnAdvertisingSetTerminated(advertiser_id, 0x00,
423                                                            0x01ed, 0x00);
424   enable_cb.Run(0);
425   ::testing::Mock::VerifyAndClearExpectations(hci_mock.get());
426 }
427 
428 /* Make sure that instance is not reenabled if it's already disabled */
TEST_F(BleAdvertisingManagerTest,test_reenabling_disabled_instance)429 TEST_F(BleAdvertisingManagerTest, test_reenabling_disabled_instance) {
430   uint8_t advertiser_id = 1;  // any unregistered value
431 
432   EXPECT_CALL(*hci_mock, Enable(_, _, _)).Times(Exactly(0));
433   BleAdvertisingManager::Get()->OnAdvertisingSetTerminated(advertiser_id, 0x00,
434                                                            0x05, 0x00);
435   ::testing::Mock::VerifyAndClearExpectations(hci_mock.get());
436 }
437 
438 /* This test verifies that the only flow that is currently used on Android, is
439  * working correctly in happy case scenario. */
TEST_F(BleAdvertisingManagerTest,test_start_advertising_set)440 TEST_F(BleAdvertisingManagerTest, test_start_advertising_set) {
441   std::vector<uint8_t> adv_data;
442   std::vector<uint8_t> scan_resp;
443   tBTM_BLE_ADV_PARAMS params;
444   tBLE_PERIODIC_ADV_PARAMS periodic_params;
445   periodic_params.enable = false;
446   std::vector<uint8_t> periodic_data;
447 
448   parameters_cb set_params_cb;
449   status_cb set_address_cb;
450   status_cb set_data_cb;
451   status_cb set_scan_resp_data_cb;
452   status_cb enable_cb;
453   EXPECT_CALL(*hci_mock, SetParameters1(_, _, _, _, _, _, _, _, _)).Times(1);
454   EXPECT_CALL(*hci_mock, SetParameters2(_, _, _, _, _, _, _, _))
455       .Times(1)
456       .WillOnce(SaveArg<7>(&set_params_cb));
457   EXPECT_CALL(*hci_mock, SetRandomAddress(_, _, _))
458       .Times(1)
459       .WillOnce(SaveArg<2>(&set_address_cb));
460   EXPECT_CALL(*hci_mock, SetAdvertisingData(_, _, _, _, _, _))
461       .Times(1)
462       .WillOnce(SaveArg<5>(&set_data_cb));
463   EXPECT_CALL(*hci_mock, SetScanResponseData(_, _, _, _, _, _))
464       .Times(1)
465       .WillOnce(SaveArg<5>(&set_scan_resp_data_cb));
466   EXPECT_CALL(*hci_mock, Enable(0x01 /* enable */, _, _))
467       .Times(1)
468       .WillOnce(SaveArg<2>(&enable_cb));
469 
470   BleAdvertisingManager::Get()->StartAdvertisingSet(
471       Bind(&BleAdvertisingManagerTest::StartAdvertisingSetCb,
472            base::Unretained(this)),
473       &params, adv_data, scan_resp, &periodic_params, periodic_data,
474       0 /* duration */, 0 /* maxExtAdvEvents */, Bind(DoNothing2));
475 
476   // we are a truly gracious fake controller, let the commands succeed!
477   int selected_tx_power = -15;
478   set_params_cb.Run(0, selected_tx_power);
479   set_address_cb.Run(0);
480   set_data_cb.Run(0);
481   set_scan_resp_data_cb.Run(0);
482   enable_cb.Run(0);
483   EXPECT_EQ(BTM_BLE_MULTI_ADV_SUCCESS, start_advertising_set_status);
484   EXPECT_EQ(selected_tx_power, start_advertising_set_tx_power);
485   int advertiser_id = start_advertising_set_advertiser_id;
486   ::testing::Mock::VerifyAndClearExpectations(hci_mock.get());
487 
488   // ... advertising ...
489 
490   // Disable advertiser
491   status_cb disable_cb;
492   EXPECT_CALL(*hci_mock,
493               Enable(0x00 /* disable */,
494                      AllOf(SizeIs(1), Contains(Field(&SetEnableData::handle,
495                                                      advertiser_id))),
496                      _))
497       .Times(1)
498       .WillOnce(SaveArg<2>(&disable_cb));
499   status_cb remove_cb;
500   EXPECT_CALL(*hci_mock, RemoveAdvertisingSet(advertiser_id, _))
501       .Times(1)
502       .WillOnce(SaveArg<1>(&remove_cb));
503   BleAdvertisingManager::Get()->Unregister(advertiser_id);
504   ::testing::Mock::VerifyAndClearExpectations(hci_mock.get());
505 
506   disable_cb.Run(0);
507   remove_cb.Run(0);
508 }
509 
TEST_F(BleAdvertisingManagerTest,test_start_advertising_set_params_failed)510 TEST_F(BleAdvertisingManagerTest, test_start_advertising_set_params_failed) {
511   BleAdvertisingManager::Get()->RegisterAdvertiser(
512       Bind(&BleAdvertisingManagerTest::RegistrationCb, base::Unretained(this)));
513   EXPECT_EQ(BTM_BLE_MULTI_ADV_SUCCESS, reg_status);
514   int advertiser_id = reg_inst_id;
515 
516   std::vector<uint8_t> adv_data;
517   std::vector<uint8_t> scan_resp;
518   tBTM_BLE_ADV_PARAMS params;
519 
520   parameters_cb set_params_cb;
521   EXPECT_CALL(*hci_mock, SetParameters1(advertiser_id, _, _, _, _, _, _, _, _))
522       .Times(1);
523   EXPECT_CALL(*hci_mock, SetParameters2(_, _, _, _, _, _, _, _))
524       .Times(1)
525       .WillOnce(SaveArg<7>(&set_params_cb));
526 
527   EXPECT_CALL(*hci_mock, SetAdvertisingData(advertiser_id, _, _, _, _, _))
528       .Times(Exactly(0));
529 
530   BleAdvertisingManager::Get()->StartAdvertising(
531       advertiser_id,
532       Bind(&BleAdvertisingManagerTest::StartAdvertisingCb,
533            base::Unretained(this)),
534       &params, adv_data, scan_resp, 0, base::Callback<void(uint8_t)>());
535   ::testing::Mock::VerifyAndClearExpectations(hci_mock.get());
536 
537   // set params failed
538   set_params_cb.Run(0x01, 0);
539 
540   // Expect the whole flow to fail right away
541   EXPECT_EQ(BTM_BLE_MULTI_ADV_FAILURE, start_advertising_status);
542 }
543 
TEST_F(BleAdvertisingManagerTest,test_data_sender)544 TEST_F(BleAdvertisingManagerTest, test_data_sender) {
545   // prepare test input vector
546   const int max_data_size = 1650;
547   std::vector<uint8_t> data(max_data_size);
548   for (int i = 0; i < max_data_size; i++) data[i] = i;
549 
550   BleAdvertisingManager::Get()->RegisterAdvertiser(
551       Bind(&BleAdvertisingManagerTest::RegistrationCb, base::Unretained(this)));
552   EXPECT_EQ(BTM_BLE_MULTI_ADV_SUCCESS, reg_status);
553   int advertiser_id = reg_inst_id;
554 
555   status_cb set_data_cb;
556   EXPECT_CALL(*hci_mock, SetAdvertisingData(advertiser_id, FIRST, _, 251, _, _))
557       .Times(1)
558       .WillOnce(SaveArg<5>(&set_data_cb));
559   EXPECT_CALL(*hci_mock,
560               SetAdvertisingData(advertiser_id, INTERMEDIATE, _, 251, _, _))
561       .Times(5)
562       .WillRepeatedly(SaveArg<5>(&set_data_cb));
563   EXPECT_CALL(*hci_mock, SetAdvertisingData(advertiser_id, LAST, _, 144, _, _))
564       .Times(1)
565       .WillOnce(SaveArg<5>(&set_data_cb));
566   BleAdvertisingManager::Get()->SetData(
567       advertiser_id, false, data,
568       Bind(&BleAdvertisingManagerTest::SetDataCb, base::Unretained(this)));
569   for (int i = 0; i < 7; i++) {
570     set_data_cb.Run(0x00);
571   }
572   ::testing::Mock::VerifyAndClearExpectations(hci_mock.get());
573   // Expect the whole flow to succeed
574   EXPECT_EQ(BTM_BLE_MULTI_ADV_SUCCESS, set_data_status);
575 
576   // ***************** Try again with different data size *********************
577   data.resize(503);
578   EXPECT_CALL(*hci_mock, SetAdvertisingData(advertiser_id, FIRST, _, 251, _, _))
579       .Times(1)
580       .WillOnce(SaveArg<5>(&set_data_cb));
581   EXPECT_CALL(*hci_mock,
582               SetAdvertisingData(advertiser_id, INTERMEDIATE, _, 251, _, _))
583       .Times(1)
584       .WillRepeatedly(SaveArg<5>(&set_data_cb));
585   EXPECT_CALL(*hci_mock, SetAdvertisingData(advertiser_id, LAST, _, 1, _, _))
586       .Times(1)
587       .WillOnce(SaveArg<5>(&set_data_cb));
588   BleAdvertisingManager::Get()->SetData(
589       advertiser_id, false, data,
590       Bind(&BleAdvertisingManagerTest::SetDataCb, base::Unretained(this)));
591   for (int i = 0; i < 3; i++) {
592     set_data_cb.Run(0x00);
593   }
594   ::testing::Mock::VerifyAndClearExpectations(hci_mock.get());
595   // Expect the whole flow to succeed
596   EXPECT_EQ(BTM_BLE_MULTI_ADV_SUCCESS, set_data_status);
597 
598   // ***************** Try again with different data size *********************
599   data.resize(502);
600   EXPECT_CALL(*hci_mock, SetAdvertisingData(advertiser_id, FIRST, _, 251, _, _))
601       .Times(1)
602       .WillOnce(SaveArg<5>(&set_data_cb));
603   EXPECT_CALL(*hci_mock, SetAdvertisingData(advertiser_id, LAST, _, 251, _, _))
604       .Times(1)
605       .WillOnce(SaveArg<5>(&set_data_cb));
606   BleAdvertisingManager::Get()->SetData(
607       advertiser_id, false, data,
608       Bind(&BleAdvertisingManagerTest::SetDataCb, base::Unretained(this)));
609   for (int i = 0; i < 2; i++) {
610     set_data_cb.Run(0x00);
611   }
612   ::testing::Mock::VerifyAndClearExpectations(hci_mock.get());
613   // Expect the whole flow to succeed
614   EXPECT_EQ(BTM_BLE_MULTI_ADV_SUCCESS, set_data_status);
615 
616   // ***************** Try again with different data size *********************
617   data.resize(501);
618   EXPECT_CALL(*hci_mock, SetAdvertisingData(advertiser_id, FIRST, _, 251, _, _))
619       .Times(1)
620       .WillOnce(SaveArg<5>(&set_data_cb));
621   EXPECT_CALL(*hci_mock, SetAdvertisingData(advertiser_id, LAST, _, 250, _, _))
622       .Times(1)
623       .WillOnce(SaveArg<5>(&set_data_cb));
624   BleAdvertisingManager::Get()->SetData(
625       advertiser_id, false, data,
626       Bind(&BleAdvertisingManagerTest::SetDataCb, base::Unretained(this)));
627   for (int i = 0; i < 2; i++) {
628     set_data_cb.Run(0x00);
629   }
630   ::testing::Mock::VerifyAndClearExpectations(hci_mock.get());
631   // Expect the whole flow to succeed
632   EXPECT_EQ(BTM_BLE_MULTI_ADV_SUCCESS, set_data_status);
633 
634   // ***************** Try again with different data size *********************
635   data.resize(251);
636   EXPECT_CALL(*hci_mock,
637               SetAdvertisingData(advertiser_id, COMPLETE, _, 251, _, _))
638       .Times(1)
639       .WillOnce(SaveArg<5>(&set_data_cb));
640   BleAdvertisingManager::Get()->SetData(
641       advertiser_id, false, data,
642       Bind(&BleAdvertisingManagerTest::SetDataCb, base::Unretained(this)));
643   set_data_cb.Run(0x00);
644   ::testing::Mock::VerifyAndClearExpectations(hci_mock.get());
645   // Expect the whole flow to succeed
646   EXPECT_EQ(BTM_BLE_MULTI_ADV_SUCCESS, set_data_status);
647 
648   // ***************** Try again with different data size *********************
649   data.resize(120);
650   EXPECT_CALL(*hci_mock,
651               SetAdvertisingData(advertiser_id, COMPLETE, _, 120, _, _))
652       .Times(1)
653       .WillOnce(SaveArg<5>(&set_data_cb));
654   BleAdvertisingManager::Get()->SetData(
655       advertiser_id, false, data,
656       Bind(&BleAdvertisingManagerTest::SetDataCb, base::Unretained(this)));
657   set_data_cb.Run(0x00);
658   ::testing::Mock::VerifyAndClearExpectations(hci_mock.get());
659   // Expect the whole flow to succeed
660   EXPECT_EQ(BTM_BLE_MULTI_ADV_SUCCESS, set_data_status);
661 
662   // ***************** Try again with different data size *********************
663   data.resize(0);
664   EXPECT_CALL(*hci_mock,
665               SetAdvertisingData(advertiser_id, COMPLETE, _, 0, _, _))
666       .Times(1)
667       .WillOnce(SaveArg<5>(&set_data_cb));
668   BleAdvertisingManager::Get()->SetData(
669       advertiser_id, false, data,
670       Bind(&BleAdvertisingManagerTest::SetDataCb, base::Unretained(this)));
671   set_data_cb.Run(0x00);
672   ::testing::Mock::VerifyAndClearExpectations(hci_mock.get());
673   // Expect the whole flow to succeed
674   EXPECT_EQ(BTM_BLE_MULTI_ADV_SUCCESS, set_data_status);
675 }
676 
677 /* This test makes sure that conectable advertisment with timeout will get it's
678  * address updated once the timeout passes and one tries to enable it again.*/
TEST_F(BleAdvertisingManagerTest,test_connectable_address_update_during_timeout)679 TEST_F(BleAdvertisingManagerTest,
680        test_connectable_address_update_during_timeout) {
681   std::vector<uint8_t> adv_data;
682   std::vector<uint8_t> scan_resp;
683   tBTM_BLE_ADV_PARAMS params;
684   params.advertising_event_properties = 0x1 /* connectable */;
685   tBLE_PERIODIC_ADV_PARAMS periodic_params;
686   periodic_params.enable = false;
687   std::vector<uint8_t> periodic_data;
688 
689   uint8_t maxExtAdvEvents = 50;
690 
691   parameters_cb set_params_cb;
692   status_cb set_address_cb;
693   status_cb set_data_cb;
694   status_cb set_scan_resp_data_cb;
695   status_cb enable_cb;
696   EXPECT_CALL(*hci_mock, SetParameters1(_, _, _, _, _, _, _, _, _)).Times(1);
697   EXPECT_CALL(*hci_mock, SetParameters2(_, _, _, _, _, _, _, _))
698       .Times(1)
699       .WillOnce(SaveArg<7>(&set_params_cb));
700   EXPECT_CALL(*hci_mock, SetRandomAddress(_, _, _))
701       .Times(1)
702       .WillOnce(SaveArg<2>(&set_address_cb));
703   EXPECT_CALL(*hci_mock, SetAdvertisingData(_, _, _, _, _, _))
704       .Times(1)
705       .WillOnce(SaveArg<5>(&set_data_cb));
706   EXPECT_CALL(*hci_mock, SetScanResponseData(_, _, _, _, _, _))
707       .Times(1)
708       .WillOnce(SaveArg<5>(&set_scan_resp_data_cb));
709   EXPECT_CALL(
710       *hci_mock,
711       Enable(
712           0x01 /* enable */,
713           AllOf(SizeIs(1),
714                 Contains(Field(&SetEnableData::max_extended_advertising_events,
715                                maxExtAdvEvents))),
716           _))
717       .Times(1)
718       .WillOnce(SaveArg<2>(&enable_cb));
719 
720   BleAdvertisingManager::Get()->StartAdvertisingSet(
721       Bind(&BleAdvertisingManagerTest::StartAdvertisingSetCb,
722            base::Unretained(this)),
723       &params, adv_data, scan_resp, &periodic_params, periodic_data,
724       0 /* duration */, maxExtAdvEvents, Bind(DoNothing2));
725 
726   // we are a truly gracious fake controller, let the commands succeed!
727   int selected_tx_power = -15;
728   set_params_cb.Run(0, selected_tx_power);
729   set_address_cb.Run(0);
730   set_data_cb.Run(0);
731   set_scan_resp_data_cb.Run(0);
732   enable_cb.Run(0);
733   EXPECT_EQ(BTM_BLE_MULTI_ADV_SUCCESS, start_advertising_set_status);
734   EXPECT_EQ(selected_tx_power, start_advertising_set_tx_power);
735   int advertiser_id = start_advertising_set_advertiser_id;
736   ::testing::Mock::VerifyAndClearExpectations(hci_mock.get());
737 
738   // ... advertising ...
739 
740   // No HCI calls should be triggered, becuase there is a timeout on a
741   // connectable advertisement.
742   TriggerRandomAddressUpdate();
743   ::testing::Mock::VerifyAndClearExpectations(hci_mock.get());
744 
745   // Set terminated because we advertised maxExtAdvEvents times!
746   BleAdvertisingManager::Get()->OnAdvertisingSetTerminated(
747       0x43 /*status */, advertiser_id, 0x00 /* conn_handle*/, maxExtAdvEvents);
748   ::testing::Mock::VerifyAndClearExpectations(hci_mock.get());
749 
750   // Try to Enable the advertiser. It should first update it's random address.
751   EXPECT_CALL(*hci_mock, SetRandomAddress(_, _, _))
752       .Times(1)
753       .WillOnce(SaveArg<2>(&set_address_cb));
754   EXPECT_CALL(
755       *hci_mock,
756       Enable(
757           0x01 /* enable */,
758           AllOf(SizeIs(1),
759                 Contains(Field(&SetEnableData::max_extended_advertising_events,
760                                maxExtAdvEvents))),
761           _))
762       .Times(1)
763       .WillOnce(SaveArg<2>(&enable_cb));
764   BleAdvertisingManager::Get()->Enable(
765       advertiser_id, true,
766       Bind(&BleAdvertisingManagerTest::EnableCb, base::Unretained(this)), 0,
767       maxExtAdvEvents, Bind(DoNothing));
768   set_address_cb.Run(0);
769   enable_cb.Run(0);
770   ::testing::Mock::VerifyAndClearExpectations(hci_mock.get());
771 
772   // Disable advertiser
773   status_cb disable_cb;
774   EXPECT_CALL(*hci_mock,
775               Enable(0x00 /* disable */,
776                      AllOf(SizeIs(1), Contains(Field(&SetEnableData::handle,
777                                                      advertiser_id))),
778                      _))
779       .Times(1)
780       .WillOnce(SaveArg<2>(&disable_cb));
781   status_cb remove_cb;
782   EXPECT_CALL(*hci_mock, RemoveAdvertisingSet(advertiser_id, _))
783       .Times(1)
784       .WillOnce(SaveArg<1>(&remove_cb));
785   BleAdvertisingManager::Get()->Unregister(advertiser_id);
786   ::testing::Mock::VerifyAndClearExpectations(hci_mock.get());
787 
788   disable_cb.Run(0);
789   remove_cb.Run(0);
790 }
791 
792 /* This test makes sure that periodic advertising is stopped before
793  * unregistering the advertiser, if it was enabled. */
TEST_F(BleAdvertisingManagerTest,test_periodic_adv_disable_on_unregister)794 TEST_F(BleAdvertisingManagerTest, test_periodic_adv_disable_on_unregister) {
795   std::vector<uint8_t> adv_data;
796   std::vector<uint8_t> scan_resp;
797   tBTM_BLE_ADV_PARAMS params;
798   params.advertising_event_properties = 0x1 /* connectable */;
799   tBLE_PERIODIC_ADV_PARAMS periodic_params;
800   periodic_params.enable = true;  // enable periodic advertising
801   std::vector<uint8_t> periodic_data;
802 
803   parameters_cb set_params_cb;
804   status_cb set_address_cb;
805   status_cb set_data_cb;
806   status_cb set_scan_resp_data_cb;
807   status_cb enable_cb;
808   status_cb set_periodic_params_cb;
809   status_cb set_periodic_data_cb;
810   status_cb set_periodic_enable_cb;
811   EXPECT_CALL(*hci_mock, SetParameters1(_, _, _, _, _, _, _, _, _)).Times(1);
812   EXPECT_CALL(*hci_mock, SetParameters2(_, _, _, _, _, _, _, _))
813       .Times(1)
814       .WillOnce(SaveArg<7>(&set_params_cb));
815   EXPECT_CALL(*hci_mock, SetRandomAddress(_, _, _))
816       .Times(1)
817       .WillOnce(SaveArg<2>(&set_address_cb));
818   EXPECT_CALL(*hci_mock, SetAdvertisingData(_, _, _, _, _, _))
819       .Times(1)
820       .WillOnce(SaveArg<5>(&set_data_cb));
821   EXPECT_CALL(*hci_mock, SetScanResponseData(_, _, _, _, _, _))
822       .Times(1)
823       .WillOnce(SaveArg<5>(&set_scan_resp_data_cb));
824   EXPECT_CALL(*hci_mock, SetPeriodicAdvertisingParameters(_, _, _, _, _))
825       .Times(1)
826       .WillOnce(SaveArg<4>(&set_periodic_params_cb));
827   EXPECT_CALL(*hci_mock, SetPeriodicAdvertisingData(_, _, _, _, _))
828       .Times(1)
829       .WillOnce(SaveArg<4>(&set_periodic_data_cb));
830   EXPECT_CALL(*hci_mock, SetPeriodicAdvertisingEnable(0x01 /* enable */, _, _))
831       .Times(1)
832       .WillOnce(SaveArg<2>(&set_periodic_enable_cb));
833   EXPECT_CALL(*hci_mock, Enable(0x01 /* enable */, _, _))
834       .Times(1)
835       .WillOnce(SaveArg<2>(&enable_cb));
836 
837   BleAdvertisingManager::Get()->StartAdvertisingSet(
838       Bind(&BleAdvertisingManagerTest::StartAdvertisingSetCb,
839            base::Unretained(this)),
840       &params, adv_data, scan_resp, &periodic_params, periodic_data,
841       0 /* duration */, 0 /* maxExtAdvEvents */, Bind(DoNothing2));
842 
843   // we are a truly gracious fake controller, let the commands succeed!
844   int selected_tx_power = -15;
845   set_params_cb.Run(0, selected_tx_power);
846   set_address_cb.Run(0);
847   set_data_cb.Run(0);
848   set_scan_resp_data_cb.Run(0);
849   set_periodic_params_cb.Run(0);
850   set_periodic_data_cb.Run(0);
851   set_periodic_enable_cb.Run(0);
852   enable_cb.Run(0);
853   EXPECT_EQ(BTM_BLE_MULTI_ADV_SUCCESS, start_advertising_set_status);
854   EXPECT_EQ(selected_tx_power, start_advertising_set_tx_power);
855   int advertiser_id = start_advertising_set_advertiser_id;
856   ::testing::Mock::VerifyAndClearExpectations(hci_mock.get());
857 
858   // ... advertising ...
859 
860   // Unregister advertiser - should disable periodic advertising
861   status_cb disable_cb;
862   EXPECT_CALL(*hci_mock,
863               Enable(0x00 /* disable */,
864                      AllOf(SizeIs(1), Contains(Field(&SetEnableData::handle,
865                                                      advertiser_id))),
866                      _))
867       .Times(1)
868       .WillOnce(SaveArg<2>(&disable_cb));
869   status_cb disable_periodic_cb;
870   EXPECT_CALL(*hci_mock, SetPeriodicAdvertisingEnable(0x00 /* disable */,
871                                                       advertiser_id, _))
872       .Times(1)
873       .WillOnce(SaveArg<2>(&disable_periodic_cb));
874   status_cb remove_cb;
875   EXPECT_CALL(*hci_mock, RemoveAdvertisingSet(advertiser_id, _))
876       .Times(1)
877       .WillOnce(SaveArg<1>(&remove_cb));
878   BleAdvertisingManager::Get()->Unregister(advertiser_id);
879   ::testing::Mock::VerifyAndClearExpectations(hci_mock.get());
880 
881   disable_cb.Run(0);
882   disable_periodic_cb.Run(0);
883   remove_cb.Run(0);
884 }
885 
TEST_F(BleAdvertisingManagerTest,test_suspend_resume)886 TEST_F(BleAdvertisingManagerTest, test_suspend_resume) {
887   for (int i = 0; i < 10; i++) {
888     BleAdvertisingManager::Get()->RegisterAdvertiser(Bind(
889         &BleAdvertisingManagerTest::RegistrationCb, base::Unretained(this)));
890     EXPECT_EQ(BTM_BLE_MULTI_ADV_SUCCESS, reg_status);
891     EXPECT_EQ(i, reg_inst_id);
892   }
893 
894   std::array<int, 3> enabled = {{1, 3, 9}};
895 
896   for (int advertiser_id : enabled) {
897     status_cb enable_cb;
898     EXPECT_CALL(*hci_mock,
899                 Enable(0x01 /* enable */,
900                        AllOf(SizeIs(1), Contains(Field(&SetEnableData::handle,
901                                                        advertiser_id))),
902                        _))
903         .Times(1)
904         .WillOnce(SaveArg<2>(&enable_cb));
905     BleAdvertisingManager::Get()->Enable(
906         advertiser_id, true,
907         Bind(&BleAdvertisingManagerTest::EnableCb, base::Unretained(this)), 0,
908         0, base::Callback<void(uint8_t)>());
909     enable_cb.Run(0);
910     ::testing::Mock::VerifyAndClearExpectations(hci_mock.get());
911   }
912 
913   // we have some advertisers registered, three advertising.
914 
915   // Call to Suspend() should disable all running advertisers
916   status_cb disable_cb;
917   EXPECT_CALL(
918       *hci_mock,
919       Enable(0x00 /* disable */,
920              AllOf(SizeIs(3), Contains(Field(&SetEnableData::handle, 1)),
921                    Contains(Field(&SetEnableData::handle, 3)),
922                    Contains(Field(&SetEnableData::handle, 9))),
923              _))
924       .Times(1)
925       .WillOnce(SaveArg<2>(&disable_cb));
926 
927   BleAdvertisingManager::Get()->Suspend();
928 
929   disable_cb.Run(0);
930   ::testing::Mock::VerifyAndClearExpectations(hci_mock.get());
931 
932   // Call to Resume() should re-enable advertisers
933   status_cb enable_cb;
934   EXPECT_CALL(
935       *hci_mock,
936       Enable(0x01 /* enable */,
937              AllOf(SizeIs(3), Contains(Field(&SetEnableData::handle, 1)),
938                    Contains(Field(&SetEnableData::handle, 3)),
939                    Contains(Field(&SetEnableData::handle, 9))),
940              _))
941       .Times(1)
942       .WillOnce(SaveArg<2>(&enable_cb));
943 
944   BleAdvertisingManager::Get()->Resume();
945 
946   enable_cb.Run(0);
947 
948   ::testing::Mock::VerifyAndClearExpectations(hci_mock.get());
949 }
950 
951 /* This test makes sure that conectable advertisment with timeout will get it's
952  * duration and maxExtAdvEvents updated, when it's terminated due to incoming
953  * connection.*/
TEST_F(BleAdvertisingManagerTest,test_duration_update_during_timeout)954 TEST_F(BleAdvertisingManagerTest, test_duration_update_during_timeout) {
955   std::vector<uint8_t> adv_data;
956   std::vector<uint8_t> scan_resp;
957   tBTM_BLE_ADV_PARAMS params;
958   params.advertising_event_properties = 0x1 /* connectable */;
959   params.adv_int_min = params.adv_int_max = 0xA0 /* 100ms */;
960   tBLE_PERIODIC_ADV_PARAMS periodic_params;
961   periodic_params.enable = false;
962   std::vector<uint8_t> periodic_data;
963 
964   uint8_t maxExtAdvEvents = 50;
965   uint16_t duration = 500 /* 5s */;
966 
967   parameters_cb set_params_cb;
968   status_cb set_address_cb;
969   status_cb set_data_cb;
970   status_cb set_scan_resp_data_cb;
971   status_cb enable_cb;
972   EXPECT_CALL(*hci_mock, SetParameters1(_, _, _, _, _, _, _, _, _)).Times(1);
973   EXPECT_CALL(*hci_mock, SetParameters2(_, _, _, _, _, _, _, _))
974       .Times(1)
975       .WillOnce(SaveArg<7>(&set_params_cb));
976   EXPECT_CALL(*hci_mock, SetRandomAddress(_, _, _))
977       .Times(1)
978       .WillOnce(SaveArg<2>(&set_address_cb));
979   EXPECT_CALL(*hci_mock, SetAdvertisingData(_, _, _, _, _, _))
980       .Times(1)
981       .WillOnce(SaveArg<5>(&set_data_cb));
982   EXPECT_CALL(*hci_mock, SetScanResponseData(_, _, _, _, _, _))
983       .Times(1)
984       .WillOnce(SaveArg<5>(&set_scan_resp_data_cb));
985   EXPECT_CALL(
986       *hci_mock,
987       Enable(0x01 /* enable */,
988              AllOf(SizeIs(1),
989                    Contains(AllOf(
990                        Field(&SetEnableData::max_extended_advertising_events,
991                              maxExtAdvEvents),
992                        Field(&SetEnableData::duration, duration)))),
993              _))
994       .Times(1)
995       .WillOnce(SaveArg<2>(&enable_cb));
996 
997   BleAdvertisingManager::Get()->StartAdvertisingSet(
998       Bind(&BleAdvertisingManagerTest::StartAdvertisingSetCb,
999            base::Unretained(this)),
1000       &params, adv_data, scan_resp, &periodic_params, periodic_data, duration,
1001       maxExtAdvEvents, Bind(DoNothing2));
1002 
1003   // we are a truly gracious fake controller, let the commands succeed!
1004   int selected_tx_power = -15;
1005   set_params_cb.Run(0, selected_tx_power);
1006   set_address_cb.Run(0);
1007   set_data_cb.Run(0);
1008   set_scan_resp_data_cb.Run(0);
1009   enable_cb.Run(0);
1010   EXPECT_EQ(BTM_BLE_MULTI_ADV_SUCCESS, start_advertising_set_status);
1011   EXPECT_EQ(selected_tx_power, start_advertising_set_tx_power);
1012   int advertiser_id = start_advertising_set_advertiser_id;
1013   ::testing::Mock::VerifyAndClearExpectations(hci_mock.get());
1014 
1015   // ... advertising ...
1016 
1017   sleep(1);
1018 
1019   std::vector<SetEnableData> setEnableData;
1020   // Set terminated because we received connect request! Should trigger
1021   // re-enabling of the set
1022   EXPECT_CALL(*hci_mock, Enable(0x01 /* enable */, _, _))
1023       .Times(1)
1024       .WillOnce(DoAll(SaveArg<1>(&setEnableData), SaveArg<2>(&enable_cb)));
1025 
1026   BleAdvertisingManager::Get()->OnAdvertisingSetTerminated(
1027       0x00 /* Advertising successfully ended with a connection being created */,
1028       advertiser_id, 0x01fe /* conn_handle*/, 20 /* completed ExtAdvEvents */);
1029   enable_cb.Run(0);
1030 
1031   ::testing::Mock::VerifyAndClearExpectations(hci_mock.get());
1032 
1033   uint16_t new_duration = setEnableData[0].duration;
1034   uint8_t new_extAdvEvents = setEnableData[0].max_extended_advertising_events;
1035 
1036   // Sleep is not super-accurate, so assume the recomputed timeouts are around
1037   // 4s +/- 100ms
1038   EXPECT_NEAR((duration - new_duration), 100 /*4s */, 10);
1039   EXPECT_NEAR((maxExtAdvEvents - new_extAdvEvents), 10, 1);
1040 
1041   // Disable advertiser
1042   status_cb disable_cb;
1043   EXPECT_CALL(*hci_mock,
1044               Enable(0x00 /* disable */,
1045                      AllOf(SizeIs(1), Contains(Field(&SetEnableData::handle,
1046                                                      advertiser_id))),
1047                      _))
1048       .Times(1)
1049       .WillOnce(SaveArg<2>(&disable_cb));
1050   status_cb remove_cb;
1051   EXPECT_CALL(*hci_mock, RemoveAdvertisingSet(advertiser_id, _))
1052       .Times(1)
1053       .WillOnce(SaveArg<1>(&remove_cb));
1054   BleAdvertisingManager::Get()->Unregister(advertiser_id);
1055   ::testing::Mock::VerifyAndClearExpectations(hci_mock.get());
1056 
1057   disable_cb.Run(0);
1058   remove_cb.Run(0);
1059 }
1060 
1061 /* This test verifies that stack cleanup, and shutdown happening while there is
1062  * outstanding HCI command is not triggering the callback */
TEST_F(BleAdvertisingManagerTest,test_cleanup_during_execution)1063 TEST_F(BleAdvertisingManagerTest, test_cleanup_during_execution) {
1064   std::vector<uint8_t> adv_data;
1065   std::vector<uint8_t> scan_resp;
1066   tBTM_BLE_ADV_PARAMS params;
1067   tBLE_PERIODIC_ADV_PARAMS periodic_params;
1068   periodic_params.enable = false;
1069   std::vector<uint8_t> periodic_data;
1070 
1071   parameters_cb set_params_cb;
1072   status_cb set_address_cb;
1073   status_cb set_data_cb;
1074   EXPECT_CALL(*hci_mock, SetParameters1(_, _, _, _, _, _, _, _, _)).Times(1);
1075   EXPECT_CALL(*hci_mock, SetParameters2(_, _, _, _, _, _, _, _))
1076       .Times(1)
1077       .WillOnce(SaveArg<7>(&set_params_cb));
1078   EXPECT_CALL(*hci_mock, SetRandomAddress(_, _, _))
1079       .Times(1)
1080       .WillOnce(SaveArg<2>(&set_address_cb));
1081   EXPECT_CALL(*hci_mock, SetAdvertisingData(_, _, _, _, _, _))
1082       .Times(1)
1083       .WillOnce(SaveArg<5>(&set_data_cb));
1084 
1085   BleAdvertisingManager::Get()->StartAdvertisingSet(
1086       Bind(&BleAdvertisingManagerTest::StartAdvertisingSetCb,
1087            base::Unretained(this)),
1088       &params, adv_data, scan_resp, &periodic_params, periodic_data,
1089       0 /* duration */, 0 /* maxExtAdvEvents */, Bind(DoNothing2));
1090 
1091   // we are a truly gracious fake controller, let the commands succeed!
1092   int selected_tx_power = -15;
1093   set_params_cb.Run(0, selected_tx_power);
1094   set_address_cb.Run(0);
1095 
1096   // Someone shut down the stack in the middle of flow, when the HCI Set
1097   // Advertise Data was scheduled!
1098   BleAdvertisingManager::Get()->CleanUp();
1099 
1100   // The HCI call returns with status, and tries to execute the callback. This
1101   // should just silently drop the call. If it got executed, we would get crash,
1102   // because BleAdvertisingManager object was already deleted.
1103   set_data_cb.Run(0);
1104 
1105   ::testing::Mock::VerifyAndClearExpectations(hci_mock.get());
1106 }
1107 
1108 extern void testRecomputeTimeout1();
1109 extern void testRecomputeTimeout2();
1110 extern void testRecomputeTimeout3();
1111 
TEST_F(BleAdvertisingManagerTest,test_recompute_timeout)1112 TEST_F(BleAdvertisingManagerTest, test_recompute_timeout) {
1113   testRecomputeTimeout1();
1114   testRecomputeTimeout2();
1115   testRecomputeTimeout3();
1116 }