Snap for 8944149 from 074b21af5a9d8af9f81075574d6a13192c68a49e to mainline-media-swcodec-release

Change-Id: Iaa16a96e2327d139b6a9376654abee4a3f5e81fb
diff --git a/android/app/src/com/android/bluetooth/btservice/AdapterService.java b/android/app/src/com/android/bluetooth/btservice/AdapterService.java
index f44b6d4..b627e07 100644
--- a/android/app/src/com/android/bluetooth/btservice/AdapterService.java
+++ b/android/app/src/com/android/bluetooth/btservice/AdapterService.java
@@ -3679,9 +3679,17 @@
                 receiver.propagateException(e);
             }
         }
+        @RequiresPermission(allOf = {
+                android.Manifest.permission.BLUETOOTH_CONNECT,
+                android.Manifest.permission.BLUETOOTH_PRIVILEGED,
+        })
         private boolean allowLowLatencyAudio(boolean allowed, BluetoothDevice device) {
             AdapterService service = getService();
-            if (service == null) {
+            if (service == null
+                    || !Utils.checkCallerIsSystemOrActiveUser(TAG)
+                    || !Utils.checkConnectPermissionForDataDelivery(
+                            service, Utils.getCallingAttributionSource(service),
+                                "AdapterService allowLowLatencyAudio")) {
                 return false;
             }
             enforceBluetoothPrivilegedPermission(service);
@@ -3697,12 +3705,24 @@
                 receiver.propagateException(e);
             }
         }
-        public int startRfcommListener(
+        @RequiresPermission(allOf = {
+                android.Manifest.permission.BLUETOOTH_CONNECT,
+                android.Manifest.permission.BLUETOOTH_PRIVILEGED,
+        })
+        private int startRfcommListener(
                 String name,
                 ParcelUuid uuid,
                 PendingIntent pendingIntent,
                 AttributionSource attributionSource) {
-            return mService.startRfcommListener(name, uuid, pendingIntent, attributionSource);
+            AdapterService service = getService();
+            if (service == null
+                    || !Utils.checkCallerIsSystemOrActiveUser(TAG)
+                    || !Utils.checkConnectPermissionForDataDelivery(
+                            service, attributionSource, "AdapterService startRfcommListener")) {
+                return BluetoothStatusCodes.ERROR_BLUETOOTH_NOT_ALLOWED;
+            }
+            enforceBluetoothPrivilegedPermission(service);
+            return service.startRfcommListener(name, uuid, pendingIntent, attributionSource);
         }
 
         @Override
@@ -3714,8 +3734,20 @@
                 receiver.propagateException(e);
             }
         }
-        public int stopRfcommListener(ParcelUuid uuid, AttributionSource attributionSource) {
-            return mService.stopRfcommListener(uuid, attributionSource);
+        @RequiresPermission(allOf = {
+                android.Manifest.permission.BLUETOOTH_CONNECT,
+                android.Manifest.permission.BLUETOOTH_PRIVILEGED,
+        })
+        private int stopRfcommListener(ParcelUuid uuid, AttributionSource attributionSource) {
+            AdapterService service = getService();
+            if (service == null
+                    || !Utils.checkCallerIsSystemOrActiveUser(TAG)
+                    || !Utils.checkConnectPermissionForDataDelivery(
+                            service, attributionSource, "AdapterService stopRfcommListener")) {
+                return BluetoothStatusCodes.ERROR_BLUETOOTH_NOT_ALLOWED;
+            }
+            enforceBluetoothPrivilegedPermission(service);
+            return service.stopRfcommListener(uuid, attributionSource);
         }
 
         @Override
@@ -3727,9 +3759,22 @@
                 receiver.propagateException(e);
             }
         }
