SurfaceTexture: fix a memory leak

This change fixes an issue where we were sometimes setting the SurfaceTexture's
EGLDisplay to EGL_NO_DISPLAY in detachFromContext, and then subsequently
abandoning the texture.  Abandoning while in the detached state would result in
the eglDestroyImageKHR calls failing, which resulted in a memory leak.

Bug: 6302694
Change-Id: I24c1de0dac029a83c7508075fb8aaeaed96a14ea
diff --git a/libs/gui/SurfaceTexture.cpp b/libs/gui/SurfaceTexture.cpp
index ed1ea4e..a6ee971 100644
--- a/libs/gui/SurfaceTexture.cpp
+++ b/libs/gui/SurfaceTexture.cpp
@@ -344,6 +344,18 @@
         glDeleteTextures(1, &mTexName);
     }
 
+    // Because we're giving up the EGLDisplay we need to free all the EGLImages
+    // that are associated with it.  They'll be recreated when the
+    // SurfaceTexture gets attached to a new OpenGL ES context (and thus gets a
+    // new EGLDisplay).
+    for (int i =0; i < BufferQueue::NUM_BUFFER_SLOTS; i++) {
+        EGLImageKHR img = mEGLSlots[i].mEglImage;
+        if (img != EGL_NO_IMAGE_KHR) {
+            eglDestroyImageKHR(mEglDisplay, img);
+            mEGLSlots[i].mEglImage = EGL_NO_IMAGE_KHR;
+        }
+    }
+
     mEglDisplay = EGL_NO_DISPLAY;
     mEglContext = EGL_NO_CONTEXT;
     mAttached = false;
@@ -668,13 +680,12 @@
     if (slotIndex == mCurrentTexture) {
         mCurrentTexture = BufferQueue::INVALID_BUFFER_SLOT;
     }
-    if (mEGLSlots[slotIndex].mEglImage != EGL_NO_IMAGE_KHR) {
-        EGLImageKHR img = mEGLSlots[slotIndex].mEglImage;
-        if (img != EGL_NO_IMAGE_KHR) {
-            eglDestroyImageKHR(mEglDisplay, img);
-        }
-        mEGLSlots[slotIndex].mEglImage = EGL_NO_IMAGE_KHR;
+    EGLImageKHR img = mEGLSlots[slotIndex].mEglImage;
+    if (img != EGL_NO_IMAGE_KHR) {
+        ST_LOGV("destroying EGLImage dpy=%p img=%p", mEglDisplay, img);
+        eglDestroyImageKHR(mEglDisplay, img);
     }
+    mEGLSlots[slotIndex].mEglImage = EGL_NO_IMAGE_KHR;
 }
 
 void SurfaceTexture::abandon() {