From ffb37978ba120522eccf2c0849e46edd94afde67 Mon Sep 17 00:00:00 2001
From: Christian Ullrich <chris@chrullrich.net>
Date: Wed, 16 Nov 2016 16:47:21 +0100
Subject: [PATCH] Do the process environment update first.

This closes a potential race that can happen if a new CRT is loaded while
pgwin32_putenv() is running. Per Noah Misch.
---
 src/port/win32env.c | 64 ++++++++++++++++++++++++++---------------------------
 1 file changed, 32 insertions(+), 32 deletions(-)

diff --git a/src/port/win32env.c b/src/port/win32env.c
index 7bccee6..d6391b0 100644
--- a/src/port/win32env.c
+++ b/src/port/win32env.c
@@ -24,6 +24,38 @@ pgwin32_putenv(const char *envval)
 	char	   *cp;
 
 	/*
+	 * Update the process environment - to make modifications visible to child
+	 * processes.
+	 *
+	 * Need a copy of the string so we can modify it.
+	 */
+	envcpy = strdup(envval);
+	if (!envcpy)
+		return -1;
+	cp = strchr(envcpy, '=');
+	if (cp == NULL)
+	{
+		free(envcpy);
+		return -1;
+	}
+	*cp = '\0';
+	cp++;
+	if (strlen(cp))
+	{
+		/*
+		 * Only call SetEnvironmentVariable() when we are adding a variable,
+		 * not when removing it. Calling it on both crashes on at least
+		 * certain versions of MingW.
+		 */
+		if (!SetEnvironmentVariable(envcpy, cp))
+		{
+			free(envcpy);
+			return -1;
+		}
+	}
+	free(envcpy);
+
+	/*
 	 * Each version of MSVCRT has its own _putenv() call in the runtime
 	 * library.
 	 *
@@ -102,38 +134,6 @@ pgwin32_putenv(const char *envval)
 	}
 #endif   /* _MSC_VER */
 
-	/*
-	 * Update the process environment - to make modifications visible to child
-	 * processes.
-	 *
-	 * Need a copy of the string so we can modify it.
-	 */
-	envcpy = strdup(envval);
-	if (!envcpy)
-		return -1;
-	cp = strchr(envcpy, '=');
-	if (cp == NULL)
-	{
-		free(envcpy);
-		return -1;
-	}
-	*cp = '\0';
-	cp++;
-	if (strlen(cp))
-	{
-		/*
-		 * Only call SetEnvironmentVariable() when we are adding a variable,
-		 * not when removing it. Calling it on both crashes on at least
-		 * certain versions of MingW.
-		 */
-		if (!SetEnvironmentVariable(envcpy, cp))
-		{
-			free(envcpy);
-			return -1;
-		}
-	}
-	free(envcpy);
-
 	/* Finally, update our "own" cache */
 	return _putenv(envval);
 }
-- 
2.10.2.windows.1