-        public IncomingRfcommSocketInfo retrievePendingSocketForServiceRecord(
+        @RequiresPermission(allOf = {
+                android.Manifest.permission.BLUETOOTH_CONNECT,
+                android.Manifest.permission.BLUETOOTH_PRIVILEGED,
+        })
+        private IncomingRfcommSocketInfo retrievePendingSocketForServiceRecord(
                 ParcelUuid uuid, AttributionSource attributionSource) {
-            return mService.retrievePendingSocketForServiceRecord(uuid, attributionSource);
+            AdapterService service = getService();
+            if (service == null
+                    || !Utils.checkCallerIsSystemOrActiveUser(TAG)
+                    || !Utils.checkConnectPermissionForDataDelivery(
+                            service, attributionSource,
+                            "AdapterService retrievePendingSocketForServiceRecord")) {
+                return null;
+            }
+            enforceBluetoothPrivilegedPermission(service);
+            return service.retrievePendingSocketForServiceRecord(uuid, attributionSource);
         }
 
         @Override
diff --git a/system/bta/dm/bta_dm_act.cc b/system/bta/dm/bta_dm_act.cc
index 3383743..55f7871 100644
--- a/system/bta/dm/bta_dm_act.cc
+++ b/system/bta/dm/bta_dm_act.cc
@@ -652,13 +652,6 @@
   if (!other_address_connected && !other_address.IsEmpty()) {
     bta_dm_process_remove_device(other_address);
   }
-
-  /* Check the length of the paired devices, and if 0 then reset IRK */
-  auto paired_devices = btif_config_get_paired_devices();
-  if (paired_devices.empty()) {
-    LOG_INFO("Last paired device removed, resetting IRK");
-    btm_ble_reset_id();
-  }
 }
 
 /*******************************************************************************
@@ -4023,6 +4016,20 @@
 
 /*******************************************************************************
  *
+ * Function         bta_dm_ble_reset_id
+ *
+ * Description      Reset the local adapter BLE keys.
+ *
+ * Parameters:
+ *
+ ******************************************************************************/
+void bta_dm_ble_reset_id(void) {
+  VLOG(1) << "bta_dm_ble_reset_id in bta_dm_act";
+  bluetooth::shim::BTM_BleResetId();
+}
+
+/*******************************************************************************
+ *
  * Function         bta_dm_gattc_callback
  *
  * Description      This is GATT client callback function used in DM.
diff --git a/system/bta/dm/bta_dm_api.cc b/system/bta/dm/bta_dm_api.cc
index fa15a7e..eded208 100644
--- a/system/bta/dm/bta_dm_api.cc
+++ b/system/bta/dm/bta_dm_api.cc
@@ -675,3 +675,17 @@
   APPL_TRACE_API("BTA_DmClearEventFilter");
   do_in_main_thread(FROM_HERE, base::Bind(bta_dm_clear_event_filter));
 }
+
+/*******************************************************************************
+ *
+ * Function         BTA_DmBleResetId
+ *
+ * Description      This function resets the ble keys such as IRK
+ *
+ * Returns          void
+ *
+ ******************************************************************************/
+void BTA_DmBleResetId(void) {
+  APPL_TRACE_API("BTA_DmBleResetId");
+  do_in_main_thread(FROM_HERE, base::Bind(bta_dm_ble_reset_id));
+}
diff --git a/system/bta/dm/bta_dm_int.h b/system/bta/dm/bta_dm_int.h
index eaf2fa3..d952dcc 100644
--- a/system/bta/dm/bta_dm_int.h
+++ b/system/bta/dm/bta_dm_int.h
@@ -543,6 +543,8 @@
 
 extern void bta_dm_clear_event_filter(void);
 
+extern void bta_dm_ble_reset_id(void);
+
 uint8_t bta_dm_search_get_state();
 void bta_dm_search_set_state(uint8_t state);
 
diff --git a/system/bta/include/bta_api.h b/system/bta/include/bta_api.h
index 447823a..59d6d98 100644
--- a/system/bta/include/bta_api.h
+++ b/system/bta/include/bta_api.h
@@ -1203,4 +1203,15 @@
  ******************************************************************************/
 extern void BTA_DmClearEventFilter(void);
 
+/*******************************************************************************
+ *
+ * Function         BTA_DmBleResetId
+ *
+ * Description      This function resets the ble keys such as IRK
+ *
+ * Returns          void
+ *
+ ******************************************************************************/
+extern void BTA_DmBleResetId(void);
+
 #endif /* BTA_API_H */
