Merge cherrypicks of [8558068, 8558825, 8558826, 8558827, 8557109, 8558018, 8558886, 8558887, 8558888, 8558889, 8558071, 8558072, 8556231] into qt-release

Change-Id: If94b5583cacf7855e75758a6998568eefa39026b
diff --git a/services/surfaceflinger/TransactionCompletedThread.cpp b/services/surfaceflinger/TransactionCompletedThread.cpp
index 5cf8eb1..fd466de 100644
--- a/services/surfaceflinger/TransactionCompletedThread.cpp
+++ b/services/surfaceflinger/TransactionCompletedThread.cpp
@@ -197,8 +197,14 @@
     }
 
     transactionStats->latchTime = handle->latchTime;
-    transactionStats->surfaceStats.emplace_back(handle->surfaceControl, handle->acquireTime,
-                                                handle->previousReleaseFence);
+    // If the layer has already been destroyed, don't add the SurfaceControl to the callback.
+    // The client side keeps a sp<> to the SurfaceControl so if the SurfaceControl has been
+    // destroyed the client side is dead and there won't be anyone to send the callback to.
+    sp<IBinder> surfaceControl = handle->surfaceControl.promote();
+    if (surfaceControl) {
+        transactionStats->surfaceStats.emplace_back(surfaceControl, handle->acquireTime,
+                                                    handle->previousReleaseFence);
+    }
     return NO_ERROR;
 }
 
diff --git a/services/surfaceflinger/TransactionCompletedThread.h b/services/surfaceflinger/TransactionCompletedThread.h
index 21e2678..e849f71 100644
--- a/services/surfaceflinger/TransactionCompletedThread.h
+++ b/services/surfaceflinger/TransactionCompletedThread.h
@@ -49,7 +49,7 @@
 
     sp<ITransactionCompletedListener> listener;
     std::vector<CallbackId> callbackIds;
-    sp<IBinder> surfaceControl;
+    wp<IBinder> surfaceControl;
 
     bool releasePreviousBuffer = false;
     sp<Fence> previousReleaseFence;