BT: Features supported changes for system/bt

Fixed Static Analysis Issues
change-id: If389820b427f39e1030013f14d5538d7c99ce9c6

Bluetooth: Add support to send/receive raw command/event.
change-id: Id70d419c19a2b983450ebc113b8d0cca2b36ecf9

BT: Enable SoC logging through developer option.
change-id: I7193d085a1de4aa1e4b0ed6ec16a4812c8dc70b5

Bluetooth: Do not go for inquiry in BONDING State.
change-id: I71b902ae201e32a0fb18fd3bce52fd86e8cbcdd5

Bluetooth: Read BLE vendor capability to proceed on Secure conn.
change-id: I64e79d4e6fff7d9f1b0ea7272250e8155f5888e2

Handling Authentication Failure From the lower layer.
change-id: Ic9003f2b85bbaaa30b201b8a639a9d9b52055ac5

Bluetooth:CoreStack: DUT Stack Logging.
change-id: I6e74bdb1cda4455c50314f67bbcd19accd3c31e4

Bluetooth:CoreStack: DUT Stack Logging set2
change-id: I7a25d751b200e8ece87f9e5fd79ab48d736087cb

Bluetooth: Add debug logs for the remote device information
change-id: I857016c056635907586d8a9d0d577edde4efc34a

Add logs to provide the below remote device information
change-Id: I99f51841716e27ef7170b7566379b975c99a65e0

Change-Id: If276099626b0da9a7c606b8c0463460bfa846921
CRs-Fixed: 2021908
diff --git a/bta/dm/bta_dm_act.cc b/bta/dm/bta_dm_act.cc
index 75447e3..3f3ebc4 100644
--- a/bta/dm/bta_dm_act.cc
+++ b/bta/dm/bta_dm_act.cc
@@ -648,7 +648,25 @@
   if (p_data->set_visibility.pair_mode != BTA_DM_IGNORE ||
       p_data->set_visibility.conn_paired_only != BTA_DM_IGNORE)
     BTM_SetPairableMode((bool)(!(bta_dm_cb.disable_pair_mode)),
-                        bta_dm_cb.conn_paired_only);
+                          bta_dm_cb.conn_paired_only);
+}
+
+/*******************************************************************************
+**
+** Function         bta_dm_hci_raw_command
+**
+** Description      Send a HCI RAW command to the controller
+**
+**
+** Returns          void
+**
+*******************************************************************************/
+void bta_dm_hci_raw_command (tBTA_DM_MSG *p_data)
+{
+    tBTM_STATUS status;
+    APPL_TRACE_API("bta_dm_hci_raw_command");
+    status = BTM_Hci_Raw_Command(p_data->btc_command.opcode,p_data->btc_command.param_len,p_data->btc_command.p_param_buf, p_data->btc_command.p_cback);
+
 }
 
 /*******************************************************************************
@@ -2149,11 +2167,13 @@
       /* check whether connection already exists to the device
          if connection exists, we don't have to wait for ACL
          link to go down to start search on next device */