diff --git a/system/btif/src/btif_storage.cc b/system/btif/src/btif_storage.cc
index 865bcf9..bd7e89c 100644
--- a/system/btif/src/btif_storage.cc
+++ b/system/btif/src/btif_storage.cc
@@ -896,6 +896,13 @@
 
   /* write bonded info immediately */
   btif_config_flush();
+
+  /* Check the length of the paired devices, and if 0 then reset IRK */
+  auto paired_devices = btif_config_get_paired_devices();
+  if (paired_devices.empty()) {
+    LOG_INFO("Last paired device removed, resetting IRK");
+    BTA_DmBleResetId();
+  }
   return ret ? BT_STATUS_SUCCESS : BT_STATUS_FAIL;
 }
 
@@ -1279,7 +1286,10 @@
       return BT_STATUS_FAIL;
   }
   int ret = btif_config_set_bin("Adapter", name, key.data(), key.size());
-  btif_config_save();
+  // Had to change this to flush to get it to work on test.
+  // Seems to work in the real world on a phone... but not sure why there's a
+  // race in test. Investigate b/239828132
+  btif_config_flush();
   return ret ? BT_STATUS_SUCCESS : BT_STATUS_FAIL;
 }
 
diff --git a/system/gd/hci/le_address_manager.cc b/system/gd/hci/le_address_manager.cc
index 28f5100..9634a5e 100644
--- a/system/gd/hci/le_address_manager.cc
+++ b/system/gd/hci/le_address_manager.cc
@@ -51,6 +51,18 @@
     bool supports_ble_privacy,
     std::chrono::milliseconds minimum_rotation_time,
     std::chrono::milliseconds maximum_rotation_time) {
+  // Handle repeated calls to the function
+  if (address_policy_ != AddressPolicy::POLICY_NOT_SET) {
+    // Need to update some parameteres like IRK if privacy is supported
+    if (supports_ble_privacy) {
+      LOG_INFO("Updating rotation parameters.");
+      rotation_irk_ = rotation_irk;
+      minimum_rotation_time_ = minimum_rotation_time;
+      maximum_rotation_time_ = maximum_rotation_time;
+      set_random_address();
+    }
+    return;
+  }
   ASSERT(address_policy_ == AddressPolicy::POLICY_NOT_SET);
   ASSERT(address_policy != AddressPolicy::POLICY_NOT_SET);
   ASSERT_LOG(registered_clients_.empty(), "Policy must be set before clients are registered.");
diff --git a/system/main/shim/btm_api.cc b/system/main/shim/btm_api.cc
index 6e79931..8b761c0 100644
--- a/system/main/shim/btm_api.cc
+++ b/system/main/shim/btm_api.cc
@@ -37,6 +37,7 @@
 #include "main/shim/shim.h"
 #include "main/shim/stack.h"
 #include "osi/include/allocator.h"
+#include "stack/btm/btm_ble_int.h"
 #include "stack/btm/btm_int_types.h"
 #include "stack/include/bt_hdr.h"
 #include "stack/include/bt_octets.h"
@@ -1334,3 +1335,8 @@
   controller_get_interface()->clear_event_filter();
   return BTM_SUCCESS;
 }
+
+tBTM_STATUS bluetooth::shim::BTM_BleResetId() {
+  btm_ble_reset_id();
+  return BTM_SUCCESS;
+}
diff --git a/system/main/shim/btm_api.h b/system/main/shim/btm_api.h
index c1dd4be..1e10849 100644
--- a/system/main/shim/btm_api.h
+++ b/system/main/shim/btm_api.h
@@ -1821,6 +1821,15 @@
  ******************************************************************************/
 tBTM_STATUS BTM_ClearEventFilter(void);
 
+/*******************************************************************************
+ *
+ * Function         BTM_BleResetId
+ *
+ * Description      Resets the local BLE keys
+ *
+ *******************************************************************************/
+tBTM_STATUS BTM_BleResetId(void);
+
 /**
  * Send remote name request to GD shim Name module
  */
