Merge cherrypicks of [6072697, 6072075, 6072758, 6072124, 6072885, 6072886, 6072887, 6072580, 6072581, 6072582, 6072583, 6072584, 6072132, 6072195, 6072133, 6072077, 6072134, 6072078, 6072211, 6072762, 6072763, 6072908, 6072909, 6072910, 6072911, 6072912, 6072913, 6072914, 6072930, 6072212, 6072743] into pi-qpr2-release

Change-Id: Id793360e2640b37b6708c97596bc27929320e1ff
diff --git a/stack/l2cap/l2c_fcr.cc b/stack/l2cap/l2c_fcr.cc
index 8326e4d..88503fb 100644
--- a/stack/l2cap/l2c_fcr.cc
+++ b/stack/l2cap/l2c_fcr.cc
@@ -833,7 +833,16 @@
   }
 
   if (p_ccb->is_first_seg) {
+    if (p_buf->len < sizeof(sdu_length)) {
+      L2CAP_TRACE_ERROR("%s: buffer length=%d too small. Need at least 2.",
+                        __func__, p_buf->len);
+      android_errorWriteWithInfoLog(0x534e4554, "120665616", -1, NULL, 0);
+      /* Discard the buffer */
+      osi_free(p_buf);
+      return;
+    }
     STREAM_TO_UINT16(sdu_length, p);
+
     /* Check the SDU Length with local MTU size */
     if (sdu_length > p_ccb->local_conn_cfg.mtu) {
       /* Discard the buffer */
@@ -841,6 +850,9 @@
       return;
     }
 
+    p_buf->len -= sizeof(sdu_length);
+    p_buf->offset += sizeof(sdu_length);
+
     if (sdu_length < p_buf->len) {
       L2CAP_TRACE_ERROR("%s: Invalid sdu_length: %d", __func__, sdu_length);
       android_errorWriteWithInfoLog(0x534e4554, "112321180", -1, NULL, 0);
@@ -859,8 +871,6 @@
     p_data->len = 0;
     p_ccb->ble_sdu_length = sdu_length;
     L2CAP_TRACE_DEBUG("%s SDU Length = %d", __func__, sdu_length);
-    p_buf->len -= sizeof(sdu_length);
-    p_buf->offset += sizeof(sdu_length);
     p_data->offset = 0;
 
   } else {