Fix rendering to a destroyed gralloc buffer.

Wait for draw calls that use the Android native image to finish before
dereferencing the buffer and potentially destroying it.

Bug 20885669

Change-Id: I1c8f56e5065ad4c77d7b950feec4505c2e109a47
Reviewed-on: https://swiftshader-review.googlesource.com/3074
Reviewed-by: Greg Hartman <ghartman@google.com>
Tested-by: Greg Hartman <ghartman@google.com>
Reviewed-by: Nicolas Capens <capn@google.com>
diff --git a/src/OpenGL/common/Image.hpp b/src/OpenGL/common/Image.hpp
index 60b0176..fe7d1df 100644
--- a/src/OpenGL/common/Image.hpp
+++ b/src/OpenGL/common/Image.hpp
@@ -183,12 +183,13 @@
 private:

 	ANativeWindowBuffer *nativeBuffer;

 

-	virtual ~AndroidNativeImage() { }

-

-	void setNativeBuffer(ANativeWindowBuffer* buffer)

+	virtual ~AndroidNativeImage()

 	{

-		nativeBuffer = buffer;

-		nativeBuffer->common.incRef(&nativeBuffer->common);

+		// Wait for any draw calls that use this image to finish

+		resource->lock(sw::DESTRUCT);

+		resource->unlock();

+

+		nativeBuffer->common.decRef(&nativeBuffer->common);

 	}

 

 	virtual void *lockInternal(int x, int y, int z, sw::Lock lock, sw::Accessor client)

@@ -255,15 +256,6 @@
 	{

 		GrallocModule::getInstance()->unlock(nativeBuffer->handle);

 	}

-

-	virtual void destroyShared()   // Release a shared image

-	{

-		if(nativeBuffer)

-		{

-			nativeBuffer->common.decRef(&nativeBuffer->common);

-		}

-		egl::Image::destroyShared();

-	}

 };

 

 #endif  // __ANDROID__

diff --git a/src/Renderer/Surface.hpp b/src/Renderer/Surface.hpp
index b0a0669..31d5d6f 100644
--- a/src/Renderer/Surface.hpp
+++ b/src/Renderer/Surface.hpp
@@ -244,6 +244,9 @@
 

 		static void setTexturePalette(unsigned int *palette);

 

+	protected:

+		sw::Resource *resource;

+

 	private:

 		typedef unsigned char byte;

 		typedef unsigned short word;

@@ -365,7 +368,6 @@
 		static unsigned int *palette;   // FIXME: Not multi-device safe

 		static unsigned int paletteID;

 

-		sw::Resource *resource;

 		bool hasParent;

 	};

 }