diff --git a/system/stack/avdt/avdt_msg.cc b/system/stack/avdt/avdt_msg.cc
index a3e71c8..7a3ed28 100644
--- a/system/stack/avdt/avdt_msg.cc
+++ b/system/stack/avdt/avdt_msg.cc
@@ -1252,6 +1252,10 @@
      * would have allocated smaller buffer.
      */
     p_ccb->p_rx_msg = (BT_HDR*)osi_malloc(BT_DEFAULT_BUFFER_SIZE);
+    if (sizeof(BT_HDR) + p_buf->offset + p_buf->len > BT_DEFAULT_BUFFER_SIZE) {
+      android_errorWriteLog(0x534e4554, "232023771");
+      return NULL;
+    }
     memcpy(p_ccb->p_rx_msg, p_buf, sizeof(BT_HDR) + p_buf->offset + p_buf->len);
 
     /* Free original buffer */
diff --git a/system/stack/avrc/avrc_pars_ct.cc b/system/stack/avrc/avrc_pars_ct.cc
index 12aee4c..a571042 100644
--- a/system/stack/avrc/avrc_pars_ct.cc
+++ b/system/stack/avrc/avrc_pars_ct.cc
@@ -237,7 +237,7 @@
   }
   BE_STREAM_TO_UINT8(pdu, p);
   uint16_t pkt_len;
-  int min_len = 0;
+  uint16_t min_len = 0;
   /* read the entire packet len */
   BE_STREAM_TO_UINT16(pkt_len, p);
 
@@ -380,8 +380,14 @@
               /* Parse the name now */
               BE_STREAM_TO_UINT16(attr_entry->name.charset_id, p);
               BE_STREAM_TO_UINT16(attr_entry->name.str_len, p);
+              if (static_cast<uint16_t>(min_len + attr_entry->name.str_len) <
+                  min_len) {
+                // Check for overflow
+                android_errorWriteLog(0x534e4554, "205570663");
+              }
+              if (pkt_len - min_len < attr_entry->name.str_len)
+                goto browse_length_error;
               min_len += attr_entry->name.str_len;
