From ac833f7bdd69e638d2e0811c9473e6b44cd10281 Mon Sep 17 00:00:00 2001
From: Thomas Munro <thomas.munro@enterprisedb.com>
Date: Wed, 8 Nov 2017 13:48:23 +1300
Subject: [PATCH] Avoid unlikely File leak.

fd.c previously broke a resowner.c programming rule by acquiring a resource
that was to be managed by resowner.c before ensuring that there was
sufficient space to track the resource.

Author: Thomas Munro, based on comments from Andres Freund on a related patch
---
 src/backend/storage/file/fd.c | 8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)

diff --git a/src/backend/storage/file/fd.c b/src/backend/storage/file/fd.c
index b0c174284b4..131587a70b0 100644
--- a/src/backend/storage/file/fd.c
+++ b/src/backend/storage/file/fd.c
@@ -1397,6 +1397,13 @@ OpenTemporaryFile(bool interXact)
 {
 	File		file = 0;
 
+	/*
+	 * Make sure the current resource owner has space for this File before
+	 * we open it, if we'll be registering it below.
+	 */
+	if (!interXact)
+		ResourceOwnerEnlargeFiles(CurrentResourceOwner);
+
 	/*
 	 * If some temp tablespace(s) have been given to us, try to use the next
 	 * one.  If a given tablespace can't be found, we silently fall back to
@@ -1433,7 +1440,6 @@ OpenTemporaryFile(bool interXact)
 	{
 		VfdCache[file].fdstate |= FD_XACT_TEMPORARY;
 
-		ResourceOwnerEnlargeFiles(CurrentResourceOwner);
 		ResourceOwnerRememberFile(CurrentResourceOwner, file);
 		VfdCache[file].resowner = CurrentResourceOwner;
 
-- 
2.14.1

