Merge cherrypicks of [13524839, 13524840, 13524841, 13524928, 13524929, 13524930, 13522744, 13524951, 13524860, 13524371, 13524372, 13524373, 13524374, 13524861, 13525166, 13525167, 13525168, 13524843, 13524957, 13524958, 13524936, 13525246, 13524939, 13524940, 13525248, 13524942, 13525249, 13525250, 13525251, 13524943, 13525169, 13525170, 13524358, 13524961, 13524962, 13524963, 13524966, 13524844, 13525325, 13525326, 13524964, 13525327, 13525328, 13524359, 13525307, 13525345] into rvc-qpr2-release

Change-Id: Iae77a22f67cdbb757fb279f406864441ba48b510
diff --git a/src/nfc/tags/rw_mfc.cc b/src/nfc/tags/rw_mfc.cc
index 27797ad..aaa5908 100644
--- a/src/nfc/tags/rw_mfc.cc
+++ b/src/nfc/tags/rw_mfc.cc
@@ -22,6 +22,7 @@
  ******************************************************************************/
 #include <android-base/stringprintf.h>
 #include <base/logging.h>
+#include <log/log.h>
 #include <string.h>
 #include "bt_types.h"
 #include "nfc_target.h"
@@ -997,6 +998,7 @@
   NFC_HDR* mfc_data;
   uint16_t len;
   uint16_t offset;
+  uint16_t saved_length;
   bool failed = false;
   bool done = false;
   tRW_READ_DATA evt_data;
@@ -1018,6 +1020,7 @@
       /* On the first read, adjust for any partial block offset */
       offset = 0;
       len = RW_MFC_1K_BLOCK_SIZE;
+      saved_length = p_mfc->ndef_length;
 
       if (p_mfc->work_offset == 0) {
         /* The Ndef Message offset may be present in the read 16 bytes */
@@ -1029,14 +1032,18 @@
         }
       }
 
-      /* Skip all reserved and lock bytes */
-      while ((offset < len) && (p_mfc->work_offset < p_mfc->ndef_length))
+      if (!failed && saved_length >= p_mfc->ndef_length) {
+        /* Skip all reserved and lock bytes */
+        while ((offset < len) && (p_mfc->work_offset < p_mfc->ndef_length))
 
-      {
-        /* Collect the NDEF Message */
-        p_mfc->p_ndef_buffer[p_mfc->work_offset] = p[offset];
-        p_mfc->work_offset++;
-        offset++;
+        {
+          /* Collect the NDEF Message */
+          p_mfc->p_ndef_buffer[p_mfc->work_offset] = p[offset];
+          p_mfc->work_offset++;
+          offset++;
+        }
+      } else {
+        android_errorWriteLog(0x534e4554, "178725766");
       }
 
       if (p_mfc->work_offset >= p_mfc->ndef_length) {