surfaceflinger: fix a potential child layer leak

We should not remove a child layer from its already removed parent.
Call p->removeChild only after we've checked that the ancestor is
alive.

Apply e6b63e1ae12692327f7e46d5f10d6ade5a7bf192 and this fix to
SurfaceFlinger_hwc1.cpp as well.

Bug: 37121786
Test: manual stress test
Change-Id: I7b811450a998acc4ad9690bd4eda058ce6588e14
diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp
index 6174185..29e7bd6 100644
--- a/services/surfaceflinger/SurfaceFlinger.cpp
+++ b/services/surfaceflinger/SurfaceFlinger.cpp
@@ -2689,8 +2689,6 @@
             return NO_ERROR;
         }
 
-        index = p->removeChild(layer);
-
         sp<Layer> ancestor = p;
         while (ancestor->getParent() != nullptr) {
             ancestor = ancestor->getParent();
@@ -2699,6 +2697,8 @@
             ALOGE("removeLayer called with a layer whose parent has been removed");
             return NAME_NOT_FOUND;
         }
+
+        index = p->removeChild(layer);
     } else {
         index = mCurrentState.layersSortedByZ.remove(layer);
     }