Merge cherrypicks of ['googleplex-android-review.googlesource.com/42592346'] into 26Q4-release.

Change-Id: Ibc268118d5369a370190f907e4427b9145ed0408
diff --git a/libs/gui/Surface.cpp b/libs/gui/Surface.cpp
index a8ad5a2..4f972b5 100644
--- a/libs/gui/Surface.cpp
+++ b/libs/gui/Surface.cpp
@@ -635,9 +635,9 @@
         }
     }
 
-    sp<GraphicBuffer> graphicBuffer;
-    status_t result = c->dequeueBuffer(&graphicBuffer, fenceFd);
-    *buffer = graphicBuffer.get();
+    GraphicBuffer* graphicBuffer = nullptr;
+    status_t result = c->dequeueBufferForANativeWindow(&graphicBuffer, fenceFd);
+    *buffer = graphicBuffer;
     return result;
 }
 
@@ -645,9 +645,9 @@
                                    int* fenceFd) {
     Surface* c = getSelf(window);
 
-    sp<GraphicBuffer> graphicBuffer;
-    status_t result = c->dequeueBuffer(&graphicBuffer, fenceFd);
-    *buffer = graphicBuffer.get();
+    GraphicBuffer* graphicBuffer = nullptr;
+    status_t result = c->dequeueBufferForANativeWindow(&graphicBuffer, fenceFd);
+    *buffer = graphicBuffer;
     return result;
 }
 
@@ -693,9 +693,9 @@
 int Surface::hook_dequeueBuffer_DEPRECATED(ANativeWindow* window,
         ANativeWindowBuffer** buffer) {
     Surface* c = getSelf(window);
-    sp<GraphicBuffer> buf;
+    GraphicBuffer* buf = nullptr;
     int fenceFd = -1;
-    int result = c->dequeueBuffer(&buf, &fenceFd);
+    int result = c->dequeueBufferForANativeWindow(&buf, &fenceFd);
     if (result != OK) {
         return result;
     }
@@ -704,10 +704,10 @@
     if (waitResult != OK) {
         ALOGE("dequeueBuffer_DEPRECATED: Fence::wait returned an error: %d",
                 waitResult);
-        c->cancelBuffer(std::move(buf), Fence::NO_FENCE);
+        c->cancelBuffer(GraphicBuffer::from(buf), Fence::NO_FENCE);
         return waitResult;
     }
-    *buffer = buf.get();
+    *buffer = buf;
     return result;
 }
 
@@ -809,7 +809,17 @@
     dequeueInput->getTimestamps = mEnableFrameTimestamps;
 }
 
