Avoid adding to root when parent is destroyed

The move of addToRoot resolution left a behavior change that we now
would allow the layer being added to root if its initial parent is
destroyed between queuing the layer creation transaction and actual
handling of it in the main thread.

Bug: 204204635
Test: atest SurfaceFlinger_test
Test: atest libsurfaceflinger_test
Change-Id: I2f5b30cbe6fc579540a673af22ad41e248ae25c9
diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp
index 48c3c10..cc9e1f8 100644
--- a/services/surfaceflinger/SurfaceFlinger.cpp
+++ b/services/surfaceflinger/SurfaceFlinger.cpp
@@ -6825,14 +6825,16 @@
     }
 
     sp<Layer> parent;
+    bool addToRoot = state->addToRoot;
     if (state->initialParent != nullptr) {
         parent = state->initialParent.promote();
         if (parent == nullptr) {
             ALOGE("Invalid parent %p", state->initialParent.unsafe_get());
+            addToRoot = false;
         }
     }
 
-    if (parent == nullptr && state->addToRoot) {
+    if (parent == nullptr && addToRoot) {
         layer->setIsAtRoot(true);
         mCurrentState.layersSortedByZ.add(layer);
     } else if (parent == nullptr) {