summaryrefslogtreecommitdiff
path: root/src/port/win32env.c
blob: 36888286b7f888dda0b2a5d606d340c1c943677a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/*-------------------------------------------------------------------------
 *
 * win32env.c
 *    putenv() and unsetenv() for win32, that updates both process
 *    environment and the cached versions in (potentially multiple)
 *    MSVCRT.
 *
 * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
 * Portions Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
 *	  $PostgreSQL: pgsql/src/port/win32env.c,v 1.2 2009/02/12 12:53:34 mha Exp $
 *
 *-------------------------------------------------------------------------
 */

#include "c.h"

int
pgwin32_putenv(const char *envval)
{
	char   *envcpy;
	char   *cp;

	/*
	 * Each version of MSVCRT has its own _putenv() call in the runtime
	 * library.
	 *
	 * If we're in VC 7.0 or later (means != mingw), update in
	 * the 6.0 MSVCRT.DLL environment as well, to work with third party
	 * libraries linked against it (such as gnuwin32 libraries).
	 */
#if defined(_MSC_VER) && (_MSC_VER >= 1300)
	typedef int 		(_cdecl *PUTENVPROC)(const char *);
	HMODULE				hmodule;
	static PUTENVPROC	putenvFunc = NULL;
	int					ret;

	if (putenvFunc == NULL)
	{
		hmodule = GetModuleHandle("msvcrt");
		if (hmodule == NULL)
			return 1;
		putenvFunc = (PUTENVPROC)GetProcAddress(hmodule, "_putenv");
		if (putenvFunc == NULL)
			return 1;
	}
	ret = putenvFunc(envval);
	if (ret != 0)
		return ret;
#endif /* _MSC_VER >= 1300 */


	/*
	 * 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);
	cp = strchr(envcpy, '=');
	if (cp == NULL)
		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);
}

void
pgwin32_unsetenv(const char *name)
{
	char   *envbuf;

	envbuf = (char *) malloc(strlen(name)+2);
	if (!envbuf)
		return;

	sprintf(envbuf, "%s=", name);
	pgwin32_putenv(envbuf);
	free(envbuf);
}