Merge "Check in_use to prevent accessing deallocated cb" into main
diff --git a/system/bta/gatt/bta_gattc_act.cc b/system/bta/gatt/bta_gattc_act.cc
index 636951c..95eb0a7 100644
--- a/system/bta/gatt/bta_gattc_act.cc
+++ b/system/bta/gatt/bta_gattc_act.cc
@@ -297,7 +297,7 @@
   /* close all CLCB related to this app */
   if (com::android::bluetooth::flags::gatt_client_dynamic_allocation()) {
     for (auto& p_clcb : bta_gattc_cb.clcb_set) {
-      if (p_clcb->p_rcb != p_clreg) {
+      if (!p_clcb->in_use || p_clcb->p_rcb != p_clreg) {
         continue;
       }
       p_clreg->dereg_pending = true;
@@ -1504,7 +1504,8 @@
       tBTA_GATTC_CLCB* p_clcb = &bta_gattc_cb.clcb[0];
       if (com::android::bluetooth::flags::gatt_client_dynamic_allocation()) {
         for (auto& p_clcb_i : bta_gattc_cb.clcb_set) {
-          if (p_clcb_i->p_srcb == p_srvc_cb) {
+          if (p_clcb_i->in_use && p_clcb_i->p_srcb == p_srvc_cb) {
+            p_clcb = p_clcb_i.get();
             found = true;
             break;
           }
@@ -1576,7 +1577,7 @@
     if (p_clcb == NULL || (p_clcb && p_clcb->p_q_cmd != NULL)) {
       if (com::android::bluetooth::flags::gatt_client_dynamic_allocation()) {
         for (auto& p_clcb_i : bta_gattc_cb.clcb_set) {
-          if (p_clcb_i->p_srcb == p_srcb && p_clcb_i->p_q_cmd == NULL) {
+          if (p_clcb_i->in_use && p_clcb_i->p_srcb == p_srcb && p_clcb_i->p_q_cmd == NULL) {
             p_clcb = p_clcb_i.get();
             break;
           }
diff --git a/system/bta/gatt/bta_gattc_utils.cc b/system/bta/gatt/bta_gattc_utils.cc
index 36e05ba..ca911de 100644
--- a/system/bta/gatt/bta_gattc_utils.cc
+++ b/system/bta/gatt/bta_gattc_utils.cc
@@ -145,7 +145,7 @@
 tBTA_GATTC_CLCB* bta_gattc_find_clcb_by_conn_id(tCONN_ID conn_id) {
   if (com::android::bluetooth::flags::gatt_client_dynamic_allocation()) {
     for (auto& p_clcb : bta_gattc_cb.clcb_set) {
-      if (p_clcb->bta_conn_id == conn_id) {
+      if (p_clcb->in_use && p_clcb->bta_conn_id == conn_id) {
         return p_clcb.get();
       }
     }
@@ -960,6 +960,9 @@
   if (com::android::bluetooth::flags::gatt_client_dynamic_allocation()) {
     stream << " ->clcb (dynamic)\n";
     for (auto& p_clcb : bta_gattc_cb.clcb_set) {
+      if (!p_clcb->in_use) {
+        continue;
+      }
       entry_count++;
       stream << "  conn_id: " << loghex(p_clcb->bta_conn_id)
              << "  address: " << ADDRESS_TO_LOGGABLE_STR(p_clcb->bda)