sync from coreutils
[gnulib.git] / lib / setenv.c
1 /* Copyright (C) 1992,1995-1999,2000-2003,2005 Free Software Foundation, Inc.
2    This file is part of the GNU C Library.
3
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 2, or (at your option)
7    any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License along
15    with this program; if not, write to the Free Software Foundation,
16    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
17
18 #ifdef HAVE_CONFIG_H
19 # include <config.h>
20 #endif
21 #include <alloca.h>
22
23 #include <errno.h>
24 #ifndef __set_errno
25 # define __set_errno(ev) ((errno) = (ev))
26 #endif
27
28 #include <stdlib.h>
29 #include <string.h>
30 #include <unistd.h>
31
32 #if !_LIBC
33 # include "allocsa.h"
34 #endif
35
36 #if !_LIBC
37 # define __environ      environ
38 # ifndef HAVE_ENVIRON_DECL
39 extern char **environ;
40 # endif
41 #endif
42
43 #if _LIBC
44 /* This lock protects against simultaneous modifications of `environ'.  */
45 # include <bits/libc-lock.h>
46 __libc_lock_define_initialized (static, envlock)
47 # define LOCK   __libc_lock_lock (envlock)
48 # define UNLOCK __libc_lock_unlock (envlock)
49 #else
50 # define LOCK
51 # define UNLOCK
52 #endif
53
54 /* In the GNU C library we must keep the namespace clean.  */
55 #ifdef _LIBC
56 # define setenv __setenv
57 # define clearenv __clearenv
58 # define tfind __tfind
59 # define tsearch __tsearch
60 #endif
61
62 /* In the GNU C library implementation we try to be more clever and
63    allow arbitrarily many changes of the environment given that the used
64    values are from a small set.  Outside glibc this will eat up all
65    memory after a while.  */
66 #if defined _LIBC || (defined HAVE_SEARCH_H && defined HAVE_TSEARCH \
67                       && defined __GNUC__)
68 # define USE_TSEARCH    1
69 # include <search.h>
70 typedef int (*compar_fn_t) (const void *, const void *);
71
72 /* This is a pointer to the root of the search tree with the known
73    values.  */
74 static void *known_values;
75
76 # define KNOWN_VALUE(Str) \
77   ({                                                                          \
78     void *value = tfind (Str, &known_values, (compar_fn_t) strcmp);           \
79     value != NULL ? *(char **) value : NULL;                                  \
80   })
81 # define STORE_VALUE(Str) \
82   tsearch (Str, &known_values, (compar_fn_t) strcmp)
83
84 #else
85 # undef USE_TSEARCH
86
87 # define KNOWN_VALUE(Str) NULL
88 # define STORE_VALUE(Str) do { } while (0)
89
90 #endif
91
92
93 /* If this variable is not a null pointer we allocated the current
94    environment.  */
95 static char **last_environ;
96
97
98 /* This function is used by `setenv' and `putenv'.  The difference between
99    the two functions is that for the former must create a new string which
100    is then placed in the environment, while the argument of `putenv'
101    must be used directly.  This is all complicated by the fact that we try
102    to reuse values once generated for a `setenv' call since we can never
103    free the strings.  */
104 int
105 __add_to_environ (const char *name, const char *value, const char *combined,
106                   int replace)
107 {
108   register char **ep;
109   register size_t size;
110   const size_t namelen = strlen (name);
111   const size_t vallen = value != NULL ? strlen (value) + 1 : 0;
112
113   LOCK;
114
115   /* We have to get the pointer now that we have the lock and not earlier
116      since another thread might have created a new environment.  */
117   ep = __environ;
118
119   size = 0;
120   if (ep != NULL)
121     {
122       for (; *ep != NULL; ++ep)
123         if (!strncmp (*ep, name, namelen) && (*ep)[namelen] == '=')
124           break;
125         else
126           ++size;
127     }
128
129   if (ep == NULL || *ep == NULL)
130     {
131       char **new_environ;
132 #ifdef USE_TSEARCH
133       char *new_value;
134 #endif
135
136       /* We allocated this space; we can extend it.  */
137       new_environ =
138         (char **) (last_environ == NULL
139                    ? malloc ((size + 2) * sizeof (char *))
140                    : realloc (last_environ, (size + 2) * sizeof (char *)));
141       if (new_environ == NULL)
142         {
143           UNLOCK;
144           return -1;
145         }
146
147       /* If the whole entry is given add it.  */
148       if (combined != NULL)
149         /* We must not add the string to the search tree since it belongs
150            to the user.  */
151         new_environ[size] = (char *) combined;
152       else
153         {
154           /* See whether the value is already known.  */
155 #ifdef USE_TSEARCH
156 # ifdef _LIBC
157           new_value = (char *) alloca (namelen + 1 + vallen);
158           __mempcpy (__mempcpy (__mempcpy (new_value, name, namelen), "=", 1),
159                      value, vallen);
160 # else
161           new_value = (char *) allocsa (namelen + 1 + vallen);
162           if (new_value == NULL)
163             {
164               __set_errno (ENOMEM);
165               UNLOCK;
166               return -1;
167             }
168           memcpy (new_value, name, namelen);
169           new_value[namelen] = '=';
170           memcpy (&new_value[namelen + 1], value, vallen);
171 # endif
172
173           new_environ[size] = KNOWN_VALUE (new_value);
174           if (new_environ[size] == NULL)
175 #endif
176             {
177               new_environ[size] = (char *) malloc (namelen + 1 + vallen);
178               if (new_environ[size] == NULL)
179                 {
180 #if defined USE_TSEARCH && !defined _LIBC
181                   freesa (new_value);
182 #endif
183                   __set_errno (ENOMEM);
184                   UNLOCK;
185                   return -1;
186                 }
187
188 #ifdef USE_TSEARCH
189               memcpy (new_environ[size], new_value, namelen + 1 + vallen);
190 #else
191               memcpy (new_environ[size], name, namelen);
192               new_environ[size][namelen] = '=';
193               memcpy (&new_environ[size][namelen + 1], value, vallen);
194 #endif
195               /* And save the value now.  We cannot do this when we remove
196                  the string since then we cannot decide whether it is a
197                  user string or not.  */
198               STORE_VALUE (new_environ[size]);
199             }
200 #if defined USE_TSEARCH && !defined _LIBC
201           freesa (new_value);
202 #endif
203         }
204
205       if (__environ != last_environ)
206         memcpy ((char *) new_environ, (char *) __environ,
207                 size * sizeof (char *));
208
209       new_environ[size + 1] = NULL;
210
211       last_environ = __environ = new_environ;
212     }
213   else if (replace)
214     {
215       char *np;
216
217       /* Use the user string if given.  */
218       if (combined != NULL)
219         np = (char *) combined;
220       else
221         {
222 #ifdef USE_TSEARCH
223           char *new_value;
224 # ifdef _LIBC
225           new_value = alloca (namelen + 1 + vallen);
226           __mempcpy (__mempcpy (__mempcpy (new_value, name, namelen), "=", 1),
227                      value, vallen);
228 # else
229           new_value = allocsa (namelen + 1 + vallen);
230           if (new_value == NULL)
231             {
232               __set_errno (ENOMEM);
233               UNLOCK;
234               return -1;
235             }
236           memcpy (new_value, name, namelen);
237           new_value[namelen] = '=';
238           memcpy (&new_value[namelen + 1], value, vallen);
239 # endif
240
241           np = KNOWN_VALUE (new_value);
242           if (np == NULL)
243 #endif
244             {
245               np = malloc (namelen + 1 + vallen);
246               if (np == NULL)
247                 {
248 #if defined USE_TSEARCH && !defined _LIBC
249                   freesa (new_value);
250 #endif
251                   __set_errno (ENOMEM);
252                   UNLOCK;
253                   return -1;
254                 }
255
256 #ifdef USE_TSEARCH
257               memcpy (np, new_value, namelen + 1 + vallen);
258 #else
259               memcpy (np, name, namelen);
260               np[namelen] = '=';
261               memcpy (&np[namelen + 1], value, vallen);
262 #endif
263               /* And remember the value.  */
264               STORE_VALUE (np);
265             }
266 #if defined USE_TSEARCH && !defined _LIBC
267           freesa (new_value);
268 #endif
269         }
270
271       *ep = np;
272     }
273
274   UNLOCK;
275
276   return 0;
277 }
278
279 int
280 setenv (const char *name, const char *value, int replace)
281 {
282   return __add_to_environ (name, value, NULL, replace);
283 }
284
285 /* The `clearenv' was planned to be added to POSIX.1 but probably
286    never made it.  Nevertheless the POSIX.9 standard (POSIX bindings
287    for Fortran 77) requires this function.  */
288 int
289 clearenv (void)
290 {
291   LOCK;
292
293   if (__environ == last_environ && __environ != NULL)
294     {
295       /* We allocated this environment so we can free it.  */
296       free (__environ);
297       last_environ = NULL;
298     }
299
300   /* Clear the environment pointer removes the whole environment.  */
301   __environ = NULL;
302
303   UNLOCK;
304
305   return 0;
306 }
307
308 #ifdef _LIBC
309 static void
310 free_mem (void)
311 {
312   /* Remove all traces.  */
313   clearenv ();
314
315   /* Now remove the search tree.  */
316   __tdestroy (known_values, free);
317   known_values = NULL;
318 }
319 text_set_element (__libc_subfreeres, free_mem);
320
321
322 # undef setenv
323 # undef clearenv
324 weak_alias (__setenv, setenv)
325 weak_alias (__clearenv, clearenv)
326 #endif