Merge RQ3A.210705.001 to aosp-master - DO NOT MERGE

Merged-In: I6fc38d4dae7e8ed1eab1510eb6775c42344d0ce5
Merged-In: I422190daf26845f8a9625dd798acb922b3673d68
Merged-In: I422190daf26845f8a9625dd798acb922b3673d68
Change-Id: I004a6beb4e89fe107be73ee4913e687dc44e5fa1
diff --git a/Parcel.cpp b/Parcel.cpp
index 57a99a1..adafaab 100644
--- a/Parcel.cpp
+++ b/Parcel.cpp
@@ -1337,6 +1337,19 @@
                   static_cast<uint64_t>(buffer_obj->parent_offset), parentOffset);
             return false;
         }
+
+        binder_buffer_object *parentBuffer =
+            reinterpret_cast<binder_buffer_object*>(mData + mObjects[parent]);
+        void* bufferInParent = *reinterpret_cast<void**>(
+            reinterpret_cast<uint8_t*>(parentBuffer->buffer) + parentOffset);
+        void* childBuffer = reinterpret_cast<void*>(buffer_obj->buffer);
+
+        if (bufferInParent != childBuffer) {
+              ALOGE("Buffer in parent %p differs from embedded buffer %p",
+                    bufferInParent, childBuffer);
+              android_errorWriteLog(0x534e4554, "179289794");
+              return false;
+        }
     }
 
     return true;
@@ -1422,12 +1435,31 @@
                                                size_t parent_buffer_handle,
                                                size_t parent_offset) const
 {
-    status_t status;
     uint64_t nativeHandleSize;
-    size_t fdaParent;
+    status_t status = readUint64(&nativeHandleSize);
+    if (status != OK) {
+        return BAD_VALUE;
+    }
 
-    status = readUint64(&nativeHandleSize);
-    if (status != OK || nativeHandleSize == 0) {
+    if (nativeHandleSize == 0) {
+        // If !embedded, then parent_* vars are 0 and don't actually correspond
+        // to anything. In that case, we're actually reading this data into
+        // writable memory, and the handle returned from here will actually be
+        // used (rather than be ignored).
+        if (embedded) {
+            binder_buffer_object *parentBuffer =
+                reinterpret_cast<binder_buffer_object*>(mData + mObjects[parent_buffer_handle]);
+
+            void* bufferInParent = *reinterpret_cast<void**>(
+                reinterpret_cast<uint8_t*>(parentBuffer->buffer) + parent_offset);
+
+            if (bufferInParent != nullptr) {
+                  ALOGE("Buffer in (handle) parent %p is not nullptr.", bufferInParent);
+                  android_errorWriteLog(0x534e4554, "179289794");
+                  return BAD_VALUE;
+            }
+        }
+
         *handle = nullptr;
         return status;
     }
@@ -1437,6 +1469,7 @@
         return BAD_VALUE;
     }
 
+    size_t fdaParent;
     if (embedded) {
         status = readNullableEmbeddedBuffer(nativeHandleSize, &fdaParent,
                                             parent_buffer_handle, parent_offset,