Win32: fix environment memory leaks

All functions that modify the environment have memory leaks. Disable gitunsetenv in the Makefile and use env_setenv (via mingw_putenv) instead (this frees removed environment entries). Move xstrdup from env_setenv to make_augmented_environ, so that mingw_putenv no longer copies the environment entries (according to POSIX [1], "the string [...] shall become part of the environment"). This also fixes the memory leak in gitsetenv, which expects a POSIX compliant putenv. [1] http://pubs.opengroup.org/onlinepubs/009695399/functions/putenv.html Note: This patch depends on taking control of char **environ and having our own mingw_putenv (both introduced in "Win32: Unicode environment (incoming)"). Signed-off-by: Karsten Blees <blees@dcon.de> Signed-off-by: Stepan Kasal <kasal@ucw.cz> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Karsten Blees committed Jul 17, 2014 at 17:37 UTC e96942e821dec273b884fec378cc2a97a7f5d689
3 files changed +7 -6
compat/mingw.c
+6 -4
@@ -1220,14 +1220,14 @@ static char **env_setenv(char **env, const char *name)
1220 for (i = 0; env[i]; i++)
1221 ;
1222 env = xrealloc(env, (i+2)*sizeof(*env));
1223 - env[i] = xstrdup(name);
1223 + env[i] = (char*) name;
1224 env[i+1] = NULL;
1225 }
1226 }
1227 else {
1228 free(env[i]);
1229 if (*eq)
1230 - env[i] = xstrdup(name);
1230 + env[i] = (char*) name;
1231 else
1232 for (; env[i]; i++)
1233 env[i] = env[i+1];
@@ -1242,8 +1242,10 @@ char **make_augmented_environ(const char *const *vars)
1242 {
1243 char **env = copy_environ();
1244
1245 - while (*vars)
1246 - env = env_setenv(env, *vars++);
1245 + while (*vars) {
1246 + const char *v = *vars++;
1247 + env = env_setenv(env, strchr(v, '=') ? xstrdup(v) : v);
1248 + }
1249 return env;
1250 }
1251
compat/mingw.h
+1
@@ -209,6 +209,7 @@ char *mingw_getenv(const char *name);
209 #define getenv mingw_getenv
210 int mingw_putenv(const char *namevalue);
211 #define putenv mingw_putenv
212 +#define unsetenv mingw_putenv
213
214 int mingw_gethostname(char *host, int namelen);
215 #define gethostname mingw_gethostname
config.mak.uname
-2
@@ -326,7 +326,6 @@ ifeq ($(uname_S),Windows)
326 NO_IPV6 = YesPlease
327 NO_UNIX_SOCKETS = YesPlease
328 NO_SETENV = YesPlease
329 - NO_UNSETENV = YesPlease
329 NO_STRCASESTR = YesPlease
330 NO_STRLCPY = YesPlease
331 NO_MEMMEM = YesPlease
@@ -479,7 +478,6 @@ ifneq (,$(findstring MINGW,$(uname_S)))
478 NO_SYMLINK_HEAD = YesPlease
479 NO_UNIX_SOCKETS = YesPlease
480 NO_SETENV = YesPlease
482 - NO_UNSETENV = YesPlease
481 NO_STRCASESTR = YesPlease
482 NO_STRLCPY = YesPlease
483 NO_MEMMEM = YesPlease