SF: Fix tracing layerhandle to layerid map

Fixes an issue where the layer handle would be
added after it was used in a transaction by adding
the handle before constructing the create layer
transaction in SF.

Fixes an issue where the layer handle pointer
could be reused by a new handle by updating
the map when the handle is destroyed.

Test: presubmit
Bug: 200284593
Change-Id: Ia163e456500fc909bcda6e97dd8c7efa4be50c9e
diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp
index 0840241..9584592 100644
--- a/services/surfaceflinger/SurfaceFlinger.cpp
+++ b/services/surfaceflinger/SurfaceFlinger.cpp
@@ -4422,10 +4422,6 @@
     if (parentLayer != nullptr) {
         addToRoot = false;
     }
-    result = addClientLayer(args.client, *outHandle, layer, parent, addToRoot, outTransformHint);
-    if (result != NO_ERROR) {
-        return result;
-    }
 
     int parentId = -1;
     // We can safely promote the layer in binder thread because we have a strong reference
@@ -4439,6 +4435,11 @@
                                          args.flags, parentId);
     }
 
+    result = addClientLayer(args.client, *outHandle, layer, parent, addToRoot, outTransformHint);
+    if (result != NO_ERROR) {
+        return result;
+    }
+
     setTransactionFlags(eTransactionNeeded);
     *outLayerId = layer->sequence;
     return result;
@@ -4521,6 +4522,9 @@
     markLayerPendingRemovalLocked(layer);
     mBufferCountTracker.remove(handle);
     layer.clear();
+    if (mTransactionTracingEnabled) {
+        mTransactionTracing.onHandleRemoved(handle);
+    }
 }
 
 // ---------------------------------------------------------------------------