-              if (pkt_len < min_len) goto browse_length_error;
               attr_entry->name.p_str = (uint8_t*)osi_malloc(
                   attr_entry->name.str_len * sizeof(uint8_t));
               BE_STREAM_TO_ARRAY(p, attr_entry->name.p_str,
@@ -444,8 +450,14 @@
         BE_STREAM_TO_UINT32(attr_entry->attr_id, p);
         BE_STREAM_TO_UINT16(attr_entry->name.charset_id, p);
         BE_STREAM_TO_UINT16(attr_entry->name.str_len, p);
+        if (static_cast<uint16_t>(min_len + attr_entry->name.str_len) <
+            min_len) {
+          // Check for overflow
+          android_errorWriteLog(0x534e4554, "205570663");
+        }
+        if (pkt_len - min_len < attr_entry->name.str_len)
+          goto browse_length_error;
         min_len += attr_entry->name.str_len;
-        if (pkt_len < min_len) goto browse_length_error;
         attr_entry->name.p_str =
             (uint8_t*)osi_malloc(attr_entry->name.str_len * sizeof(uint8_t));
         BE_STREAM_TO_ARRAY(p, attr_entry->name.p_str, attr_entry->name.str_len);
@@ -815,8 +827,12 @@
           BE_STREAM_TO_UINT32(p_attrs[i].attr_id, p);
           BE_STREAM_TO_UINT16(p_attrs[i].name.charset_id, p);
           BE_STREAM_TO_UINT16(p_attrs[i].name.str_len, p);
-          min_len += p_attrs[i].name.str_len;
-          if (len < min_len) {
+          if (static_cast<uint16_t>(min_len + p_attrs[i].name.str_len) <
+              min_len) {
+            // Check for overflow
+            android_errorWriteLog(0x534e4554, "205570663");
+          }
+          if (len - min_len < p_attrs[i].name.str_len) {
             for (int j = 0; j < i; j++) {
               osi_free(p_attrs[j].name.p_str);
             }
@@ -824,6 +840,7 @@
             p_result->get_attrs.num_attrs = 0;
             goto length_error;
           }
+          min_len += p_attrs[i].name.str_len;
           if (p_attrs[i].name.str_len > 0) {
             p_attrs[i].name.p_str =
                 (uint8_t*)osi_calloc(p_attrs[i].name.str_len);
diff --git a/system/stack/btm/btm_ble.cc b/system/stack/btm/btm_ble.cc
index 9d313b3..3a18f25 100644
--- a/system/stack/btm/btm_ble.cc
+++ b/system/stack/btm/btm_ble.cc
@@ -32,6 +32,7 @@
 #include "main/shim/l2c_api.h"
 #include "main/shim/shim.h"
 #include "osi/include/allocator.h"
+#include "osi/include/properties.h"
 #include "stack/btm/btm_dev.h"
 #include "stack/btm/btm_int_types.h"
 #include "stack/btm/security_device_record.h"
@@ -56,6 +57,11 @@
 extern void gatt_notify_phy_updated(tGATT_STATUS status, uint16_t handle,
                                     uint8_t tx_phy, uint8_t rx_phy);
 
+
+#ifndef PROPERTY_BLE_PRIVACY_ENABLED
+#define PROPERTY_BLE_PRIVACY_ENABLED "bluetooth.core.gap.le.privacy.enabled"
+#endif
+
 /******************************************************************************/
 /* External Function to be called by other modules                            */
 /******************************************************************************/
@@ -82,7 +88,7 @@
     p_dev_rec->conn_params.peripheral_latency = BTM_BLE_CONN_PARAM_UNDEF;
 
     LOG_DEBUG("Device added, handle=0x%x, p_dev_rec=%p, bd_addr=%s",
-              p_dev_rec->ble_hci_handle, p_dev_rec, bd_addr.ToString().c_str());
+              p_dev_rec->ble_hci_handle, p_dev_rec, PRIVATE_ADDRESS(bd_addr));
   }
 
   memset(p_dev_rec->sec_bd_name, 0, sizeof(tBTM_BD_NAME));
@@ -2049,6 +2055,11 @@
   /* proceed generate ER */
   btm_cb.devcb.ble_encryption_key_value = rand2;
   btm_notify_new_key(BTM_BLE_KEY_TYPE_ER);
+
+  /* if privacy is enabled, update the irk and RPA in the LE address manager */
+  if (btm_cb.ble_ctr_cb.privacy_mode != BTM_PRIVACY_NONE) {
+    BTM_BleConfigPrivacy(true);
+  }
 }
 
 struct reset_id_data {
diff --git a/system/stack/btm/btm_ble_gap.cc b/system/stack/btm/btm_ble_gap.cc
index 76f6c6f..c2fda91 100644
--- a/system/stack/btm/btm_ble_gap.cc
+++ b/system/stack/btm/btm_ble_gap.cc
@@ -805,7 +805,7 @@
 
   GAP_BleAttrDBUpdate(GATT_UUID_GAP_CENTRAL_ADDR_RESOL, &gap_ble_attr_value);
 
-    bluetooth::shim::ACL_ConfigureLePrivacy(privacy_mode);
+  bluetooth::shim::ACL_ConfigureLePrivacy(privacy_mode);
   return true;
 }
 
diff --git a/system/stack/test/stack_avrcp_test.cc b/system/stack/test/stack_avrcp_test.cc
index 72ec45f..e731e98 100644
--- a/system/stack/test/stack_avrcp_test.cc
+++ b/system/stack/test/stack_avrcp_test.cc
@@ -27,6 +27,56 @@
   virtual ~StackAvrcpTest() = default;
 };
 