-int Surface::dequeueBuffer(sp<GraphicBuffer>* buffer, int* fenceFd) {
+int Surface::dequeueBufferForANativeWindow(GraphicBuffer** outBuffer, int* fenceFd) {
+    sp<GraphicBuffer> buffer;
+    int result = dequeueBufferImpl(&buffer, fenceFd, /*callerOwnsReference=*/false);
+    if (result == NO_ERROR) {
+        // The slot keeps a strong reference until the buffer is returned to the Surface.
+        *outBuffer = buffer.get();
+    }
+    return result;
+}
+
+int Surface::dequeueBufferImpl(sp<GraphicBuffer>* buffer, int* fenceFd, bool callerOwnsReference) {
     {
         std::scoped_lock _dl(mDebugMutex);
         ATRACE_FORMAT("dequeueBuffer - %s", mDebugName.c_str());
@@ -926,6 +936,7 @@
 
     mQueueInProgressSlots.erase(buf);
     mDequeuedSlots.insert(buf);
+    mSlots[buf].callerOwnsReference = callerOwnsReference;
 
     return OK;
 }
@@ -937,7 +948,9 @@
 
     sp<GraphicBuffer> tmpBuffer;
     int fd = -1;
-    status_t res = dequeueBuffer(&tmpBuffer, &fd);
+    // The caller receives an sp<GraphicBuffer>, so it owns a reference and the Surface does not
+    // need to keep the buffer alive across a disconnect (b/555458155).
+    status_t res = dequeueBufferImpl(&tmpBuffer, &fd, /*callerOwnsReference=*/true);
     if (res != NO_ERROR) {
         SURF_LOGV("dequeueBuffer() returned %d", res);
         return res;
@@ -955,12 +968,14 @@
 
     Mutex::Autolock lock(mMutex);
 
+    bool outstandingAtDisconnect = takeDisconnectedOwnedBufferLocked(buffer);
     if (mLeakedBuffers.contains(buffer)) {
         SURF_LOGE("Surface::detachBuffer given a leaked buffer! Deleting extra held reference.");
         mLeakedBuffers.erase(buffer);
-        if (!mIsConnected) {
-            return OK;
-        }
+        outstandingAtDisconnect = true;
+    }
+    if (outstandingAtDisconnect && !mIsConnected) {
+        return OK;
     }
 
     uint64_t bufferId = buffer->getId();
@@ -1179,6 +1194,7 @@
         buffers->at(batchIdx).buffer = gbuf.get();
         mQueueInProgressSlots.erase(slot);
         mDequeuedSlots.insert(slot);
+        mSlots[slot].callerOwnsReference = false;
     }
     return OK;
 }
@@ -1188,12 +1204,14 @@
     SURF_LOGV("Surface::cancelBuffer");
     Mutex::Autolock lock(mMutex);
 
+    bool outstandingAtDisconnect = takeDisconnectedOwnedBufferLocked(buffer);
     if (mLeakedBuffers.contains(buffer)) {
         SURF_LOGE("Surface::cancelBuffer given a leaked buffer! Deleting extra held reference.");
         mLeakedBuffers.erase(buffer);
-        if (!mIsConnected) {
-            return OK;
-        }
+        outstandingAtDisconnect = true;
+    }
+    if (outstandingAtDisconnect && !mIsConnected) {
+        return OK;
     }
 
     int i = getSlotFromBufferLocked(buffer);
@@ -1233,18 +1251,23 @@
     {
         Mutex::Autolock _l(mMutex);
 
+        bool outstandingAtDisconnect = false;
         for (auto& batchBuffer : buffers) {
             auto buffer = GraphicBuffer::from(batchBuffer.buffer);
+            if (takeDisconnectedOwnedBufferLocked(buffer)) {
+                outstandingAtDisconnect = true;
+            }
             if (mLeakedBuffers.contains(buffer)) {
                 SURF_LOGE("Surface::cancelBuffers given a leaked buffer! Deleting extra held "
                           "reference.");
                 mLeakedBuffers.erase(buffer);
+                outstandingAtDisconnect = true;
                 // Hold onto one last reference to the buffer until the end of the scope of this
                 // function in the rare case that it still needs to be sent to the client.
                 deletedLeakedBuffers.push_back(std::move(buffer));
             }
         }
-        if (!mIsConnected && !deletedLeakedBuffers.empty()) {
+        if (!mIsConnected && outstandingAtDisconnect) {
             return OK;
         }
 
@@ -1432,12 +1455,14 @@
     {
         Mutex::Autolock lock(mMutex);
 
+        bool outstandingAtDisconnect = takeDisconnectedOwnedBufferLocked(buffer);
         if (mLeakedBuffers.contains(buffer)) {
             SURF_LOGE("Surface::queueBuffer given a leaked buffer! Deleting extra held reference.");
             mLeakedBuffers.erase(buffer);
-            if (!mIsConnected) {
-                return OK;
-            }
+            outstandingAtDisconnect = true;
+        }
+        if (outstandingAtDisconnect && !mIsConnected) {
+            return OK;
         }
 
         slot = getSlotFromBufferLocked(buffer);
@@ -1616,18 +1641,23 @@
     {
         Mutex::Autolock lock(mMutex);
 
+        bool outstandingAtDisconnect = false;
         for (auto& batchBuffer : buffers) {
             auto buffer = GraphicBuffer::from(batchBuffer.buffer);
+            if (takeDisconnectedOwnedBufferLocked(buffer)) {
+                outstandingAtDisconnect = true;
+            }
             if (mLeakedBuffers.contains(buffer)) {
                 SURF_LOGE("Surface::queueBuffers given a leaked buffer! Deleting extra held "
                           "reference.");
                 mLeakedBuffers.erase(buffer);
+                outstandingAtDisconnect = true;
                 // Hold onto one last reference to the buffer until the end of the scope of this
                 // function in the rare case that it still needs to be sent to the client.
                 deletedLeakedBuffers.push_back(std::move(buffer));
             }
         }
-        if (!mIsConnected && !deletedLeakedBuffers.empty()) {
+        if (!mIsConnected && outstandingAtDisconnect) {
             return OK;
         }
 
@@ -2737,6 +2767,7 @@
         mRemovedBuffers.push_back(mSlots[attachedSlot].buffer);
     }
     mSlots[attachedSlot].buffer = graphicBuffer;
+    mSlots[attachedSlot].callerOwnsReference = false;
     mDequeuedSlots.insert(attachedSlot);
 
     return NO_ERROR;
@@ -3073,16 +3104,27 @@
                   __FUNCTION__, mDequeuedSlots.size(), mQueueInProgressSlots.size());
     }
     for (int i = 0; i < (int)mSlots.size(); i++) {
-        // Since we're ANW contractually oblicates us to be responsible for a reference to a
-        // dequeued buffer, hold onto a reference to the buffer even though we're disconnecting.
-        // This is especially important in the case of when some client is using ANW and someone
-        // else, having a reference to the Surface, disconnects it.
         if (mDequeuedSlots.contains(i) || mQueueInProgressSlots.contains(i)) {
-            mLeakedBuffers.insert(mSlots[i].buffer);
+            if (mSlots[i].callerOwnsReference) {
+                // The buffer was handed out as an sp<GraphicBuffer>, so the caller keeps it alive.
+                // Holding another reference here would only leak the buffer if the Surface is
+                // reused and the caller never returns it (b/555458155). Remember its ID so a late
+                // queue/cancel/detach is still accepted, as it is for mLeakedBuffers.
+                if (mSlots[i].buffer != nullptr) {
+                    mDisconnectedOwnedBufferIds.insert(mSlots[i].buffer->getId());
+                }
+            } else {
+                // The ANativeWindow contract obligates us to be responsible for a reference to a
+                // dequeued buffer, so hold onto a reference to the buffer even though we're
+                // disconnecting. This is especially important in the case of when some client is
+                // using ANW and someone else, having a reference to the Surface, disconnects it.
+                mLeakedBuffers.insert(mSlots[i].buffer);
+            }
         }
         mSlots[i].buffer = nullptr;
         mSlots[i].dirtyRegion.clear();
         mSlots[i].requiresFreeOnReturn = false;
+        mSlots[i].callerOwnsReference = false;
     }
     mDequeuedSlots.clear();
     mQueueInProgressSlots.clear();
@@ -3092,6 +3134,13 @@
     }
 }
 
+bool Surface::takeDisconnectedOwnedBufferLocked(const sp<GraphicBuffer>& buffer) {
+    if (buffer == nullptr || mDisconnectedOwnedBufferIds.empty()) {
+        return false;
+    }
+    return mDisconnectedOwnedBufferIds.erase(buffer->getId()) > 0;
+}
+
 status_t Surface::getAndFlushBuffersFromSlots(const std::vector<int32_t>& slots,
                                               std::vector<sp<GraphicBuffer>>* outBuffers) {
     SURF_LOGV("Surface::getAndFlushBuffersFromSlots");
@@ -3222,10 +3271,12 @@
     setUsage(GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
              (mIsForCursor ? GRALLOC_USAGE_CURSOR : 0));
 
-    sp<GraphicBuffer> backBuffer;
+    GraphicBuffer* rawBackBuffer = nullptr;
     int fenceFd = -1;
-    status_t err = dequeueBuffer(&backBuffer, &fenceFd);
+    status_t err = dequeueBufferForANativeWindow(&rawBackBuffer, &fenceFd);
     SURF_LOGE_IF(err, "dequeueBuffer failed (%s)", strerror(-err));
+    // Safe to re-wrap: the slot holds a strong reference while the buffer is dequeued.
+    sp<GraphicBuffer> backBuffer = GraphicBuffer::from(rawBackBuffer);
     if (err == NO_ERROR) {
         const Rect bounds(backBuffer->width, backBuffer->height);
 
diff --git a/libs/gui/include/gui/Surface.h b/libs/gui/include/gui/Surface.h
index 49e7255..f441796 100644
--- a/libs/gui/include/gui/Surface.h
+++ b/libs/gui/include/gui/Surface.h
@@ -501,7 +501,11 @@
     int dispatchIsProducerThrottlingEnabled(va_list args);
 
 protected:
-    virtual int dequeueBuffer(sp<GraphicBuffer>* buffer, int* fenceFd);
+    // ANativeWindow entry point. The caller only receives a raw pointer, so the Surface keeps the
+    // buffer alive (in its slot, or in mLeakedBuffers after a disconnect) until it is queued,
+    // cancelled or detached. Callers that want to own the reference use
+    // dequeueBuffer(sp<GraphicBuffer>*, sp<Fence>*).
+    virtual int dequeueBufferForANativeWindow(GraphicBuffer** outBuffer, int* fenceFd);
     virtual int perform(int operation, va_list args);
     virtual int setSwapInterval(int interval);
 
@@ -689,6 +693,17 @@
                              const SurfaceQueueBufferInput* maybeInput,
                              SurfaceQueueBufferOutput* output) EXCLUDES(mMutex);
 
+    // Shared implementation of the ANativeWindow and sp<GraphicBuffer> dequeue entry points.
+    // |callerOwnsReference| is recorded on the slot, under mMutex, together with marking the slot
+    // dequeued. See BufferSlot::callerOwnsReference.
+    int dequeueBufferImpl(sp<GraphicBuffer>* buffer, int* fenceFd, bool callerOwnsReference)
+            EXCLUDES(mMutex);
+
+    // Called from the post-disconnect early-out in queue/cancel/detach. Returns true if |buffer|
+    // was dequeued through the sp<GraphicBuffer> API and was still outstanding when the Surface
+    // disconnected, and forgets it.
+    bool takeDisconnectedOwnedBufferLocked(const sp<GraphicBuffer>& buffer) REQUIRES(mMutex);
+
     // For easing in adoption of gralloc4 metadata by vendor components, as well as for supporting
     // the public ANativeWindow api, allow setting relevant metadata when queueing a buffer through
     // a native window
@@ -706,6 +721,10 @@
         // This buffer/slot was dequeued when the underlying IGBP sent a RELEASE_ALL_BUFFERS flag,
         // and we must release this buffer on detach/cancel/queue.
         bool requiresFreeOnReturn = false;
+        // The buffer was handed out through the sp<GraphicBuffer> API, so the caller owns a strong
+        // reference and the Surface does not need to keep one across a disconnect. False for the
+        // ANativeWindow hooks, batch dequeue and attach, which give the caller a raw pointer.
+        bool callerOwnsReference = false;
     };
 
     // mSurfaceTexture is the interface to the surface texture server. All
@@ -742,6 +761,13 @@
     // given back to the Surface via queue or cancel.
     std::unordered_set<sp<GraphicBuffer>, BufferHash> mLeakedBuffers;
 
+    // IDs of buffers that were dequeued through the sp<GraphicBuffer> API and were still
+    // outstanding at the time of a disconnection. The caller owns a reference to these, so the
+    // Surface does not keep one (see BufferSlot::callerOwnsReference), but it still needs to
+    // recognize them when they are queued/cancelled/detached after the disconnect so that those
+    // calls behave the same way as for mLeakedBuffers.
+    std::unordered_set<uint64_t> mDisconnectedOwnedBufferIds;
+
     // mReqWidth is the buffer width that will be requested at the next dequeue
     // operation. It is initialized to 1.
     uint32_t mReqWidth;
diff --git a/libs/gui/tests/Surface_test.cpp b/libs/gui/tests/Surface_test.cpp
index 272d123..b8ca8ec 100644
--- a/libs/gui/tests/Surface_test.cpp
+++ b/libs/gui/tests/Surface_test.cpp
@@ -3219,6 +3219,76 @@
     ASSERT_EQ(nullptr, wpBufferA.promote());
 }
 