+    if (transport == BT_TRANSPORT_BR_EDR) {
       if (BTM_IsAclConnectionUp(bta_dm_search_cb.peer_bdaddr,
                                 BT_TRANSPORT_BR_EDR))
         bta_dm_search_cb.wait_disc = false;
       else
         bta_dm_search_cb.wait_disc = true;
+    }
 
       if (bta_dm_search_cb.p_btm_inq_info) {
         APPL_TRACE_DEBUG(
@@ -2711,6 +2731,9 @@
            and initiate a name request with values from key_notif */
         if (p_data->key_notif.bd_name[0] == 0) {
           bta_dm_cb.pin_evt = pin_evt;
+          /* Store the local and remote io caps */
+          bta_dm_cb.loc_io_caps = sec_event.cfm_req.loc_io_caps;
+          bta_dm_cb.rmt_io_caps = sec_event.cfm_req.rmt_io_caps;
           bdcpy(bta_dm_cb.pin_bd_addr, p_data->key_notif.bd_addr);
           BTA_COPY_DEVICE_CLASS(bta_dm_cb.pin_dev_class,
                                 p_data->key_notif.dev_class);
@@ -3092,7 +3115,8 @@
       bta_dm_cb.device_list.le_count--;
     conn.link_down.link_type = p_data->acl_change.transport;
 
-    if (bta_dm_search_cb.wait_disc &&
+    if ((p_data->acl_change.transport == BT_TRANSPORT_BR_EDR) &&
+        bta_dm_search_cb.wait_disc &&
         !bdcmp(bta_dm_search_cb.peer_bdaddr, p_bda)) {
       bta_dm_search_cb.wait_disc = false;
 
diff --git a/bta/dm/bta_dm_api.cc b/bta/dm/bta_dm_api.cc
index 90ca94b..7af6570 100644
--- a/bta/dm/bta_dm_api.cc
+++ b/bta/dm/bta_dm_api.cc
@@ -182,6 +182,42 @@
 }
 
 /*******************************************************************************
+**
+** Function         BTA_DmHciRawCommand
+**
+** Description      This function sends the HCI Raw  command
+**                  to the controller
+**
+**
+** Returns          tBTA_STATUS
+**
+*******************************************************************************/
+tBTA_STATUS BTA_DmHciRawCommand (uint16_t opcode, uint8_t param_len,
+                                         uint8_t *p_param_buf,
+                                         tBTA_RAW_CMPL_CBACK *p_cback)
+{
+
+  tBTA_DM_API_RAW_COMMAND *p_msg;
+  uint16_t size;
+
+  size = sizeof (tBTA_DM_API_RAW_COMMAND) + param_len;
+  p_msg = (tBTA_DM_API_RAW_COMMAND *) osi_malloc(size);
+  if (p_msg != NULL) {
+    p_msg->hdr.event = BTA_DM_API_HCI_RAW_COMMAND_EVT;
+    p_msg->opcode = opcode;
+    p_msg->param_len = param_len;
+    p_msg->p_param_buf = (uint8_t *)(p_msg + 1);
+    p_msg->p_cback = p_cback;
+
+    memcpy (p_msg->p_param_buf, p_param_buf, param_len);
+
+    bta_sys_sendmsg(p_msg);
+  }
+  return BTA_SUCCESS;
+
+}
+
+/*******************************************************************************
  *
  * Function         BTA_DmSearch
  *
diff --git a/bta/dm/bta_dm_int.h b/bta/dm/bta_dm_int.h
index 74eabd7..692dbfa 100644
--- a/bta/dm/bta_dm_int.h
+++ b/bta/dm/bta_dm_int.h
@@ -96,6 +96,7 @@
   BTA_DM_API_EXECUTE_CBACK_EVT,
   BTA_DM_API_REMOVE_ALL_ACL_EVT,
   BTA_DM_API_REMOVE_DEVICE_EVT,
+  BTA_DM_API_HCI_RAW_COMMAND_EVT,
   BTA_DM_MAX_EVT
 };
 
@@ -136,6 +137,15 @@
   uint8_t conn_paired_only;
 } tBTA_DM_API_SET_VISIBILITY;
 
+/* data type for BTA_DM_API_HCI_RAW_COMMAND_EVT */
+typedef struct
+{
+  BT_HDR hdr;
+  uint16_t opcode;
+  uint8_t param_len;
+  uint8_t *p_param_buf;
+  tBTA_RAW_CMPL_CBACK *p_cback;
+} tBTA_DM_API_RAW_COMMAND;
 enum {
   BTA_DM_RS_NONE, /* straight API call */
   BTA_DM_RS_OK,   /* the role switch result - successful */
@@ -507,7 +517,7 @@
 
   tBTA_DM_API_REMOVE_ACL remove_acl;
   tBTA_DM_API_REMOVE_ALL_ACL remove_all_acl;
-
+  tBTA_DM_API_RAW_COMMAND btc_command;
 } tBTA_DM_MSG;
 
 #define BTA_DM_NUM_PEER_DEVICE 7
@@ -874,4 +884,5 @@
 extern void bta_dm_execute_callback(tBTA_DM_MSG* p_data);
 
 extern void bta_dm_remove_all_acl(tBTA_DM_MSG* p_data);
+extern void bta_dm_hci_raw_command(tBTA_DM_MSG *p_data);
 #endif /* BTA_DM_INT_H */
diff --git a/bta/dm/bta_dm_main.cc b/bta/dm/bta_dm_main.cc
index d91eaba..d3676ea 100644
--- a/bta/dm/bta_dm_main.cc
+++ b/bta/dm/bta_dm_main.cc
@@ -91,6 +91,7 @@
 
     bta_dm_remove_all_acl, /* BTA_DM_API_REMOVE_ALL_ACL_EVT */
     bta_dm_remove_device,  /* BTA_DM_API_REMOVE_DEVICE_EVT */
+    bta_dm_hci_raw_command, /* BTA_DM_API_HCI_RAW_COMMAND_EVT */
 };
 
 /* state machine action enumeration list */
@@ -333,7 +334,7 @@
   /* execute action functions */
   for (i = 0; i < BTA_DM_SEARCH_ACTIONS; i++) {
     action = state_table[p_msg->event & 0x00ff][i];
-    if (action != BTA_DM_SEARCH_IGNORE) {
+    if (action < BTA_DM_SEARCH_IGNORE) {
       (*bta_dm_search_action[action])((tBTA_DM_MSG*)p_msg);
     } else {
       break;
diff --git a/bta/hl/bta_hl_main.cc b/bta/hl/bta_hl_main.cc
index bc8f396..9030151 100644
--- a/bta/hl/bta_hl_main.cc
+++ b/bta/hl/bta_hl_main.cc
@@ -452,7 +452,7 @@
 
   for (i = 0; i < BTA_HL_CCH_ACTIONS; i++) {
     action = state_table[event][i];
-    if (action != BTA_HL_CCH_IGNORE) {
+    if (action < BTA_HL_CCH_IGNORE) {
       (*bta_hl_cch_action[action])(app_idx, mcl_idx, p_data);
     } else {
       /* discard HDP data */
@@ -503,7 +503,7 @@
 
   for (i = 0; i < BTA_HL_DCH_ACTIONS; i++) {
     action = state_table[event][i];
-    if (action != BTA_HL_DCH_IGNORE) {
+    if (action < BTA_HL_DCH_IGNORE) {
       (*bta_hl_dch_action[action])(app_idx, mcl_idx, mdl_idx, p_data);
     } else {
       /* discard mas data */
diff --git a/bta/include/bta_api.h b/bta/include/bta_api.h
index e27ba43..c148f28 100644
--- a/bta/include/bta_api.h
+++ b/bta/include/bta_api.h
@@ -702,6 +702,8 @@
 #define BTA_DM_BLE_PF_LIST_LOGIC_OR 1
 #define BTA_DM_BLE_PF_FILT_LOGIC_OR 0
 
+/* HCI RAW Command Callback */
+typedef tBTM_RAW_CMPL_CB tBTA_RAW_CMPL_CBACK;
 /* Search callback events */
 #define BTA_DM_INQ_RES_EVT 0  /* Inquiry result for a peer device. */
 #define BTA_DM_INQ_CMPL_EVT 1 /* Inquiry complete. */
@@ -1114,6 +1116,18 @@
  ******************************************************************************/
 extern void BTA_DmSetVisibility(tBTA_DM_DISC disc_mode, tBTA_DM_CONN conn_mode,
                                 uint8_t pairable_mode, uint8_t conn_filter);
+/*******************************************************************************
+**
+** Function         BTA_DmHciRawCommand
+**
+** Description      This function sends the HCI RAW command
+**                  to the controller
+**
+**
+** Returns          tBTA_STATUS
+**
+*******************************************************************************/
+extern tBTA_STATUS BTA_DmHciRawCommand (uint16_t opcode, uint8_t param_len, uint8_t *p_param_buf, tBTA_RAW_CMPL_CBACK *p_cback);
 
 /*******************************************************************************
  *
diff --git a/bta/sys/bta_sys_main.cc b/bta/sys/bta_sys_main.cc
index 32985e8..a137939 100644
--- a/bta/sys/bta_sys_main.cc
+++ b/bta/sys/bta_sys_main.cc
@@ -229,7 +229,7 @@
   /* execute action functions */
   for (i = 0; i < BTA_SYS_ACTIONS; i++) {
     action = state_table[p_msg->event & 0x00ff][i];
-    if (action != BTA_SYS_IGNORE) {
+    if (action < BTA_SYS_IGNORE) {
       (*bta_sys_action[action])((tBTA_SYS_HW_MSG*)p_msg);
     } else {
       break;
diff --git a/btif/include/btif_api.h b/btif/include/btif_api.h
index e066b83..82ee330 100644
--- a/btif/include/btif_api.h
+++ b/btif/include/btif_api.h
@@ -379,6 +379,17 @@
 bt_status_t btif_dut_mode_send(uint16_t opcode, uint8_t* buf, uint8_t len);
 
 /*******************************************************************************
+**
+** Function         btif_hci_cmd_send
+**
+** Description      Sends a HCI Raw command to the controller
+**
+** Returns          BT_STATUS_SUCCESS on success
+**
+*******************************************************************************/
+bt_status_t btif_hci_cmd_send(uint16_t opcode, uint8_t *buf, uint8_t len);
+
+/*******************************************************************************
  *
  * Function         btif_le_test_mode
  *
diff --git a/btif/src/bluetooth.cc b/btif/src/bluetooth.cc
index 9885117..a35a485 100644
--- a/btif/src/bluetooth.cc
+++ b/btif/src/bluetooth.cc
@@ -53,6 +53,7 @@
 #include "btif_a2dp.h"
 #include "btif_api.h"
 #include "btif_config.h"
+#include "device/include/controller.h"
 #include "btif_debug.h"
 #include "btif_storage.h"
 #include "btsnoop.h"
@@ -110,6 +111,10 @@
 /*SDP search client*/
 extern btsdp_interface_t* btif_sdp_get_interface();
 
+#ifdef WIPOWER_SUPPORTED
+extern wipower_interface_t *get_wipower_interface();
+#endif
+
 /* List all test interface here */
 extern btmcap_test_interface_t* stack_mcap_get_interface();
 
diff --git a/btif/src/btif_config.cc b/btif/src/btif_config.cc
index 3b3dc4f..0509941 100644
--- a/btif/src/btif_config.cc
+++ b/btif/src/btif_config.cc
@@ -181,10 +181,12 @@
   } else {
     time_t current_time = time(NULL);
     struct tm* time_created = localtime(&current_time);
-    strftime(btif_config_time_created, TIME_STRING_LENGTH, TIME_STRING_FORMAT,
-             time_created);
-    config_set_string(config, INFO_SECTION, FILE_TIMESTAMP,
-                      btif_config_time_created);
+    if (time_created) {
+      strftime(btif_config_time_created, TIME_STRING_LENGTH, TIME_STRING_FORMAT,
+               time_created);
+      config_set_string(config, INFO_SECTION, FILE_TIMESTAMP,
+                        btif_config_time_created);
+    }
   }
 
   // TODO(sharvil): use a non-wake alarm for this once we have
diff --git a/btif/src/btif_core.cc b/btif/src/btif_core.cc
index 2be458d..f33102e 100644
--- a/btif/src/btif_core.cc
+++ b/btif/src/btif_core.cc
@@ -524,6 +524,50 @@
 }
 
 /*******************************************************************************
+**
+**   BTIF Test Mode APIs
+**
+*****************************************************************************/
+#if HCI_RAW_CMD_INCLUDED == TRUE
+/*******************************************************************************
+**
+** Function         btif_hci_event_cback
+**
+** Description     Callback invoked on receiving HCI event
+**
+** Returns          None
+**
+*******************************************************************************/
+static void btif_hci_event_cback ( tBTM_RAW_CMPL *p )
+{
+  BTIF_TRACE_DEBUG("%s", __FUNCTION__);
+//  if((p != NULL) && (bt_hal_cbacks != NULL)
+//      && (bt_hal_cbacks->hci_event_recv_cb != NULL)) {
+//    HAL_CBACK(bt_hal_cbacks, hci_event_recv_cb, p->event_code, p->p_param_buf,
+//                                                                p->param_len);
+//  }
+//#endif
+}
+
+/*******************************************************************************
+**
+** Function        btif_hci_cmd_send
+**
+** Description     Sends a HCI raw command to the controller
+**
+** Returns         BT_STATUS_SUCCESS on success
+**
+*******************************************************************************/
+bt_status_t btif_hci_cmd_send(uint16_t opcode, uint8_t *buf, uint8_t len)
+{
+  BTIF_TRACE_DEBUG("%s", __FUNCTION__);
+
+  BTM_Hci_Raw_Command(opcode, len, buf, btif_hci_event_cback);
+  return BT_STATUS_SUCCESS;
+}
+#endif
+
+/*******************************************************************************
  *
  * Function         btif_dut_mode_cback
  *
diff --git a/btif/src/btif_debug_conn.cc b/btif/src/btif_debug_conn.cc
index 1a59456..bea2f8d 100644
--- a/btif/src/btif_debug_conn.cc
+++ b/btif/src/btif_debug_conn.cc
@@ -42,9 +42,11 @@
   const time_t secs = ms / 1000;
   struct tm* ptm = localtime(&secs);
 
-  char tempbuff[20];
-  strftime(tempbuff, sizeof(tempbuff), "%m-%d %H:%M:%S", ptm);
-  snprintf(buffer, len, "%s.%03u", tempbuff, (uint16_t)(ms % 1000));
+  char tempbuff[20] = {0};
+  if (ptm) {
+    strftime(tempbuff, sizeof(tempbuff), "%m-%d %H:%M:%S", ptm);
+    snprintf(buffer, len, "%s.%03u", tempbuff, (uint16_t)(ms % 1000));
+  }
 
   return buffer;
 }
diff --git a/btif/src/btif_dm.cc b/btif/src/btif_dm.cc
index df59fa9..1312feb 100644
--- a/btif/src/btif_dm.cc
+++ b/btif/src/btif_dm.cc
@@ -1498,8 +1498,9 @@
   BTIF_TRACE_EVENT("%s:  event = %d", __func__, event);
   switch (event) {
     case BTA_DM_DISC_RES_EVT: {
-      bt_property_t prop;
       uint32_t i = 0;
+      bt_property_t prop[2];
+      int num_properties = 0;
       bt_bdaddr_t bd_addr;
       bt_status_t ret;
 
@@ -1516,12 +1517,12 @@
         btif_dm_get_remote_services(&bd_addr);
         return;
       }
-      prop.type = BT_PROPERTY_UUIDS;
-      prop.len = 0;
+      prop[0].type = BT_PROPERTY_UUIDS;
+      prop[0].len = 0;
       if ((p_data->disc_res.result == BTA_SUCCESS) &&
           (p_data->disc_res.num_uuids > 0)) {
-        prop.val = p_data->disc_res.p_uuid_list;
-        prop.len = p_data->disc_res.num_uuids * MAX_UUID_SIZE;
+        prop[0].val = p_data->disc_res.p_uuid_list;
+        prop[0].len = p_data->disc_res.num_uuids * MAX_UUID_SIZE;
         for (i = 0; i < p_data->disc_res.num_uuids; i++) {
           char temp[256];
           uuid_to_string_legacy(
@@ -1556,12 +1557,27 @@
 
       if (p_data->disc_res.num_uuids != 0) {
         /* Also write this to the NVRAM */
-        ret = btif_storage_set_remote_device_property(&bd_addr, &prop);
+        ret = btif_storage_set_remote_device_property(&bd_addr, &prop[0]);
         ASSERTC(ret == BT_STATUS_SUCCESS, "storing remote services failed",
                 ret);
+        num_properties++;
+      }
+
+      /* Remote name update */
+      if (strlen((const char *) p_data->disc_res.bd_name)) {
+        prop[1].type = BT_PROPERTY_BDNAME;
+        prop[1].val = p_data->disc_res.bd_name;
+        prop[1].len = strlen((char *)p_data->disc_res.bd_name);
+
+        ret = btif_storage_set_remote_device_property(&bd_addr, &prop[1]);
+        ASSERTC(ret == BT_STATUS_SUCCESS, "failed to save remote device property", ret);
+        num_properties++;
+      }
+
+      if(num_properties > 0) {
         /* Send the event to the BTIF */
         HAL_CBACK(bt_hal_cbacks, remote_device_properties_cb, BT_STATUS_SUCCESS,
-                  &bd_addr, 1, &prop);
+                  &bd_addr, num_properties, prop);
       }
     } break;
 
@@ -1703,7 +1719,7 @@
       bt_status_t status;
       bt_property_t prop;
       prop.type = BT_PROPERTY_BDNAME;
-      prop.len = BD_NAME_LEN;
+      prop.len = BD_NAME_LEN + 1;
       prop.val = (void*)bdname;
 
       status = btif_storage_get_adapter_property(&prop);
@@ -2135,11 +2151,11 @@
    * to the end of the tBTA_DM_SEARCH */
   switch (event) {
     case BTA_DM_INQ_RES_EVT: {
-      if (p_data->inq_res.p_eir) param_len += HCI_EXT_INQ_RESPONSE_LEN;
+      if (p_data && p_data->inq_res.p_eir) param_len += HCI_EXT_INQ_RESPONSE_LEN;
     } break;
 
     case BTA_DM_DISC_RES_EVT: {
-      if (p_data->disc_res.raw_data_size && p_data->disc_res.p_raw_data)
+      if (p_data && p_data->disc_res.raw_data_size && p_data->disc_res.p_raw_data)
         param_len += p_data->disc_res.raw_data_size;
     } break;
   }
@@ -2148,7 +2164,7 @@
 
   /* if remote name is available in EIR, set teh flag so that stack doesnt
    * trigger RNR */
-  if (event == BTA_DM_INQ_RES_EVT)
+  if (p_data && event == BTA_DM_INQ_RES_EVT)
     p_data->inq_res.remt_name_not_required =
         check_eir_remote_name(p_data, NULL, NULL);
 
@@ -2173,7 +2189,7 @@
   if (p_data) param_len += sizeof(tBTA_DM_SEARCH);
   switch (event) {
     case BTA_DM_DISC_RES_EVT: {
-      if ((p_data->disc_res.result == BTA_SUCCESS) &&
+      if ((p_data && p_data->disc_res.result == BTA_SUCCESS) &&
           (p_data->disc_res.num_uuids > 0)) {
         param_len += (p_data->disc_res.num_uuids * MAX_UUID_SIZE);
       }
@@ -3458,11 +3474,13 @@
     btif_bond_event_t* event = &btif_dm_bond_events[i];
 
     char eventtime[20];
-    char temptime[20];
+    char temptime[20] = {0};
     struct tm* tstamp = localtime(&event->timestamp.tv_sec);
-    strftime(temptime, sizeof(temptime), "%H:%M:%S", tstamp);
-    snprintf(eventtime, sizeof(eventtime), "%s.%03ld", temptime,
-             event->timestamp.tv_nsec / 1000000);
+    if (tstamp) {
+      strftime(temptime, sizeof(temptime), "%H:%M:%S", tstamp);
+      snprintf(eventtime, sizeof(eventtime), "%s.%03ld", temptime,
+              event->timestamp.tv_nsec / 1000000);
+    }
 
     char bdaddr[18];
     bdaddr_to_string(&event->bd_addr, bdaddr, sizeof(bdaddr));
diff --git a/btif/src/btif_hl.cc b/btif/src/btif_hl.cc
index 16c6c45..2742f5d 100644
--- a/btif/src/btif_hl.cc
+++ b/btif/src/btif_hl.cc
@@ -3789,7 +3789,6 @@
 
   if (btif_hl_find_app_idx(((uint8_t)app_id), &app_idx)) {
     evt_param.unreg.app_idx = app_idx;
-    reg_counter--;
     len = sizeof(btif_hl_unreg_t);
     status = btif_transfer_context(btif_hl_proc_cb_evt, BTIF_HL_UNREG_APP,
                                    (char*)&evt_param, len, NULL);
diff --git a/btif/src/btif_sock_l2cap.cc b/btif/src/btif_sock_l2cap.cc
index d839b55..bd3f67a 100644
--- a/btif/src/btif_sock_l2cap.cc
+++ b/btif/src/btif_sock_l2cap.cc
@@ -444,22 +444,26 @@
   // std::mutex locked by caller
   accept_rs = btsock_l2cap_alloc_l(
       sock->name, (const bt_bdaddr_t*)p_open->rem_bda, false, 0);
-  accept_rs->connected = true;
-  accept_rs->security = sock->security;
-  accept_rs->fixed_chan = sock->fixed_chan;
-  accept_rs->channel = sock->channel;
-  accept_rs->handle = sock->handle;
-  accept_rs->app_uid = sock->app_uid;
-  sock->handle =
-      -1; /* We should no longer associate this handle with the server socket */
-  accept_rs->is_le_coc = sock->is_le_coc;
+  if (accept_rs) {
+    accept_rs->connected = true;
+    accept_rs->security = sock->security;
+    accept_rs->fixed_chan = sock->fixed_chan;
+    accept_rs->channel = sock->channel;
+    accept_rs->handle = sock->handle;
+    accept_rs->app_uid = sock->app_uid;
+    sock->handle =
+        -1; /* We should no longer associate this handle with the server socket */
+    accept_rs->is_le_coc = sock->is_le_coc;
 
-  /* Swap IDs to hand over the GAP connection to the accepted socket, and start
-     a new server on
-     the newly create socket ID. */
-  new_listen_id = accept_rs->id;
-  accept_rs->id = sock->id;
-  sock->id = new_listen_id;
+    /* Swap IDs to hand over the GAP connection to the accepted socket, and start
+       a new server on
+       the newly create socket ID. */
+    new_listen_id = accept_rs->id;
+    accept_rs->id = sock->id;
+    sock->id = new_listen_id;
+  } else {
+    APPL_TRACE_ERROR("Memory not allocated for accept_rs..");
+  }
 
   if (accept_rs) {
     // start monitor the socket
@@ -815,15 +819,15 @@
    *  mtu will be set below */
   std::unique_lock<std::mutex> lock(state_lock);
   l2cap_socket* sock = btsock_l2cap_find_by_id_l(id);
-  if (!sock) {
+
+  if (sock) {
+    sock->channel = psm;
+
+    if (btSock_start_l2cap_server_l(sock) != BT_STATUS_SUCCESS)
+          btsock_l2cap_free_l(sock);
+  } else {
     APPL_TRACE_ERROR("%s: Error: sock is null", __func__);
-    return;
   }
-
-  sock->channel = psm;
-
-  if (btSock_start_l2cap_server_l(sock) != BT_STATUS_SUCCESS)
-    btsock_l2cap_free_l(sock);
 }
 
 static bt_status_t btSock_start_l2cap_server_l(l2cap_socket* sock) {
diff --git a/btif/src/btif_sock_thread.cc b/btif/src/btif_sock_thread.cc
index b206892..0f22d02 100644
--- a/btif/src/btif_sock_thread.cc
+++ b/btif/src/btif_sock_thread.cc
@@ -506,7 +506,7 @@
           ps_i, MAX_POLL, count, ts[h].poll_count);
       return;
     }
-    if (ts[h].ps[ps_i].pfd.fd >= 0) {
+    if (ts[h].ps[ps_i].pfd.fd >= 0 && pfd_i < MAX_POLL) {
       pfds[pfd_i] = ts[h].ps[ps_i].pfd;
       ts[h].psi[pfd_i] = ps_i;
       count++;
diff --git a/btif/src/btif_storage.cc b/btif/src/btif_storage.cc
index e43adb6..d6eeca0 100644
--- a/btif/src/btif_storage.cc
+++ b/btif/src/btif_storage.cc
@@ -232,13 +232,13 @@
       uint32_t i;
       char buf[64];
       value[0] = 0;
+      int size = sizeof(value);
       for (i = 0; i < (prop->len) / sizeof(bt_uuid_t); i++) {
         bt_uuid_t* p_uuid = (bt_uuid_t*)prop->val + i;
         memset(buf, 0, sizeof(buf));
         uuid_to_string_legacy(p_uuid, buf, sizeof(buf));
-        strcat(value, buf);
-        // strcat(value, ";");
-        strcat(value, " ");
+        strlcat(value, buf, size);
+        strlcat(value, " ", size);
       }
       btif_config_set_str(bdstr, BTIF_STORAGE_PATH_REMOTE_SERVICE, value);
       break;
diff --git a/device/Android.bp b/device/Android.bp
index c8cc772..bc5a2b0 100644
--- a/device/Android.bp
+++ b/device/Android.bp
@@ -21,6 +21,14 @@
     shared_libs: [
         "liblog",
     ],
+
+//ifeq ($(strip $(TARGET_BUILD_VARIANT)),userdebug)
+//ifneq ($(strip $(BOARD_HAS_QTI_BT_ROME)),true))
+    cflags: [
+        "-DQLOGKIT_USERDEBUG",
+    ],
+//endif
+//endif
 }
 
 // Bluetooth device unit tests for target
diff --git a/device/include/controller.h b/device/include/controller.h
index 3e88250..cf3fe03 100644
--- a/device/include/controller.h
+++ b/device/include/controller.h
@@ -26,9 +26,15 @@
 #include "hci_layer.h"
 #include "hci_packet_factory.h"
 #include "hci_packet_parser.h"
+#include "osi/include/log.h"
+#include "utils/include/bt_utils.h"
 
 static const char CONTROLLER_MODULE[] = "controller_module";
 
+typedef struct controller_static_t {
+  void (*enable_soc_logging) (bool value);
+} controller_static_t;
+
 typedef struct controller_t {
   bool (*get_is_ready)(void);
 
@@ -89,6 +95,7 @@
 
 } controller_t;
 
+const controller_static_t *controller_get_static_interface();
 const controller_t* controller_get_interface();
 
 const controller_t* controller_get_test_interface(
diff --git a/device/src/controller.cc b/device/src/controller.cc
index f12a95b..b5312de 100644
--- a/device/src/controller.cc
+++ b/device/src/controller.cc
@@ -29,6 +29,8 @@
 #include "hcimsgs.h"
 #include "osi/include/future.h"
 #include "stack/include/btm_ble_api.h"
+#include "osi/include/log.h"
+#include "utils/include/bt_utils.h"
 
 const bt_event_mask_t BLE_EVENT_MASK = {
     {0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x1E, 0x7f}};
@@ -43,6 +45,7 @@
 #define BLE_SUPPORTED_STATES_SIZE 8
 #define BLE_SUPPORTED_FEATURES_SIZE 8
 #define MAX_LOCAL_SUPPORTED_CODECS_SIZE 8
+#define UNUSED(x) (void)(x)
 
 static const hci_t* hci;
 static const hci_packet_factory_t* packet_factory;
diff --git a/hci/include/hci_packet_parser.h b/hci/include/hci_packet_parser.h
index 520a584..6e3fca1 100644
--- a/hci/include/hci_packet_parser.h
+++ b/hci/include/hci_packet_parser.h
@@ -79,8 +79,8 @@
       uint8_t* local_supported_codecs);
 
   void (*parse_ble_read_offload_features_response)(
-    BT_HDR *response,
-    bool *ble_offload_features_supported);
+      BT_HDR *response,
+      bool *ble_offload_features_supported);
 } hci_packet_parser_t;
 
 const hci_packet_parser_t* hci_packet_parser_get_interface();
diff --git a/hci/src/hci_packet_factory.cc b/hci/src/hci_packet_factory.cc
index adf5f38..d5344ac 100644
--- a/hci/src/hci_packet_factory.cc
+++ b/hci/src/hci_packet_factory.cc
@@ -155,8 +155,8 @@
   return make_command_no_params(HCI_READ_LOCAL_SUPPORTED_CODECS);
 }
 
-static BT_HDR* make_ble_read_offload_features_support(void) {
-    return make_command_no_params(HCI_BLE_VENDOR_CAP_OCF);
+static BT_HDR *make_ble_read_offload_features_support(void) {
+return make_command_no_params(HCI_BLE_VENDOR_CAP_OCF);
 }
 
 static BT_HDR* make_ble_set_event_mask(const bt_event_mask_t* event_mask) {
diff --git a/hci/src/hci_packet_parser.cc b/hci/src/hci_packet_parser.cc
index e7f1034..735117d 100644
--- a/hci/src/hci_packet_parser.cc
+++ b/hci/src/hci_packet_parser.cc
@@ -190,6 +190,7 @@
     BT_HDR* response, uint8_t* resolving_list_size_ptr) {
   uint8_t* stream = read_command_complete_header(
       response, HCI_BLE_READ_RESOLVING_LIST_SIZE, 1 /* bytes after */);
+  assert(stream != NULL);
   STREAM_TO_UINT8(*resolving_list_size_ptr, stream);
 
   buffer_allocator->free(response);
@@ -199,6 +200,7 @@
     BT_HDR* response, uint16_t* ble_default_packet_length_ptr) {
   uint8_t* stream = read_command_complete_header(
       response, HCI_BLE_READ_DEFAULT_DATA_LENGTH, 2 /* bytes after */);
+  assert(stream != NULL);
   STREAM_TO_UINT8(*ble_default_packet_length_ptr, stream);
 }
 
diff --git a/include/bt_target.h b/include/bt_target.h
index e5c5a66..e546e3a 100644
--- a/include/bt_target.h
+++ b/include/bt_target.h
@@ -651,6 +651,9 @@
  * BLE
  *
  *****************************************************************************/
+#ifndef HCI_RAW_CMD_INCLUDED
+#define HCI_RAW_CMD_INCLUDED    TRUE
+#endif
 
 #ifndef LOCAL_BLE_CONTROLLER_ID
 #define LOCAL_BLE_CONTROLLER_ID (1)
diff --git a/osi/src/allocation_tracker.cc b/osi/src/allocation_tracker.cc
index 2dee1dc..03478b8 100644
--- a/osi/src/allocation_tracker.cc
+++ b/osi/src/allocation_tracker.cc
@@ -120,10 +120,14 @@
       allocations[return_ptr] = allocation;
     }
 
-    allocation->allocator_id = allocator_id;
-    allocation->freed = false;
-    allocation->size = requested_size;
-    allocation->ptr = return_ptr;
+    if (allocation) {
+      allocation->allocator_id = allocator_id;
+      allocation->freed = false;
+      allocation->size = requested_size;
+      allocation->ptr = return_ptr;
+    } else {
+      LOG_ERROR(LOG_TAG, "%s Memory not allocated for allocation." ,__func__);
+    }
   }
 
   // Add the canary on both sides
diff --git a/osi/src/config.cc b/osi/src/config.cc
index 1019721..2f4e84f 100644
--- a/osi/src/config.cc
+++ b/osi/src/config.cc
@@ -214,21 +214,27 @@
   section_t* sec = section_find(config, section);
   if (!sec) {
     sec = section_new(section);
-    list_append(config->sections, sec);
-  }
-
-  for (const list_node_t* node = list_begin(sec->entries);
-       node != list_end(sec->entries); node = list_next(node)) {
-    entry_t* entry = static_cast<entry_t*>(list_node(node));
-    if (!strcmp(entry->key, key)) {
-      osi_free(entry->value);
-      entry->value = osi_strdup(value);
-      return;
+    if (sec)
+      list_append(config->sections, sec);
+    else {
+      LOG_ERROR(LOG_TAG,"%s: Unable to allocate memory for section", __func__);
     }
   }
 
-  entry_t* entry = entry_new(key, value);
-  list_append(sec->entries, entry);
+  if (sec) {
+    for (const list_node_t* node = list_begin(sec->entries);
+         node != list_end(sec->entries); node = list_next(node)) {
+      entry_t* entry = static_cast<entry_t*>(list_node(node));
+      if (!strcmp(entry->key, key)) {
+        osi_free(entry->value);
+        entry->value = osi_strdup(value);
+        return;
+      }
+    }
+
+    entry_t* entry = entry_new(key, value);
+    list_append(sec->entries, entry);
+  }
 }
 
 bool config_remove_section(config_t* config, const char* section) {
diff --git a/osi/src/socket.cc b/osi/src/socket.cc
index 201f976..48f5619 100644
--- a/osi/src/socket.cc
+++ b/osi/src/socket.cc
@@ -51,6 +51,10 @@
 socket_t* socket_new(void) {
   socket_t* ret = (socket_t*)osi_calloc(sizeof(socket_t));
   int enable = 1;
+  if (ret == NULL) {
+    LOG_ERROR(LOG_TAG, "%s unable to allocate : %s", __func__, strerror(errno));
+    return NULL;
+  }
 
   ret->fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
   if (ret->fd == INVALID_FD) {
diff --git a/osi/src/thread.cc b/osi/src/thread.cc
index 61b44f2..c8745cb 100644
--- a/osi/src/thread.cc
+++ b/osi/src/thread.cc
@@ -69,7 +69,10 @@
   CHECK(work_queue_capacity != 0);
 
   thread_t* ret = static_cast<thread_t*>(osi_calloc(sizeof(thread_t)));
-
+  if (ret == NULL) {
+    LOG_ERROR(LOG_TAG, "%s unable to allocate memory" , __func__);
+    return NULL;
+  }
   ret->reactor = reactor_new();
   if (!ret->reactor) goto error;
 
diff --git a/stack/Android.bp b/stack/Android.bp
index 58c8fe9..7a9fc1d 100644
--- a/stack/Android.bp
+++ b/stack/Android.bp
@@ -174,7 +174,7 @@
     ],
     shared_libs: [
         "libcutils",
-        "liblog",
+         "liblog",
     ],
     required: [
         "libldacBT_enc",
@@ -234,6 +234,7 @@
     ],
     shared_libs: [
         "libcutils",
+		"liblog"
     ],
     static_libs: [
         "liblog",
diff --git a/stack/btm/btm_acl.cc b/stack/btm/btm_acl.cc
index 7e9787b..e8ef484 100644
--- a/stack/btm/btm_acl.cc
+++ b/stack/btm/btm_acl.cc
@@ -196,7 +196,7 @@
   tACL_CONN* p;
   uint8_t xx;
 
-  BTM_TRACE_DEBUG("btm_acl_created hci_handle=%d link_role=%d  transport=%d",
+  BTM_TRACE_WARNING("btm_acl_created hci_handle=%d link_role=%d  transport=%d",
                   hci_handle, link_role, transport);
   /* Ensure we don't have duplicates */
   p = btm_bda_to_acl(bda, transport);
@@ -438,47 +438,49 @@
 void btm_acl_update_busy_level(tBTM_BLI_EVENT event) {
   bool old_inquiry_state = btm_cb.is_inquiry;
   tBTM_BL_UPDATE_DATA evt;
+  uint8_t busy_level = btm_cb.busy_level;
   evt.busy_level_flags = 0;
   switch (event) {
     case BTM_BLI_ACL_UP_EVT:
       BTM_TRACE_DEBUG("BTM_BLI_ACL_UP_EVT");
+      busy_level = BTM_GetNumAclLinks();
       break;
     case BTM_BLI_ACL_DOWN_EVT:
       BTM_TRACE_DEBUG("BTM_BLI_ACL_DOWN_EVT");
+      busy_level = BTM_GetNumAclLinks();
       break;
     case BTM_BLI_PAGE_EVT:
       BTM_TRACE_DEBUG("BTM_BLI_PAGE_EVT");
       btm_cb.is_paging = true;
       evt.busy_level_flags = BTM_BL_PAGING_STARTED;
+      busy_level = BTM_BL_PAGING_STARTED;
       break;
     case BTM_BLI_PAGE_DONE_EVT:
       BTM_TRACE_DEBUG("BTM_BLI_PAGE_DONE_EVT");
       btm_cb.is_paging = false;
       evt.busy_level_flags = BTM_BL_PAGING_COMPLETE;
+      busy_level = BTM_BL_PAGING_COMPLETE;
       break;
     case BTM_BLI_INQ_EVT:
       BTM_TRACE_DEBUG("BTM_BLI_INQ_EVT");
       btm_cb.is_inquiry = true;
       evt.busy_level_flags = BTM_BL_INQUIRY_STARTED;
+      busy_level = BTM_BL_INQUIRY_STARTED;
       break;
     case BTM_BLI_INQ_CANCEL_EVT:
       BTM_TRACE_DEBUG("BTM_BLI_INQ_CANCEL_EVT");
       btm_cb.is_inquiry = false;
       evt.busy_level_flags = BTM_BL_INQUIRY_CANCELLED;
+      busy_level = BTM_BL_INQUIRY_COMPLETE;
       break;
     case BTM_BLI_INQ_DONE_EVT:
       BTM_TRACE_DEBUG("BTM_BLI_INQ_DONE_EVT");
       btm_cb.is_inquiry = false;
       evt.busy_level_flags = BTM_BL_INQUIRY_COMPLETE;
+      busy_level = BTM_BL_INQUIRY_COMPLETE;
       break;
   }
 
-  uint8_t busy_level;
-  if (btm_cb.is_paging || btm_cb.is_inquiry)
-    busy_level = 10;
-  else
-    busy_level = BTM_GetNumAclLinks();
-
   if ((busy_level != btm_cb.busy_level) ||
       (old_inquiry_state != btm_cb.is_inquiry)) {
     evt.event = BTM_BL_UPDATE_EVT;
@@ -512,6 +514,10 @@
 
   /* Get the current role */
   *p_role = p->link_role;
+  BTM_TRACE_WARNING ("BTM: Local device role : 0x%02x", *p_role );
+  BTM_TRACE_WARNING ("BTM: RemBdAddr: %02x%02x%02x%02x%02x%02x",
+                           remote_bd_addr[0], remote_bd_addr[1], remote_bd_addr[2], remote_bd_addr[3],
+                           remote_bd_addr[4], remote_bd_addr[5]);
   return (BTM_SUCCESS);
 }
 
@@ -545,9 +551,6 @@
   tBTM_PM_MODE pwr_mode;
   tBTM_PM_PWR_MD settings;
   BD_ADDR_PTR p_bda;
-  BTM_TRACE_API("BTM_SwitchRole BDA: %02x-%02x-%02x-%02x-%02x-%02x",
-                remote_bd_addr[0], remote_bd_addr[1], remote_bd_addr[2],
-                remote_bd_addr[3], remote_bd_addr[4], remote_bd_addr[5]);
 
   /* Make sure the local/remote devices supports switching */
   if (!btm_dev_support_switch(remote_bd_addr))
@@ -624,6 +627,10 @@
     btm_cb.devcb.switch_role_ref_data.hci_status = HCI_ERR_UNSUPPORTED_VALUE;
     btm_cb.devcb.p_switch_role_cb = p_cb;
   }
+  BTM_TRACE_WARNING ("BTM_SwitchRole BDA: %02x-%02x-%02x-%02x-%02x-%02x",
+  remote_bd_addr[0], remote_bd_addr[1], remote_bd_addr[2],
+  remote_bd_addr[3], remote_bd_addr[4], remote_bd_addr[5]);
+  BTM_TRACE_WARNING ("Requested New Role: %d", new_role)
   return (BTM_CMD_STARTED);
 }
 
@@ -890,6 +897,11 @@
         l2cble_notify_le_connection(p_acl_cb->remote_addr);
         btm_use_preferred_conn_params(p_acl_cb->remote_addr);
       }
+        BTM_TRACE_WARNING ("btm_read_remote_version_complete: BDA: %02x-%02x-%02x-%02x-%02x-%02x",
+                             p_acl_cb->remote_addr[0], p_acl_cb->remote_addr[1], p_acl_cb->remote_addr[2],
+                             p_acl_cb->remote_addr[3], p_acl_cb->remote_addr[4], p_acl_cb->remote_addr[5]);
+        BTM_TRACE_WARNING ("btm_read_remote_version_complete lmp_version %d manufacturer %d lmp_subversion %d",
+                                       p_acl_cb->lmp_version,p_acl_cb->manufacturer, p_acl_cb->lmp_subversion);
       break;
     }
   }
@@ -1395,7 +1407,9 @@
   tBTM_SEC_DEV_REC* p_dev_rec;
   tBTM_BL_ROLE_CHG_DATA evt;
 
-  BTM_TRACE_DEBUG("btm_acl_role_changed");
+  BTM_TRACE_WARNING ("btm_acl_role_changed: BDA: %02x-%02x-%02x-%02x-%02x-%02x",
+        p_bda[0], p_bda[1], p_bda[2], p_bda[3], p_bda[4], p_bda[5]);
+  BTM_TRACE_WARNING ("btm_acl_role_changed: New role: %d", new_role);
   /* Ignore any stray events */
   if (p == NULL) {
     /* it could be a failure */
@@ -1514,7 +1528,7 @@
   /* Make sure we don't exceed max port range.
    * Stack reserves scn 1 for HFP, HSP we still do the correct way.
    */
-  if ((scn >= BTM_MAX_SCN) || (scn == 1)) return false;
+  if ((scn >= BTM_MAX_SCN) || (scn <= 1)) return false;
 
   /* check if this port is available */
   if (!btm_cb.btm_scn[scn - 1]) {
@@ -1536,7 +1550,7 @@
  ******************************************************************************/
 bool BTM_FreeSCN(uint8_t scn) {
   BTM_TRACE_DEBUG("BTM_FreeSCN ");
-  if (scn <= BTM_MAX_SCN) {
+  if (scn <= BTM_MAX_SCN && scn > 0) {
     btm_cb.btm_scn[scn - 1] = false;
     return (true);
   } else
diff --git a/stack/btm/btm_devctl.cc b/stack/btm/btm_devctl.cc
index 12a48e0..f6a3de0 100644
--- a/stack/btm/btm_devctl.cc
+++ b/stack/btm/btm_devctl.cc
@@ -565,6 +565,56 @@
   return (p_prev);
 }
 
+
+/*******************************************************************************
+**
+** Function         BTM_Hci_Raw_Command
+**
+** Description      Send  HCI raw command to the controller.
+**
+** Returns
+**      BTM_SUCCESS         Command sent. Does not expect command complete
+**                              event. (command cmpl callback param is NULL)
+**      BTM_CMD_STARTED     Command sent. Waiting for command cmpl event.
+**
+**
+*******************************************************************************/
+tBTM_STATUS BTM_Hci_Raw_Command(uint16_t opcode, uint8_t param_len,
+                              uint8_t *p_param_buf, tBTM_RAW_CMPL_CB *p_cb)
+{
+  void *p_buf;
+#if HCI_RAW_CMD_INCLUDED == TRUE
+  tBTM_DEVCB  *p_devcb = &btm_cb.devcb;
+#endif
+
+BTM_TRACE_EVENT ("BTM: BTM_Hci_Raw_Command: Opcode: 0x%04X, ParamLen: %i.",
+                   opcode, param_len);
+
+  /* Allocate a buffer to hold HCI command plus the callback function */
+  p_buf = osi_malloc((uint16_t)(sizeof(BT_HDR) + sizeof (tBTM_CMPL_CB *) +
+                          param_len + HCIC_PREAMBLE_SIZE));
+  if (p_buf != NULL) {
+    btsnd_hcic_raw_cmd (p_buf, opcode, param_len, p_param_buf, (void *)p_cb);
+
+    /* Return value */
+#if HCI_RAW_CMD_INCLUDED == TRUE
+    if (p_cb != NULL) {
+      if(p_cb != (p_devcb->p_hci_evt_cb)) {
+        p_devcb->p_hci_evt_cb = p_cb;
+      }
+            return BTM_CMD_STARTED;
+    }
+#else
+    if (p_cb != NULL)
+      return BTM_CMD_STARTED;
+#endif
+    else
+      return BTM_SUCCESS;
+  }
+  else
+    return BTM_NO_RESOURCES;
+
+}
 /*******************************************************************************
  *
  * Function         BTM_VendorSpecificCommand
@@ -589,6 +639,32 @@
                              (void*)p_cb);
 }
 
+#if HCI_RAW_CMD_INCLUDED == TRUE
+/*******************************************************************************
+**
+** Function         btm_hci_event
+**
+** Description      This function is called when HCI event is received
+**                  from the HCI layer.
+**
+** Returns          void
+**
+*******************************************************************************/
+void btm_hci_event(uint8_t *p, uint8_t event_code, uint8_t param_len)
+{
+  tBTM_DEVCB     *p_devcb = &btm_cb.devcb;
+  tBTM_RAW_CMPL  raw_cplt_params;
+
+  /* If there was a callback address for raw cmd complete, call it */
+  if (p_devcb->p_hci_evt_cb) {
+    /* Pass paramters to the callback function */
+    raw_cplt_params.event_code = event_code;   /* Number of bytes in return info */
+    raw_cplt_params.param_len = param_len;    /* Number of bytes in return info */
+    raw_cplt_params.p_param_buf = p;
+    (p_devcb->p_hci_evt_cb) (&raw_cplt_params);  /* Call the cmd complete callback function */
+  }
+}
+#endif
 /*******************************************************************************
  *
  * Function         btm_vsc_complete
diff --git a/stack/btm/btm_inq.cc b/stack/btm/btm_inq.cc
index 11c155f..aa11c64 100644
--- a/stack/btm/btm_inq.cc
+++ b/stack/btm/btm_inq.cc
@@ -1826,6 +1826,11 @@
       p_cur->dev_class[2] = dc[2];
       p_cur->clock_offset = clock_offset | BTM_CLOCK_OFFSET_VALID;
 
+      BTM_TRACE_WARNING ("btm_process_inq_results: BDA: %02x-%02x-%02x-%02x-%02x-%02x",
+                  bda[0], bda[1], bda[2],bda[3], bda[4], bda[5]);
+      BTM_TRACE_WARNING ("btm_process_inq_results: Dev class: %02x-%02x-%02x",
+                  p_cur->dev_class[0], p_cur->dev_class[1], p_cur->dev_class[2]);
+
       p_i->time_of_resp = time_get_os_boottime_ms();
 
       if (p_i->inq_count != p_inq->inq_counter)
diff --git a/stack/btm/btm_int_types.h b/stack/btm/btm_int_types.h
index 5905aeb..43cfd51 100644
--- a/stack/btm/btm_int_types.h
+++ b/stack/btm/btm_int_types.h
@@ -164,6 +164,10 @@
   uint32_t test_local_sign_cntr;
 #endif
 
+#if HCI_RAW_CMD_INCLUDED == TRUE
+  tBTM_RAW_CMPL_CB     *p_hci_evt_cb;       /* Callback function to be called when
+                                                HCI event is received successfully */
+#endif
   tBTM_IO_CAP loc_io_caps;      /* IO capability of the local device */
   tBTM_AUTH_REQ loc_auth_req;   /* the auth_req flag  */
   bool secure_connections_only; /* Rejects service level 0 connections if */
@@ -869,3 +873,7 @@
 typedef uint8_t tBTM_SEC_ACTION;
 
 #endif  // BTM_INT_TYPES_H
+/* HCI event handler */
+#if HCI_RAW_CMD_INCLUDED == TRUE
+extern void btm_hci_event(uint8_t *p, uint8_t event_code, uint8_t param_len);
+#endif
diff --git a/stack/btm/btm_pm.cc b/stack/btm/btm_pm.cc
index 0df4667..437f499 100644
--- a/stack/btm/btm_pm.cc
+++ b/stack/btm/btm_pm.cc
@@ -172,7 +172,7 @@
     /* check if the requested mode is supported */
     ind = mode - BTM_PM_MD_HOLD; /* make it base 0 */
     p_features = BTM_ReadLocalFeatures();
-    if (!(p_features[btm_pm_mode_off[ind]] & btm_pm_mode_msk[ind]))
+    if (ind < BTM_PM_NUM_SET_MODES && !(p_features[btm_pm_mode_off[ind]] & btm_pm_mode_msk[ind]))
       return BTM_MODE_UNSUPPORTED;
   }
 
@@ -346,7 +346,7 @@
   tBTM_PM_STATUS_CBACK* cb = NULL;
 
   /* clear the pending request for application */
-  if ((btm_cb.pm_pend_id != BTM_PM_SET_ONLY_ID) &&
+  if ((btm_cb.pm_pend_id < BTM_PM_SET_ONLY_ID) &&
       (btm_cb.pm_reg_db[btm_cb.pm_pend_id].mask & BTM_PM_REG_NOTIF)) {
     cb = btm_cb.pm_reg_db[btm_cb.pm_pend_id].cback;
   }
@@ -702,7 +702,7 @@
   }
 
   /* notify the caller is appropriate */
-  if ((btm_cb.pm_pend_id != BTM_PM_SET_ONLY_ID) &&
+  if ((btm_cb.pm_pend_id < BTM_PM_SET_ONLY_ID) &&
       (btm_cb.pm_reg_db[btm_cb.pm_pend_id].mask & BTM_PM_REG_NOTIF)) {
     (*btm_cb.pm_reg_db[btm_cb.pm_pend_id].cback)(
         btm_cb.acl_db[btm_cb.pm_pend_link].remote_addr, pm_status, 0, status);
diff --git a/stack/btm/btm_sec.cc b/stack/btm/btm_sec.cc
index f095305..f247ee3 100644
--- a/stack/btm/btm_sec.cc
+++ b/stack/btm/btm_sec.cc
@@ -206,10 +206,12 @@
  ******************************************************************************/
 static bool btm_serv_trusted(tBTM_SEC_DEV_REC* p_dev_rec,
                              tBTM_SEC_SERV_REC* p_serv_rec) {
-  if (BTM_SEC_IS_SERVICE_TRUSTED(p_dev_rec->trusted_mask,
+  if (p_serv_rec->service_id < BTM_SEC_MAX_SERVICES && BTM_SEC_IS_SERVICE_TRUSTED(p_dev_rec->trusted_mask,
                                  p_serv_rec->service_id)) {
     return (true);
   }
+  else
+    BTM_TRACE_ERROR("BTM_Sec: Service Id: %d not found", p_serv_rec->service_id);
   return (false);
 }
 
@@ -3389,12 +3391,12 @@
         (p_dev_rec->p_cur_service->security_flags & BTM_SEC_OUT_AUTHENTICATE)) {
       if (btm_cb.security_mode == BTM_SEC_MODE_SC) {
         /* SC only mode device requires MITM protection */
-        evt_data.auth_req = BTM_AUTH_SP_YES;
+        evt_data.auth_req = BTM_AUTH_SPGB_YES;
       } else {
         evt_data.auth_req =
             (p_dev_rec->p_cur_service->security_flags & BTM_SEC_OUT_MITM)
-                ? BTM_AUTH_SP_YES
-                : BTM_AUTH_SP_NO;
+                ? BTM_AUTH_SPGB_YES
+                : BTM_AUTH_SPGB_NO;
       }
     }
   }
@@ -3932,8 +3934,21 @@
     l2cu_start_post_bond_timer(p_dev_rec->hci_handle);
   }
 
-  if (!p_dev_rec) return;
+  if (!p_dev_rec) {
+  /* check if the handle is BTM_INVALID_HCI_HANDLE */
+    if(handle == BTM_INVALID_HCI_HANDLE) {
+      /* get the device with auth type as BTM_SEC_STATE_AUTHENTICATING */
+      p_dev_rec = btm_sec_find_dev_by_sec_state(BTM_SEC_STATE_AUTHENTICATING);
 
+      if ( p_dev_rec && (btm_cb.api.p_auth_complete_callback)) {
+        (*btm_cb.api.p_auth_complete_callback) (p_dev_rec->bd_addr,
+                                                p_dev_rec->dev_class,
+                                                p_dev_rec->sec_bd_name, status);
+        BTM_TRACE_DEBUG("btm_sec_auth_complete: Invalid Handle, send Auth failure");
+      }
+    }
+    return;
+  }
   /* keep the old sm4 flag and clear the retry bit in control block */
   old_sm4 = p_dev_rec->sm4;
   p_dev_rec->sm4 &= ~BTM_SM4_RETRY;
@@ -4441,7 +4456,6 @@
              (((status == HCI_ERR_AUTH_FAILURE) ||
                (status == HCI_ERR_KEY_MISSING) ||
                (status == HCI_ERR_HOST_REJECT_SECURITY) ||
-               (status == HCI_ERR_PAIRING_NOT_ALLOWED) ||
                (status == HCI_ERR_UNIT_KEY_USED) ||
                (status == HCI_ERR_PAIRING_WITH_UNIT_KEY_NOT_SUPPORTED) ||
                (status == HCI_ERR_ENCRY_MODE_NOT_ACCEPTABLE) ||
@@ -5296,10 +5310,9 @@
         (p_dev_rec->security_required & BTM_SEC_OUT_AUTHORIZE)) ||
        (!p_dev_rec->is_originator &&
         (p_dev_rec->security_required & BTM_SEC_IN_AUTHORIZE)))) {
-    BTM_TRACE_EVENT(
-        "service id:%d, is trusted:%d", p_dev_rec->p_cur_service->service_id,
-        (BTM_SEC_IS_SERVICE_TRUSTED(p_dev_rec->trusted_mask,
-                                    p_dev_rec->p_cur_service->service_id)));
+    BTM_TRACE_EVENT("service id:%d, is trusted:%d", 
+             p_dev_rec->p_cur_service->service_id,
+             btm_serv_trusted(p_dev_rec,p_dev_rec->p_cur_service));
     if ((btm_sec_are_all_trusted(p_dev_rec->trusted_mask) == false) &&
         (p_dev_rec->p_cur_service->service_id < BTM_SEC_MAX_SERVICES) &&
         (BTM_SEC_IS_SERVICE_TRUSTED(p_dev_rec->trusted_mask,
diff --git a/stack/btu/btu_hcif.cc b/stack/btu/btu_hcif.cc
index 83159bb..b9654d3 100644
--- a/stack/btu/btu_hcif.cc
+++ b/stack/btu/btu_hcif.cc
@@ -351,6 +351,9 @@
       btm_vendor_specific_evt(p, hci_evt_len);
       break;
   }
+#if HCI_RAW_CMD_INCLUDED == TRUE
+  btm_hci_event (p, hci_evt_code , hci_evt_len);
+#endif
 }
 
 /*******************************************************************************
diff --git a/stack/gap/gap_conn.cc b/stack/gap/gap_conn.cc
index 2e3911a..d294129 100644
--- a/stack/gap/gap_conn.cc
+++ b/stack/gap/gap_conn.cc
@@ -166,7 +166,7 @@
   if (p_cfg) p_ccb->cfg = *p_cfg;
 
   /* Configure L2CAP COC, if transport is LE */
-  if (transport == BT_TRANSPORT_LE) {
+  if (p_cfg && transport == BT_TRANSPORT_LE) {
     p_ccb->local_coc_cfg.credits = L2CAP_LE_DEFAULT_CREDIT;
     p_ccb->local_coc_cfg.mtu = p_cfg->mtu;
     p_ccb->local_coc_cfg.mps = L2CAP_LE_DEFAULT_MPS;
diff --git a/stack/hcic/hcicmds.cc b/stack/hcic/hcicmds.cc
index 62eb072..7400cc3 100644
--- a/stack/hcic/hcicmds.cc
+++ b/stack/hcic/hcicmds.cc
@@ -1381,6 +1381,24 @@
 #error "HCI_CMD_BUF_SIZE must be larger than 268"
 #endif
 
+void btsnd_hcic_raw_cmd (void *buffer, uint16_t opcode, uint8_t len,
+                                 uint8_t *p_data, void *p_cmd_cplt_cback)
+{
+  BT_HDR *p = (BT_HDR *)buffer;
+  uint8_t *pp = (uint8_t *)(p + 1);
+
+  p->len    = HCIC_PREAMBLE_SIZE + len;
+  p->offset = sizeof(void *);
+
+  *((void **)pp) = p_cmd_cplt_cback; /* Store command complete callback in buffer */
+  pp += sizeof(void *); /* Skip over callback pointer */
+
+  UINT16_TO_STREAM (pp, opcode);
+  UINT8_TO_STREAM  (pp, len);
+  ARRAY_TO_STREAM  (pp, p_data, len);
+
+  btu_hcif_send_cmd (LOCAL_BR_EDR_CONTROLLER_ID,  p);
+}
 void btsnd_hcic_vendor_spec_cmd(void* buffer, uint16_t opcode, uint8_t len,
                                 uint8_t* p_data, void* p_cmd_cplt_cback) {
   BT_HDR* p = (BT_HDR*)buffer;
diff --git a/stack/include/bt_types.h b/stack/include/bt_types.h
index da0baac..e68d337 100644
--- a/stack/include/bt_types.h
+++ b/stack/include/bt_types.h
@@ -19,6 +19,7 @@
 #ifndef BT_TYPES_H
 #define BT_TYPES_H
 
+#include <stdio.h>
 #include <stdbool.h>
 #include <stdint.h>
 
@@ -961,6 +962,8 @@
  *
  ******************************************************************************/
 static inline void bdcpy(BD_ADDR a, const BD_ADDR b) {
+  if (a ==  NULL || b == NULL)
+    return;
   int i;
 
   for (i = BD_ADDR_LEN; i != 0; i--) {
diff --git a/stack/include/btm_api_types.h b/stack/include/btm_api_types.h
index a4712da..6b4a4b0 100644
--- a/stack/include/btm_api_types.h
+++ b/stack/include/btm_api_types.h
@@ -93,6 +93,13 @@
   uint8_t* p_param_buf;
 } tBTM_VSC_CMPL;
 
+/* Structure returned with HCI Raw Command complete callback */
+typedef struct
+{
+  uint8_t  event_code;
+  uint8_t  param_len;
+  uint8_t   *p_param_buf;
+} tBTM_RAW_CMPL;
 #define BTM_VSC_CMPL_DATA_SIZE \
   (BTM_MAX_VENDOR_SPECIFIC_LEN + sizeof(tBTM_VSC_CMPL))
 /**************************************************
@@ -127,6 +134,11 @@
  */
 typedef void(tBTM_VSC_CMPL_CB)(tBTM_VSC_CMPL* p1);
 
+/* HCI RAW CMD callback function for notifying an application that a synchronous
+** BTM function is complete. The pointer contains the address of any returned data.
+*/
+typedef void (tBTM_RAW_CMPL_CB) (tBTM_RAW_CMPL *p1);
+
 /* Callback for apps to check connection and inquiry filters.
  * Parameters are the BD Address of remote and the Dev Class of remote. If the
  * app returns none zero, the connection or inquiry result will be dropped.
@@ -856,7 +868,8 @@
 /* the data type associated with BTM_BL_UPDATE_EVT */
 typedef struct {
   tBTM_BL_EVENT event;      /* The event reported. */
-  uint8_t busy_level;       /* when paging or inquiring, level is 10.
+  uint8_t busy_level;       /* when paging or inquiring, level is between
+                                      17 to 21 as the max links can be 16.
                              * Otherwise, the number of ACL links. */
   uint8_t busy_level_flags; /* Notifies actual inquiry/page activities */
 } tBTM_BL_UPDATE_DATA;
@@ -1864,3 +1877,14 @@
 typedef uint8_t tBTM_CONTRL_STATE;
 
 #endif  // BTM_API_TYPES_H
+/*******************************************************************************
+**
+** Function         BTM_Hci_Raw_Command
+**
+** Description      Send a HCI RAW started testingcommand to the controller.
+**
+*******************************************************************************/
+extern tBTM_STATUS BTM_Hci_Raw_Command(uint16_t opcode,
+                                                         uint8_t  param_len,
+                                                         uint8_t *p_param_buf,
+                                                         tBTM_RAW_CMPL_CB *p_cb);
diff --git a/stack/include/hcimsgs.h b/stack/include/hcimsgs.h
index ec9f5cd..eabb4f2 100644
--- a/stack/include/hcimsgs.h
+++ b/stack/include/hcimsgs.h
@@ -648,6 +648,8 @@
 #define HCID_HEADER_SIZE 4
 
 #define HCID_GET_SCO_LEN(p) (*((uint8_t*)((p) + 1) + (p)->offset + 2))
+extern void btsnd_hcic_raw_cmd (void *buffer, uint16_t opcode, uint8_t len,
+                                 uint8_t *p_data, void *p_cmd_cplt_cback);
 
 extern void btsnd_hcic_vendor_spec_cmd(void* buffer, uint16_t opcode,
                                        uint8_t len, uint8_t* p_data,
diff --git a/stack/l2cap/l2c_api.cc b/stack/l2cap/l2c_api.cc
index d85bea4..05fca13 100644
--- a/stack/l2cap/l2c_api.cc
+++ b/stack/l2cap/l2c_api.cc
@@ -61,7 +61,7 @@
   tL2C_RCB* p_rcb;
   uint16_t vpsm = psm;
 
-  L2CAP_TRACE_API("L2CAP - L2CA_Register() called for PSM: 0x%04x", psm);
+  L2CAP_TRACE_WARNING("L2CAP - L2CA_Register() called for PSM: 0x%04x", psm);
 
   /* Verify that the required callback info has been filled in
   **      Note:  Connection callbacks are required but not checked
@@ -125,7 +125,7 @@
   tL2C_LCB* p_lcb;
   int ii;
 
-  L2CAP_TRACE_API("L2CAP - L2CA_Deregister() called for PSM: 0x%04x", psm);
+  L2CAP_TRACE_WARNING("L2CAP - L2CA_Deregister() called for PSM: 0x%04x", psm);
 
   p_rcb = l2cu_find_rcb_by_psm(psm);
   if (p_rcb != NULL) {
@@ -231,7 +231,7 @@
   tL2C_CCB* p_ccb;
   tL2C_RCB* p_rcb;
 
-  L2CAP_TRACE_API(
+  L2CAP_TRACE_WARNING(
       "L2CA_ErtmConnectReq()  PSM: 0x%04x  BDA: %08x%04x  p_ertm_info: 0x%08x "
       "allowed:0x%x preferred:%d",
       psm, (p_bd_addr[0] << 24) + (p_bd_addr[1] << 16) + (p_bd_addr[2] << 8) +
@@ -672,7 +672,7 @@
   tL2C_LCB* p_lcb;
   tL2C_CCB* p_ccb;
 
-  L2CAP_TRACE_API(
+  L2CAP_TRACE_WARNING(
       "L2CA_ErtmConnectRsp()  CID: 0x%04x  Result: %d  Status: %d  BDA: "
       "%08x%04x  p_ertm_info:0x%08x",
       lcid, result, status, (p_bd_addr[0] << 24) + (p_bd_addr[1] << 16) +
@@ -845,7 +845,7 @@
 bool L2CA_DisconnectReq(uint16_t cid) {
   tL2C_CCB* p_ccb;
 
-  L2CAP_TRACE_API("L2CA_DisconnectReq()  CID: 0x%04x", cid);
+  L2CAP_TRACE_WARNING("L2CA_DisconnectReq()  CID: 0x%04x", cid);
 
   /* Find the channel control block. We don't know the link it is on. */
   p_ccb = l2cu_find_ccb_by_cid(NULL, cid);
@@ -872,7 +872,7 @@
 bool L2CA_DisconnectRsp(uint16_t cid) {
   tL2C_CCB* p_ccb;
 
-  L2CAP_TRACE_API("L2CA_DisconnectRsp()  CID: 0x%04x", cid);
+  L2CAP_TRACE_WARNING("L2CA_DisconnectRsp()  CID: 0x%04x", cid);
 
   /* Find the channel control block. We don't know the link it is on. */
   p_ccb = l2cu_find_ccb_by_cid(NULL, cid);
@@ -1138,7 +1138,7 @@
  *
  ******************************************************************************/
 uint8_t L2CA_SetDesireRole(uint8_t new_role) {
-  L2CAP_TRACE_API("L2CA_SetDesireRole() new:x%x, disallow_switch:%d", new_role,
+  L2CAP_TRACE_WARNING("L2CA_SetDesireRole() new:x%x, disallow_switch:%d", new_role,
                   l2cb.disallow_switch);
 
   if (L2CAP_ROLE_CHECK_SWITCH != (L2CAP_ROLE_CHECK_SWITCH & new_role)) {
@@ -1249,7 +1249,7 @@
   tL2C_CCB* p_ccb;
   bool on_off = !data_enabled;
 
-  L2CAP_TRACE_API("L2CA_FlowControl(%d)  CID: 0x%04x", on_off, cid);
+  L2CAP_TRACE_WARNING("L2CA_FlowControl(%d)  CID: 0x%04x", on_off, cid);
 
   /* Find the channel control block. We don't know the link it is on. */
   p_ccb = l2cu_find_ccb_by_cid(NULL, cid);
diff --git a/stack/l2cap/l2c_csm.cc b/stack/l2cap/l2c_csm.cc
index 0786897..907c0f0 100644
--- a/stack/l2cap/l2c_csm.cc
+++ b/stack/l2cap/l2c_csm.cc
@@ -153,7 +153,7 @@
   disconnect_ind = p_ccb->p_rcb->api.pL2CA_DisconnectInd_Cb;
   connect_cfm = p_ccb->p_rcb->api.pL2CA_ConnectCfm_Cb;
 
-  L2CAP_TRACE_EVENT("L2CAP - LCID: 0x%04x  st: CLOSED  evt: %s",
+  L2CAP_TRACE_WARNING("L2CAP - LCID: 0x%04x  st: CLOSED  evt: %s",
                     p_ccb->local_cid, l2c_csm_get_event_name(event));
 
   switch (event) {
@@ -221,7 +221,7 @@
 
       /* Wait for the info resp in this state before sending connect req (if
        * needed) */
-      if (!p_ccb->p_lcb->w4_info_rsp) {
+      if ((!p_ccb->p_lcb->w4_info_rsp)|| (BT_PSM_SDP == p_ccb->p_rcb->psm)) {
         /* Need to have at least one compatible channel to continue */
         if (!l2c_fcr_chk_chan_modes(p_ccb)) {
           l2cu_release_ccb(p_ccb);
@@ -317,7 +317,7 @@
   tL2CA_CONNECT_CFM_CB* connect_cfm = p_ccb->p_rcb->api.pL2CA_ConnectCfm_Cb;
   uint16_t local_cid = p_ccb->local_cid;
 
-  L2CAP_TRACE_EVENT("L2CAP - LCID: 0x%04x  st: ORIG_W4_SEC_COMP  evt: %s",
+  L2CAP_TRACE_WARNING("L2CAP - LCID: 0x%04x  st: ORIG_W4_SEC_COMP  evt: %s",
                     p_ccb->local_cid, l2c_csm_get_event_name(event));
 
 #if (L2CAP_UCD_INCLUDED == TRUE)
@@ -418,7 +418,7 @@
  ******************************************************************************/
 static void l2c_csm_term_w4_sec_comp(tL2C_CCB* p_ccb, uint16_t event,
                                      void* p_data) {
-  L2CAP_TRACE_EVENT("L2CAP - LCID: 0x%04x  st: TERM_W4_SEC_COMP  evt: %s",
+  L2CAP_TRACE_WARNING("L2CAP - LCID: 0x%04x  st: TERM_W4_SEC_COMP  evt: %s",
                     p_ccb->local_cid, l2c_csm_get_event_name(event));
 
 #if (L2CAP_UCD_INCLUDED == TRUE)
@@ -444,7 +444,7 @@
 
       /* Wait for the info resp in next state before sending connect ind (if
        * needed) */
-      if (!p_ccb->p_lcb->w4_info_rsp) {
+      if ((!p_ccb->p_lcb->w4_info_rsp)||(BT_PSM_SDP == p_ccb->p_rcb->psm)) {
         /* Don't need to get info from peer or already retrieved so continue */
         alarm_set_on_queue(p_ccb->l2c_ccb_timer, L2CAP_CHNL_CONNECT_TIMEOUT_MS,
                            l2c_ccb_timer_timeout, p_ccb,
@@ -537,7 +537,7 @@
   tL2CA_CONNECT_CFM_CB* connect_cfm = p_ccb->p_rcb->api.pL2CA_ConnectCfm_Cb;
   uint16_t local_cid = p_ccb->local_cid;
 
-  L2CAP_TRACE_EVENT("L2CAP - LCID: 0x%04x  st: W4_L2CAP_CON_RSP  evt: %s",
+  L2CAP_TRACE_WARNING("L2CAP - LCID: 0x%04x  st: W4_L2CAP_CON_RSP  evt: %s",
                     p_ccb->local_cid, l2c_csm_get_event_name(event));
 
   switch (event) {
@@ -666,7 +666,7 @@
       p_ccb->p_rcb->api.pL2CA_DisconnectInd_Cb;
   uint16_t local_cid = p_ccb->local_cid;
 
-  L2CAP_TRACE_EVENT("L2CAP - LCID: 0x%04x  st: W4_L2CA_CON_RSP  evt: %s",
+  L2CAP_TRACE_WARNING("L2CAP - LCID: 0x%04x  st: W4_L2CA_CON_RSP  evt: %s",
                     p_ccb->local_cid, l2c_csm_get_event_name(event));
 
   switch (event) {
@@ -771,7 +771,7 @@
   uint16_t local_cid = p_ccb->local_cid;
   uint8_t cfg_result;
 
-  L2CAP_TRACE_EVENT("L2CAP - LCID: 0x%04x  st: CONFIG  evt: %s",
+  L2CAP_TRACE_WARNING("L2CAP - LCID: 0x%04x  st: CONFIG  evt: %s",
                     p_ccb->local_cid, l2c_csm_get_event_name(event));
 
   switch (event) {
@@ -858,8 +858,8 @@
         }
       }
 
-      L2CAP_TRACE_API("L2CAP - Calling Config_Rsp_Cb(), CID: 0x%04x",
-                      p_ccb->local_cid);
+      L2CAP_TRACE_WARNING("L2CAP-peer_Config_Rsp,Local CID: 0x%04x,Remote CID: 0x%04x,PSM: %d,peer MTU present: %d,peer MTU: %d",
+                               p_ccb->local_cid,p_ccb->remote_cid,p_ccb->p_rcb->psm ,p_ccb->peer_cfg.mtu_present,p_ccb->peer_cfg.mtu);
       (*p_ccb->p_rcb->api.pL2CA_ConfigCfm_Cb)(p_ccb->local_cid, p_cfg);
       break;
 
@@ -945,6 +945,9 @@
           (!fixed_queue_is_empty(p_ccb->xmit_hold_q))) {
         l2c_link_check_send_pkts(p_ccb->p_lcb, NULL, NULL);
       }
+
+      L2CAP_TRACE_WARNING("L2CAP-Upper layer Config_Rsp,Local CID: 0x%04x,Remote CID: 0x%04x,PSM: %d,our MTU present:%d,our MTU:%d",
+                              p_ccb->local_cid,p_ccb->remote_cid, p_ccb->p_rcb->psm, p_ccb->our_cfg.mtu_present,p_ccb->our_cfg.mtu);
       break;
 
     case L2CEVT_L2CA_CONFIG_RSP_NEG: /* Upper layer config reject */
@@ -1192,7 +1195,7 @@
       p_ccb->p_rcb->api.pL2CA_DisconnectCfm_Cb;
   uint16_t local_cid = p_ccb->local_cid;
 
-  L2CAP_TRACE_EVENT("L2CAP - LCID: 0x%04x  st: W4_L2CAP_DISC_RSP  evt: %s",
+  L2CAP_TRACE_WARNING("L2CAP - LCID: 0x%04x  st: W4_L2CAP_DISC_RSP  evt: %s",
                     p_ccb->local_cid, l2c_csm_get_event_name(event));
 
   switch (event) {
@@ -1254,7 +1257,7 @@
       p_ccb->p_rcb->api.pL2CA_DisconnectInd_Cb;
   uint16_t local_cid = p_ccb->local_cid;
 
-  L2CAP_TRACE_EVENT("L2CAP - LCID: 0x%04x  st: W4_L2CA_DISC_RSP  evt: %s",
+  L2CAP_TRACE_WARNING("L2CAP - LCID: 0x%04x  st: W4_L2CA_DISC_RSP  evt: %s",
                     p_ccb->local_cid, l2c_csm_get_event_name(event));
 
   switch (event) {
diff --git a/stack/l2cap/l2c_fcr.cc b/stack/l2cap/l2c_fcr.cc
index 47714e1..f71beb1 100644
--- a/stack/l2cap/l2c_fcr.cc
+++ b/stack/l2cap/l2c_fcr.cc
@@ -1006,6 +1006,10 @@
     for (xx = 0; xx < num_bufs_acked; xx++) {
       BT_HDR* p_tmp =
           (BT_HDR*)fixed_queue_try_dequeue(p_fcrb->waiting_for_ack_q);
+      if (p_tmp == NULL) {
+        L2CAP_TRACE_WARNING ("%s: Unable to dequeue", __func__);
+        return (FALSE);
+      }
       ls = p_tmp->layer_specific & L2CAP_FCR_SAR_BITS;
 
       if ((ls == L2CAP_FCR_UNSEG_SDU) || (ls == L2CAP_FCR_END_SDU))
@@ -1185,12 +1189,12 @@
       if (p_fcrb->srej_sent) {
         /* If SREJ sent, save the frame for later processing as long as it is in
          * sequence */
-        next_srej =
-            (((BT_HDR*)fixed_queue_try_peek_last(p_fcrb->srej_rcv_hold_q))
-                 ->layer_specific +
-             1) &
-            L2CAP_FCR_SEQ_MODULO;
-
+        void * frame_msg = fixed_queue_try_peek_last(p_fcrb->srej_rcv_hold_q);
+        if (frame_msg == NULL) {
+          L2CAP_TRACE_WARNING ("%s: Unable to process frame", __func__);
+          return;
+        }
+        next_srej = (((BT_HDR *)frame_msg)->layer_specific + 1) & L2CAP_FCR_SEQ_MODULO;
         if ((tx_seq == next_srej) &&
             (fixed_queue_length(p_fcrb->srej_rcv_hold_q) <
              p_ccb->our_cfg.fcr.tx_win_sz)) {
@@ -1675,6 +1679,10 @@
   }
 
   p_buf = (BT_HDR*)fixed_queue_try_peek_first(p_ccb->xmit_hold_q);
+  if (p_buf == NULL) {
+    L2CAP_TRACE_ERROR ("%s: L2CAP - fixed_queue_try_peek_first returned queue as empty", __func__);
+    return NULL;
+  }
 
   /* If there is more data than the MPS, it requires segmentation */
   if (p_buf->len > max_pdu) {
@@ -1708,9 +1716,14 @@
     }
   } else /* Use the original buffer if no segmentation, or the last segment */
   {
-    p_xmit = (BT_HDR*)fixed_queue_try_dequeue(p_ccb->xmit_hold_q);
-
-    if (p_xmit->event != 0) last_seg = true;
+    void *seg_msg = fixed_queue_try_dequeue(p_ccb->xmit_hold_q);
+    if (seg_msg == NULL) {
+      L2CAP_TRACE_WARNING ("%s: Unable to process frame", __func__);
+      return (NULL);
+    }
+    p_xmit = (BT_HDR *)seg_msg;
+    if (p_xmit->event != 0)
+    last_seg = TRUE;
 
     p_xmit->event = p_ccb->local_cid;
   }
@@ -1815,6 +1828,10 @@
   uint16_t max_pdu = p_ccb->peer_conn_cfg.mps;
 
   p_buf = (BT_HDR*)fixed_queue_try_peek_first(p_ccb->xmit_hold_q);
+  if (p_buf == NULL) {
+    L2CAP_TRACE_ERROR ("%s: L2CAP - fixed_queue_try_peek_first returned queue as empty", __func__);
+    return (NULL);
+  }
 
   /* We are using the "event" field to tell is if we already started
    * segmentation */
diff --git a/stack/l2cap/l2c_utils.cc b/stack/l2cap/l2c_utils.cc
index 91c823e..3ca9ec1 100644
--- a/stack/l2cap/l2c_utils.cc
+++ b/stack/l2cap/l2c_utils.cc
@@ -3472,7 +3472,7 @@
       if (q_count > p_ccb->buff_quota) {
         p_ccb->cong_sent = true;
         if (p_ccb->p_rcb && p_ccb->p_rcb->api.pL2CA_CongestionStatus_Cb) {
-          L2CAP_TRACE_DEBUG(
+          L2CAP_TRACE_WARNING(
               "L2CAP - Calling CongestionStatus_Cb "
               "(true),CID:0x%04x,XmitQ:%u,Quota:%u",
               p_ccb->local_cid, q_count, p_ccb->buff_quota);
diff --git a/stack/l2cap/l2cap_client.cc b/stack/l2cap/l2cap_client.cc
index 2568fc8..5d0ed6d 100644
--- a/stack/l2cap/l2cap_client.cc
+++ b/stack/l2cap/l2cap_client.cc
@@ -105,6 +105,10 @@
   }
 
   l2cap_client_t* ret = (l2cap_client_t*)osi_calloc(sizeof(l2cap_client_t));
+  if (ret == NULL) {
+    LOG_ERROR(LOG_TAG, "%s unable to allocate space for L2CAP client.", __func__);
+    return NULL;
+  }
 
   ret->callbacks = *callbacks;
   ret->context = context;
diff --git a/stack/mcap/mca_cact.cc b/stack/mcap/mca_cact.cc
index 72efb85..bc249b9 100644
--- a/stack/mcap/mca_cact.cc
+++ b/stack/mcap/mca_cact.cc
@@ -105,8 +105,10 @@
     p_dcb = mca_dcb_by_hdl(p_ccb->p_tx_req->dcb_idx);
     /* the Abort API does not have the associated mdl_id.
      * Get the mdl_id in dcb to compose the request */
-    p_msg->mdl_id = p_dcb->mdl_id;
-    mca_dcb_event(p_dcb, MCA_DCB_API_CLOSE_EVT, NULL);
+    if(p_dcb) {
+      p_msg->mdl_id = p_dcb->mdl_id;
+      mca_dcb_event(p_dcb, MCA_DCB_API_CLOSE_EVT, NULL);
+    }
     osi_free_and_reset((void**)&p_ccb->p_tx_req);
     p_ccb->status = MCA_CCB_STAT_NORM;
     is_abort = true;
@@ -461,7 +463,7 @@
 
       if (chk_mdl) {
         p_dcb = mca_dcb_by_hdl(p_ccb->p_tx_req->dcb_idx);
-        if (evt_data.rsp.rsp_code == MCA_RSP_SUCCESS) {
+        if (p_dcb && evt_data.rsp.rsp_code == MCA_RSP_SUCCESS) {
           if (evt_data.hdr.mdl_id != p_dcb->mdl_id) {
             MCA_TRACE_ERROR("peer's mdl_id=%d != our mdl_id=%d",
                             evt_data.hdr.mdl_id, p_dcb->mdl_id);
diff --git a/stack/mcap/mca_csm.cc b/stack/mcap/mca_csm.cc
index 3c437f6..ecb9767 100644
--- a/stack/mcap/mca_csm.cc
+++ b/stack/mcap/mca_csm.cc
@@ -162,7 +162,7 @@
 
   /* execute action functions */
   action = state_table[event][MCA_CCB_ACT_COL];
-  if (action != MCA_CCB_IGNORE) {
+  if (action < MCA_CCB_IGNORE) {
     (*mca_ccb_action[action])(p_ccb, p_data);
   }
 }
@@ -313,10 +313,16 @@
 bool mca_ccb_uses_mdl_id(tMCA_CCB* p_ccb, uint16_t mdl_id) {
   bool uses = false;
   tMCA_DCB* p_dcb;
-  int i;
+  unsigned int i;
 
   i = mca_ccb_to_hdl(p_ccb) - 1;
-  p_dcb = &mca_cb.dcb[i * MCA_NUM_MDLS];
+
+  if (i*MCA_NUM_MDLS < MCA_NUM_DCBS) {
+    p_dcb = &mca_cb.dcb[i * MCA_NUM_MDLS];
+  } else {
+    MCA_TRACE_WARNING("dcb index out of range");
+    return uses;
+  }
   for (i = 0; i < MCA_NUM_MDLS; i++, p_dcb++) {
     if (p_dcb->state != MCA_DCB_NULL_ST && p_dcb->mdl_id == mdl_id) {
       uses = true;
diff --git a/stack/mcap/mca_dsm.cc b/stack/mcap/mca_dsm.cc
index 3494448..7053c44 100644
--- a/stack/mcap/mca_dsm.cc
+++ b/stack/mcap/mca_dsm.cc
@@ -126,7 +126,7 @@
 
   /* execute action functions */
   action = state_table[event][MCA_DCB_ACT_COL];
-  if (action != MCA_DCB_IGNORE) {
+  if (action < MCA_DCB_IGNORE) {
     (*mca_dcb_action[action])(p_dcb, p_data);
   }
 }
@@ -145,12 +145,18 @@
   tMCA_DCB *p_dcb = NULL, *p_dcb_tmp;
   tMCA_RCB* p_rcb = p_ccb->p_rcb;
   tMCA_CS* p_cs;
-  int i, max;
+  unsigned int  i, max;
 
   if (dep < MCA_NUM_DEPS) {
     p_cs = &p_rcb->dep[dep];
     i = mca_ccb_to_hdl(p_ccb) - 1;
-    p_dcb_tmp = &mca_cb.dcb[i * MCA_NUM_MDLS];
+    if( i*MCA_NUM_MDLS < MCA_NUM_DCBS) {
+      p_dcb_tmp = &mca_cb.dcb[i*MCA_NUM_MDLS];
+    }
+    else {
+      MCA_TRACE_WARNING("dcb index out of range");
+      return NULL;
+    }
     /* make sure p_cs->max_mdl is smaller than MCA_NUM_MDLS at MCA_CreateDep */
     max = p_cs->max_mdl;
     for (i = 0; i < max; i++, p_dcb_tmp++) {
@@ -181,14 +187,20 @@
   tMCA_DCB* p_dcb;
   tMCA_RCB* p_rcb = p_ccb->p_rcb;
   tMCA_CS* p_cs;
-  int i, max;
+  unsigned int i, max;
   uint8_t count = 0;
   uint8_t left;
 
   if (dep < MCA_NUM_DEPS) {
     p_cs = &p_rcb->dep[dep];
     i = mca_ccb_to_hdl(p_ccb) - 1;
-    p_dcb = &mca_cb.dcb[i * MCA_NUM_MDLS];
+    if( i*MCA_NUM_MDLS < MCA_NUM_DCBS) {
+      p_dcb = &mca_cb.dcb[i * MCA_NUM_MDLS];
+    }
+    else {
+      MCA_TRACE_WARNING("dcb index out of range");
+      return 0;
+    }
     /* make sure p_cs->max_mdl is smaller than MCA_NUM_MDLS at MCA_CreateDep */
     max = p_cs->max_mdl;
     for (i = 0; i < max; i++, p_dcb++) {
@@ -281,7 +293,13 @@
 
   MCA_TRACE_DEBUG("mca_dcb_close_by_mdl_id mdl_id=%d", mdl_id);
   i = mca_ccb_to_hdl(p_ccb) - 1;
-  p_dcb = &mca_cb.dcb[i * MCA_NUM_MDLS];
+  if( i*MCA_NUM_MDLS < MCA_NUM_DCBS) {
+    p_dcb = &mca_cb.dcb[i * MCA_NUM_MDLS];
+  }
+  else {
+    MCA_TRACE_WARNING("dcb index out of range");
+    return;
+  }
   for (i = 0; i < MCA_NUM_MDLS; i++, p_dcb++) {
     if (p_dcb->state) {
       if (p_dcb->mdl_id == mdl_id) {
diff --git a/stack/mcap/mca_l2c.cc b/stack/mcap/mca_l2c.cc
index fc08776..f0059ea 100644
--- a/stack/mcap/mca_l2c.cc
+++ b/stack/mcap/mca_l2c.cc
@@ -192,7 +192,7 @@
 
     /* if result ok, proceed with connection and send L2CAP
        config req */
-    if (result == L2CAP_CONN_OK) {
+    if (result == L2CAP_CONN_OK && p_tbl) {
       /* set channel state */
       p_tbl->state = MCA_TC_ST_CFG;
 
diff --git a/stack/mcap/mca_main.cc b/stack/mcap/mca_main.cc
index 9f9dbaf..60f4fca 100644
--- a/stack/mcap/mca_main.cc
+++ b/stack/mcap/mca_main.cc
@@ -233,14 +233,14 @@
  ******************************************************************************/
 void mca_set_cfg_by_tbl(tL2CAP_CFG_INFO* p_cfg, tMCA_TC_TBL* p_tbl) {
   tMCA_DCB* p_dcb;
-  const tL2CAP_FCR_OPTS* p_opt;
+  const tL2CAP_FCR_OPTS* p_opt = NULL;
   tMCA_FCS_OPT fcs = MCA_FCS_NONE;
 
   if (p_tbl->tcid == MCA_CTRL_TCID) {
     p_opt = &mca_l2c_fcr_opts_def;
   } else {
     p_dcb = mca_dcb_by_hdl(p_tbl->cb_idx);
-    if (p_dcb) {
+    if (p_dcb != NULL) {
       p_opt = &p_dcb->p_chnl_cfg->fcr_opt;
       fcs = p_dcb->p_chnl_cfg->fcs;
     }
@@ -249,7 +249,8 @@
   p_cfg->mtu_present = true;
   p_cfg->mtu = p_tbl->my_mtu;
   p_cfg->fcr_present = true;
-  memcpy(&p_cfg->fcr, p_opt, sizeof(tL2CAP_FCR_OPTS));
+  if (p_opt != NULL)
+    memcpy(&p_cfg->fcr, p_opt, sizeof(tL2CAP_FCR_OPTS));
   if (fcs & MCA_FCS_PRESNT_MASK) {
     p_cfg->fcs_present = true;
     p_cfg->fcs = (fcs & MCA_FCS_USE_MASK);
@@ -292,7 +293,9 @@
   /* if control channel, notify ccb that channel close */
   if (p_tbl->tcid == MCA_CTRL_TCID) {
     p_ccb = mca_ccb_by_hdl((tMCA_CL)p_tbl->cb_idx);
-    mca_ccb_event(p_ccb, MCA_CCB_LL_CLOSE_EVT, (tMCA_CCB_EVT*)&close);
+    if(p_ccb != NULL) {
+      mca_ccb_event(p_ccb, MCA_CCB_LL_CLOSE_EVT, (tMCA_CCB_EVT *)&close);
+    }
   }
   /* notify dcb that channel close */
   else {
@@ -337,8 +340,9 @@
   /* if control channel, notify ccb that channel open */
   if (p_tbl->tcid == MCA_CTRL_TCID) {
     p_ccb = mca_ccb_by_hdl((tMCA_CL)p_tbl->cb_idx);
-
-    mca_ccb_event(p_ccb, MCA_CCB_LL_OPEN_EVT, (tMCA_CCB_EVT*)&open);
+    if(p_ccb != NULL) {
+      mca_ccb_event(p_ccb, MCA_CCB_LL_OPEN_EVT, (tMCA_CCB_EVT *)&open);
+    }
   }
   /* must be data channel, notify dcb that channel open */
   else {
@@ -376,7 +380,9 @@
   /* if control channel, notify ccb of congestion */
   if (p_tbl->tcid == MCA_CTRL_TCID) {
     p_ccb = mca_ccb_by_hdl((tMCA_CL)p_tbl->cb_idx);
-    mca_ccb_event(p_ccb, MCA_CCB_LL_CONG_EVT, (tMCA_CCB_EVT*)&is_congested);
+    if (p_ccb != NULL) {
+      mca_ccb_event(p_ccb, MCA_CCB_LL_CONG_EVT, (tMCA_CCB_EVT *) &is_congested);
+    }
   }
   /* notify dcb that channel open */
   else {
diff --git a/stack/rfcomm/rfc_mx_fsm.cc b/stack/rfcomm/rfc_mx_fsm.cc
index 278458f..24836eb 100644
--- a/stack/rfcomm/rfc_mx_fsm.cc
+++ b/stack/rfcomm/rfc_mx_fsm.cc
@@ -591,7 +591,7 @@
   RFCOMM_TRACE_EVENT("rfc_mx_conf_cnf p_cfg:%08x res:%d ", p_cfg,
                      (p_cfg) ? p_cfg->result : 0);
 
-  if (p_cfg->result != L2CAP_CFG_OK) {
+  if (p_cfg && p_cfg->result != L2CAP_CFG_OK) {
     if (p_mcb->is_initiator) {
       PORT_StartCnf(p_mcb, p_cfg->result);
       L2CA_DisconnectReq(p_mcb->lcid);
diff --git a/stack/rfcomm/rfc_utils.cc b/stack/rfcomm/rfc_utils.cc
index bad58f3..a132026 100644
--- a/stack/rfcomm/rfc_utils.cc
+++ b/stack/rfcomm/rfc_utils.cc
@@ -356,7 +356,7 @@
 void rfc_port_closed(tPORT* p_port) {
   tRFC_MCB* p_mcb = p_port->rfc.p_mcb;
 
-  RFCOMM_TRACE_DEBUG("rfc_port_closed");
+  RFCOMM_TRACE_WARNING("rfc_port_closed");
 
   rfc_port_timer_stop(p_port);
 
@@ -411,6 +411,8 @@
   if (p_port->rfc.p_mcb->flow == PORT_FC_CREDIT) {
     if (p_port->credit_tx > 0) p_port->credit_tx--;
 
+        RFCOMM_TRACE_EVENT ("rfc_dec_credit:%d", p_port->credit_tx);
+
     if (p_port->credit_tx == 0) p_port->tx.peer_fc = true;
   }
 }
diff --git a/stack/sdp/sdp_discovery.cc b/stack/sdp/sdp_discovery.cc
index 1c0961d..d95e20d 100644
--- a/stack/sdp/sdp_discovery.cc
+++ b/stack/sdp/sdp_discovery.cc
@@ -88,9 +88,11 @@
     } else if (p_uuid_list->len == 4) {
       UINT8_TO_BE_STREAM(p_out, (UUID_DESC_TYPE << 3) | SIZE_FOUR_BYTES);
       UINT32_TO_BE_STREAM(p_out, p_uuid_list->uu.uuid32);
-    } else {
+    } else if (p_uuid_list->len == 16) {
       UINT8_TO_BE_STREAM(p_out, (UUID_DESC_TYPE << 3) | SIZE_SIXTEEN_BYTES);
       ARRAY_TO_BE_STREAM(p_out, p_uuid_list->uu.uuid128, p_uuid_list->len);
+    } else {
+      SDP_TRACE_ERROR("SDP: Passed Uuid is of Invalid length: %x",p_uuid_list->len);
     }
   }
 
diff --git a/stack/sdp/sdp_server.cc b/stack/sdp/sdp_server.cc
index c665711..966ecdd 100644
--- a/stack/sdp/sdp_server.cc
+++ b/stack/sdp/sdp_server.cc
@@ -30,6 +30,7 @@
 #include "bt_common.h"
 #include "bt_types.h"
 #include "bt_utils.h"
+#include "bt_trace.h"
 #include "btu.h"
 
 #include "hcidefs.h"
@@ -224,9 +225,17 @@
       return;
     }
 
+    if (p_req != p_req_end) {
+      sdpu_build_n_send_error (p_ccb, trans_num, SDP_INVALID_PDU_SIZE, SDP_TEXT_BAD_HEADER);
+      return;
+    }
     rem_handles =
         num_rsp_handles - cont_offset; /* extract the remaining handles */
   } else {
+    if (p_req+1 != p_req_end) {
+      sdpu_build_n_send_error (p_ccb, trans_num, SDP_INVALID_PDU_SIZE, SDP_TEXT_BAD_HEADER);
+      return;
+    }
     rem_handles = num_rsp_handles;
     cont_offset = 0;
     p_ccb->cont_offset = 0;
@@ -361,6 +370,10 @@
                               SDP_TEXT_BAD_CONT_INX);
       return;
     }
+    if (p_req != p_req_end) {
+      sdpu_build_n_send_error (p_ccb, trans_num, SDP_INVALID_PDU_SIZE, SDP_TEXT_BAD_HEADER);
+      return;
+    }
     is_cont = true;
 
     /* Initialise for continuation response */
@@ -368,6 +381,11 @@
     attr_seq.attr_entry[p_ccb->cont_info.next_attr_index].start =
         p_ccb->cont_info.next_attr_start_id;
   } else {
+    if (p_req+1 != p_req_end) {
+      sdpu_build_n_send_error (p_ccb, trans_num, SDP_INVALID_PDU_SIZE, SDP_TEXT_BAD_HEADER);
+      return;
+    }
+
     p_ccb->cont_offset = 0;
     p_rsp = &p_ccb->rsp_list[3]; /* Leave space for data elem descr */
 
@@ -526,7 +544,7 @@
   tSDP_ATTR_SEQ attr_seq, attr_seq_sav;
   tSDP_ATTRIBUTE* p_attr;
   bool maxxed_out = false, is_cont = false;
-  uint8_t* p_seq_start;
+  uint8_t* p_seq_start = NULL;
   uint16_t seq_len, attr_len;
 
   /* Extract the UUID sequence to search for */
@@ -572,6 +590,10 @@
                               SDP_TEXT_BAD_CONT_INX);
       return;
     }
+    if (p_req != p_req_end) {
+      sdpu_build_n_send_error (p_ccb, trans_num, SDP_INVALID_PDU_SIZE, SDP_TEXT_BAD_HEADER);
+      return;
+    }
     is_cont = true;
 
     /* Initialise for continuation response */
@@ -579,6 +601,10 @@
     attr_seq.attr_entry[p_ccb->cont_info.next_attr_index].start =
         p_ccb->cont_info.next_attr_start_id;
   } else {
+    if (p_req+1 != p_req_end) {
+      sdpu_build_n_send_error (p_ccb, trans_num, SDP_INVALID_PDU_SIZE, SDP_TEXT_BAD_HEADER);
+      return;
+    }
     p_ccb->cont_offset = 0;
     p_rsp = &p_ccb->rsp_list[3]; /* Leave space for data elem descr */
 
@@ -674,9 +700,13 @@
     if (p_ccb->cont_info.last_attr_seq_desc_sent == false) {
       seq_len = sdpu_get_attrib_seq_len(p_rec, &attr_seq_sav);
       if (seq_len != 0) {
+      if (p_seq_start) {
         UINT8_TO_BE_STREAM(p_seq_start,
                            (DATA_ELE_SEQ_DESC_TYPE << 3) | SIZE_IN_NEXT_WORD);
         UINT16_TO_BE_STREAM(p_seq_start, seq_len);
+      } else {
+        SDP_TRACE_DEBUG("SDP service and attribute rsp: Attribute sequence p_seq_start is NULL");
+      }
 
         if (maxxed_out) p_ccb->cont_info.last_attr_seq_desc_sent = true;
       } else
diff --git a/stack/sdp/sdp_utils.cc b/stack/sdp/sdp_utils.cc
index fcd87da..4bb421d 100644
--- a/stack/sdp/sdp_utils.cc
+++ b/stack/sdp/sdp_utils.cc
@@ -231,6 +231,8 @@
  *
  ******************************************************************************/
 uint8_t* sdpu_build_attrib_entry(uint8_t* p_out, tSDP_ATTRIBUTE* p_attr) {
+  if(!p_out)
+    return p_out;
   /* First, store the attribute ID. Goes as a UINT */
   UINT8_TO_BE_STREAM(p_out, (UINT_DESC_TYPE << 3) | SIZE_TWO_BYTES);
   UINT16_TO_BE_STREAM(p_out, p_attr->id);
@@ -925,10 +927,12 @@
 
   size_t len_to_copy =
       ((attr_len - *offset) < len) ? (attr_len - *offset) : len;
-  memcpy(p_out, &p_attr_buff[*offset], len_to_copy);
+  if(p_out) {
+    memcpy(p_out, &p_attr_buff[*offset], len_to_copy);
 
-  p_out = &p_out[len_to_copy];
-  *offset += len_to_copy;
+    p_out = &p_out[len_to_copy];
+    *offset += len_to_copy;
+  }
 
   osi_free(p_attr_buff);
   return p_out;
diff --git a/stack/smp/smp_cmac.cc b/stack/smp/smp_cmac.cc
index 876c420..812cb0e 100644
--- a/stack/smp/smp_cmac.cc
+++ b/stack/smp/smp_cmac.cc
@@ -126,7 +126,7 @@
   tSMP_ENC output;
   uint8_t i = 1, err = 0;
   uint8_t x[16] = {0};
-  uint8_t* p_mac;
+  uint8_t* p_mac = NULL;
 
   SMP_TRACE_EVENT("cmac_aes_k_calculate ");
 
@@ -146,6 +146,8 @@
   }
 
   if (!err) {
+    if (tlen > BT_OCTET16_LEN)
+      tlen = BT_OCTET16_LEN;
     p_mac = output.param_buf + (BT_OCTET16_LEN - tlen);
     memcpy(p_signature, p_mac, tlen);
 
diff --git a/stack/smp/smp_main.cc b/stack/smp/smp_main.cc
index 829a5d4..62c1000 100644
--- a/stack/smp/smp_main.cc
+++ b/stack/smp/smp_main.cc
@@ -996,7 +996,7 @@
   /* execute action functions */
   for (i = 0; i < SMP_NUM_ACTIONS; i++) {
     action = state_table[entry - 1][i];
-    if (action != SMP_SM_NO_ACTION) {
+    if (action < SMP_SM_NO_ACTION) {
       (*smp_sm_action[action])(p_cb, (tSMP_INT_DATA*)p_data);
     } else {
       break;
@@ -1025,7 +1025,7 @@
 const char* smp_get_event_name(tSMP_EVENT event) {
   const char* p_str = smp_event_name[SMP_MAX_EVT];
 
-  if (event <= SMP_MAX_EVT) {
+  if (event && event <= SMP_MAX_EVT) {
     p_str = smp_event_name[event - 1];
   }
   return p_str;
diff --git a/stack/srvc/srvc_battery.cc b/stack/srvc/srvc_battery.cc
index 7600f9d..bc28045 100644
--- a/stack/srvc/srvc_battery.cc
+++ b/stack/srvc/srvc_battery.cc
@@ -176,7 +176,7 @@
   tGATT_STATUS status = GATT_ERROR;
   tBA_INST* p_inst;
 
-  if (battery_cb.inst_id == BA_MAX_INT_NUM) {
+  if (battery_cb.inst_id >= BA_MAX_INT_NUM) {
     GATT_TRACE_ERROR("MAX battery service has been reached");
     return 0;
   }
diff --git a/stack/srvc/srvc_eng.cc b/stack/srvc/srvc_eng.cc
index 568b66e..2ff383f 100644
--- a/stack/srvc/srvc_eng.cc
+++ b/stack/srvc/srvc_eng.cc
@@ -258,6 +258,11 @@
   tGATTS_RSP rsp_msg;
   uint8_t act = SRVC_ACT_IGNORE;
   uint8_t clcb_idx = srvc_eng_find_clcb_idx_by_conn_id(conn_id);
+  if( clcb_idx == SRVC_MAX_APPS)
+  {
+    GATT_TRACE_ERROR("srvc_eng_s_request_cback received for unknown connection");
+    return;
+  }
 
   GATT_TRACE_EVENT("srvc_eng_s_request_cback : recv type (0x%02x)", type);
 
diff --git a/utils/src/bt_utils.cc b/utils/src/bt_utils.cc
index 356fa75..84f58c2 100644
--- a/utils/src/bt_utils.cc
+++ b/utils/src/bt_utils.cc
@@ -141,7 +141,7 @@
 #else   // !defined(OS_GENERIC)
     pthread_once(&g_DoSchedulingGroupOnce[g_TaskIdx],
                  check_do_scheduling_group);
-    if (g_DoSchedulingGroup[g_TaskIdx]) {
+    if (g_TaskIdx < TASK_HIGH_MAX && g_DoSchedulingGroup[g_TaskIdx]) {
       // set_sched_policy does not support tid == 0
       rc = set_sched_policy(tid, SP_AUDIO_SYS);
     }