+TEST_F(StackAvrcpTest, test_avrcp_ctrl_parse_vendor_rsp) {
+  uint8_t scratch_buf[512]{};
+  uint16_t scratch_buf_len = 512;
+  tAVRC_MSG msg{};
+  tAVRC_RESPONSE result{};
+  uint8_t vendor_rsp_buf[512]{};
+
+  msg.hdr.opcode = AVRC_OP_VENDOR;
+  msg.hdr.ctype = AVRC_CMD_STATUS;
+
+  memset(vendor_rsp_buf, 0, sizeof(vendor_rsp_buf));
+  vendor_rsp_buf[0] = AVRC_PDU_GET_ELEMENT_ATTR;
+  uint8_t* p = &vendor_rsp_buf[2];
+  UINT16_TO_BE_STREAM(p, 0x0009);   // parameter length
+  UINT8_TO_STREAM(p, 0x01);         // number of attributes
+  UINT32_TO_STREAM(p, 0x00000000);  // attribute ID
+  UINT16_TO_STREAM(p, 0x0000);      // character set ID
+  UINT16_TO_STREAM(p, 0xffff);      // attribute value length
+  msg.vendor.p_vendor_data = vendor_rsp_buf;
+  msg.vendor.vendor_len = 13;
+  EXPECT_EQ(
+      AVRC_Ctrl_ParsResponse(&msg, &result, scratch_buf, &scratch_buf_len),
+      AVRC_STS_INTERNAL_ERR);
+}
+
+TEST_F(StackAvrcpTest, test_avrcp_parse_browse_rsp) {
+  uint8_t scratch_buf[512]{};
+  uint16_t scratch_buf_len = 512;
+  tAVRC_MSG msg{};
+  tAVRC_RESPONSE result{};
+  uint8_t browse_rsp_buf[512]{};
+
+  msg.hdr.opcode = AVRC_OP_BROWSE;
+
+  memset(browse_rsp_buf, 0, sizeof(browse_rsp_buf));
+  browse_rsp_buf[0] = AVRC_PDU_GET_ITEM_ATTRIBUTES;
+  uint8_t* p = &browse_rsp_buf[1];
+  UINT16_TO_BE_STREAM(p, 0x000a);   // parameter length;
+  UINT8_TO_STREAM(p, 0x04);         // status
+  UINT8_TO_STREAM(p, 0x01);         // number of attribute
+  UINT32_TO_STREAM(p, 0x00000000);  // attribute ID
+  UINT16_TO_STREAM(p, 0x0000);      // character set ID
+  UINT16_TO_STREAM(p, 0xffff);      // attribute value length
+  msg.browse.p_browse_data = browse_rsp_buf;
+  msg.browse.browse_len = 13;
+  EXPECT_EQ(
+      AVRC_Ctrl_ParsResponse(&msg, &result, scratch_buf, &scratch_buf_len),
+      AVRC_STS_BAD_CMD);
+}
+
 TEST_F(StackAvrcpTest, test_avrcp_parse_browse_cmd) {
   uint8_t scratch_buf[512]{};
   tAVRC_MSG msg{};
diff --git a/system/test/mock/mock_bta_dm_act.h b/system/test/mock/mock_bta_dm_act.h
index 5a566dc..af58600 100644
--- a/system/test/mock/mock_bta_dm_act.h
+++ b/system/test/mock/mock_bta_dm_act.h
@@ -264,6 +264,15 @@
 };
 extern struct bta_dm_clear_event_filter bta_dm_clear_event_filter;
 
+// Name: bta_dm_ble_reset_id
+// Params: None
+// Return: void
+struct bta_dm_ble_reset_id {
+  std::function<void()> body{[]() {}};
+  void operator()() { body(); };
+};
+extern struct bta_dm_ble_reset_id bta_dm_ble_reset_id;
+
 // Name: bta_dm_ble_passkey_reply
 // Params: const RawAddress& bd_addr, bool accept, uint32_t passkey
 // Return: void
diff --git a/system/test/mock/mock_main_shim_btm_api.cc b/system/test/mock/mock_main_shim_btm_api.cc
index d799c20..5b21a76 100644
--- a/system/test/mock/mock_main_shim_btm_api.cc
+++ b/system/test/mock/mock_main_shim_btm_api.cc
@@ -429,3 +429,8 @@
   mock_function_count_map[__func__]++;
   return BTM_SUCCESS;
 }
+
+tBTM_STATUS bluetooth::shim::BTM_BleResetId() {
+  mock_function_count_map[__func__]++;
+  return BTM_SUCCESS;
+}