+TEST_F(SurfaceTest, DisconnectWhileDequeued_SpApiBufferIsNotRetained) {
+    auto [consumer, surface] = BufferItemConsumer::create(GRALLOC_USAGE_SW_READ_OFTEN);
+    ASSERT_EQ(OK, surface->connect(NATIVE_WINDOW_API_CPU, sp<StubSurfaceListener>::make(), false));
+
+    // Dequeue through the sp<GraphicBuffer> API. The caller owns a reference, so the Surface
+    // must not keep the buffer alive on its behalf once disconnected (b/555458155).
+    sp<GraphicBuffer> buffer;
+    sp<Fence> fence;
+    ASSERT_EQ(OK, surface->dequeueBuffer(&buffer, &fence));
+    wp<GraphicBuffer> wpBuffer = buffer;
+
+    ASSERT_EQ(OK, surface->disconnect(NATIVE_WINDOW_API_CPU));
+    ASSERT_NE(nullptr, wpBuffer.promote()) << "The caller's reference keeps the buffer alive.";
+
+    buffer.clear();
+    ASSERT_EQ(nullptr, wpBuffer.promote())
+            << "Dropping the caller's reference after a disconnect must free the buffer; the "
+               "Surface must not hold an extra reference to an sp<GraphicBuffer>-API buffer.";
+}
+
+TEST_F(SurfaceTest, DisconnectWhileDequeued_SpApiBufferCanBeReturnedAfterDisconnect) {
+    auto [consumer, surface] = BufferItemConsumer::create(GRALLOC_USAGE_SW_READ_OFTEN);
+    ASSERT_EQ(OK, surface->connect(NATIVE_WINDOW_API_CPU, sp<StubSurfaceListener>::make(), false));
+    ASSERT_EQ(OK, surface->setMaxDequeuedBufferCount(3));
+
+    sp<GraphicBuffer> buffers[3];
+    sp<Fence> fences[3];
+    for (int i = 0; i < 3; ++i) {
+        ASSERT_EQ(OK, surface->dequeueBuffer(&buffers[i], &fences[i]));
+    }
+
+    ASSERT_EQ(OK, surface->disconnect(NATIVE_WINDOW_API_CPU));
+
+    // A client that returns its buffers after the disconnect (e.g. an asynchronous codec
+    // release) must see the same result as for a buffer retained in the leaked set: OK.
+    EXPECT_EQ(OK, surface->cancelBuffer(buffers[0], fences[0]));
+    EXPECT_EQ(OK, surface->queueBuffer(buffers[1], fences[1]));
+    EXPECT_EQ(OK, surface->detachBuffer(buffers[2]));
+
+    // Once returned, the buffer is no longer known to the Surface.
+    EXPECT_EQ(BAD_VALUE, surface->cancelBuffer(buffers[0], fences[0]));
+
+    wp<GraphicBuffer> wpBuffer = buffers[0];
+    buffers[0].clear();
+    EXPECT_EQ(nullptr, wpBuffer.promote());
+}
+
+TEST_F(SurfaceTest, DisconnectWhileDequeued_SpApiBufferIsRejectedAfterReconnect) {
+    auto [consumer, surface] = BufferItemConsumer::create(GRALLOC_USAGE_SW_READ_OFTEN);
+
+    // Client A connects, dequeues through the sp API, and disconnects without returning.
+    ASSERT_EQ(OK, surface->connect(NATIVE_WINDOW_API_CPU, sp<StubSurfaceListener>::make(), false));
+    sp<GraphicBuffer> bufferA;
+    sp<Fence> fenceA;
+    ASSERT_EQ(OK, surface->dequeueBuffer(&bufferA, &fenceA));
+    ASSERT_EQ(OK, surface->disconnect(NATIVE_WINDOW_API_CPU));
+
+    // Client B connects and dequeues.
+    ASSERT_EQ(OK, surface->connect(NATIVE_WINDOW_API_CPU, sp<StubSurfaceListener>::make(), false));
+    sp<GraphicBuffer> bufferB;
+    sp<Fence> fenceB;
+    ASSERT_EQ(OK, surface->dequeueBuffer(&bufferB, &fenceB));
+    ASSERT_NE(bufferA, bufferB);
+
+    // Same as for ANW-leaked buffers: returning A's buffer on the reconnected Surface is an
+    // invalid operation, and B is unaffected.
+    EXPECT_NE(OK, surface->cancelBuffer(bufferA, fenceA));
+    EXPECT_EQ(OK, surface->cancelBuffer(bufferB, fenceB));
+}
+
 TEST_F(SurfaceTest, Detach_BufferIsNotLeaked) {
     auto [consumer, surface] = BufferItemConsumer::create(GRALLOC_USAGE_SW_READ_OFTEN);