1 /*-------------------------------------------------------------------------
4 * putenv() and unsetenv() for win32, that updates both process
5 * environment and the cached versions in (potentially multiple)
8 * Portions Copyright (c) 1996-2010, PostgreSQL Global Development Group
9 * Portions Copyright (c) 1994, Regents of the University of California
13 * $PostgreSQL: pgsql/src/port/win32env.c,v 1.8 2010/02/26 02:01:38 momjian Exp $
15 *-------------------------------------------------------------------------
21 pgwin32_putenv(const char *envval)
27 * Each version of MSVCRT has its own _putenv() call in the runtime
30 * mingw always uses MSVCRT.DLL, but if we are in a Visual C++
31 * environment, attempt to update the environment in all MSVCRT modules
32 * that are currently loaded, to work properly with any third party
33 * libraries linked against a different MSVCRT but still relying on
34 * environment variables.
36 * Also separately update the system environment that gets inherited by
40 typedef int (_cdecl * PUTENVPROC) (const char *);
45 PUTENVPROC putenvFunc;
50 }, /* Visual Studio 6.0 / mingw */
53 }, /* Visual Studio 2002 */
56 }, /* Visual Studio 2003 */
59 }, /* Visual Studio 2005 */
62 }, /* Visual Studio 2008 */
69 for (i = 0; rtmodules[i].modulename; i++)
71 if (rtmodules[i].putenvFunc == NULL)
73 if (rtmodules[i].hmodule == 0)
75 /* Not attempted before, so try to find this DLL */
76 rtmodules[i].hmodule = GetModuleHandle(rtmodules[i].modulename);
77 if (rtmodules[i].hmodule == NULL)
80 * Set to INVALID_HANDLE_VALUE so we know we have tried
81 * this one before, and won't try again.
83 rtmodules[i].hmodule = INVALID_HANDLE_VALUE;
88 rtmodules[i].putenvFunc = (PUTENVPROC) GetProcAddress(rtmodules[i].hmodule, "_putenv");
89 if (rtmodules[i].putenvFunc == NULL)
91 CloseHandle(rtmodules[i].hmodule);
92 rtmodules[i].hmodule = INVALID_HANDLE_VALUE;
100 * Module loaded, but we did not find the function last time.
101 * We're not going to find it this time either...
106 /* At this point, putenvFunc is set or we have exited the loop */
107 rtmodules[i].putenvFunc(envval);
109 #endif /* _MSC_VER */
112 * Update the process environment - to make modifications visible to child
115 * Need a copy of the string so we can modify it.
117 envcpy = strdup(envval);
118 cp = strchr(envcpy, '=');
126 * Only call SetEnvironmentVariable() when we are adding a variable,
127 * not when removing it. Calling it on both crashes on at least
128 * certain versions of MingW.
130 if (!SetEnvironmentVariable(envcpy, cp))
138 /* Finally, update our "own" cache */
139 return _putenv(envval);
143 pgwin32_unsetenv(const char *name)
147 envbuf = (char *) malloc(strlen(name) + 2);
151 sprintf(envbuf, "%s=", name);
152 pgwin32_putenv(envbuf);