178191c6173f161e20d0a63e395037a404c34498
[gnulib.git] / lib / setenv.c
1 /* Copyright (C) 1992, 1995-2003, 2005-2010 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 3 of the License, or
7    (at your option) 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
15    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
16
17 #if !_LIBC
18 # include <config.h>
19 #endif
20
21 /* Don't use __attribute__ __nonnull__ in this compilation unit.  Otherwise gcc
22    optimizes away the name == NULL test below.  */
23 #define _GL_ARG_NONNULL(params)
24
25 #include <alloca.h>
26
27 /* Specification.  */
28 #include <stdlib.h>
29
30 #include <errno.h>
31 #ifndef __set_errno
32 # define __set_errno(ev) ((errno) = (ev))
33 #endif
34
35 #include <string.h>
36 #if _LIBC || HAVE_UNISTD_H
37 # include <unistd.h>
38 #endif
39
40 #if !_LIBC
41 # include "malloca.h"
42 #endif
43
44 #if _LIBC || !HAVE_SETENV
45
46 #if !_LIBC
47 # define __environ      environ
48 #endif
49
50 #if _LIBC
51 /* This lock protects against simultaneous modifications of `environ'.  */
52 # include <bits/libc-lock.h>
53 __libc_lock_define_initialized (static, envlock)
54 # define LOCK   __libc_lock_lock (envlock)
55 # define UNLOCK __libc_lock_unlock (envlock)
56 #else
57 # define LOCK
58 # define UNLOCK
59 #endif
60
61 /* In the GNU C library we must keep the namespace clean.  */
62 #ifdef _LIBC
63 # define setenv __setenv
64 # define clearenv __clearenv
65 # define tfind __tfind
66 # define tsearch __tsearch
67 #endif
68
69 /* In the GNU C library implementation we try to be more clever and
70    allow arbitrarily many changes of the environment given that the used
71    values are from a small set.  Outside glibc this will eat up all
72    memory after a while.  */
73 #if defined _LIBC || (defined HAVE_SEARCH_H && defined HAVE_TSEARCH \
74                       && defined __GNUC__)
75 # define USE_TSEARCH    1
76 # include <search.h>
77 typedef int (*compar_fn_t) (const void *, const void *);
78
79 /* This is a pointer to the root of the search tree with the known
80    values.  */
81 static void *known_values;
82
83 # define KNOWN_VALUE(Str) \
84   ({                                                                          \
85     void *value = tfind (Str, &known_values, (compar_fn_t) strcmp);           \
86     value != NULL ? *(char **) value : NULL;                                  \
87   })
88 # define STORE_VALUE(Str) \
89   tsearch (Str, &known_values, (compar_fn_t) strcmp)
90
91 #else
92 # undef USE_TSEARCH
93
94 # define KNOWN_VALUE(Str) NULL
95 # define STORE_VALUE(Str) do { } while (0)
96
97 #endif
98
99
100 /* If this variable is not a null pointer we allocated the current
101    environment.  */
102 static char **last_environ;
103
104
105 /* This function is used by `setenv' and `putenv'.  The difference between
106    the two functions is that for the former must create a new string which
107    is then placed in the environment, while the argument of `putenv'
108    must be used directly.  This is all complicated by the fact that we try
109    to reuse values once generated for a `setenv' call since we can never
110    free the strings.  */
111 int
112 __add_to_environ (const char *name, const char *value, const char *combined,
113                   int replace)
114 {
115   char **ep;
116   size_t size;
117   const size_t namelen = strlen (name);
118   const size_t vallen = value != NULL ? strlen (value) + 1 : 0;
119
120   LOCK;
121
122   /* We have to get the pointer now that we have the lock and not earlier
123      since another thread might have created a new environment.  */
124   ep = __environ;
125
126   size = 0;
127   if (ep != NULL)
128     {
129       for (; *ep != NULL; ++ep)
130         if (!strncmp (*ep, name, namelen) && (*ep)[namelen] == '=')
131           break;
132         else
133           ++size;
134     }
135
136   if (ep == NULL || *ep == NULL)
137     {
138       char **new_environ;
139 #ifdef USE_TSEARCH
140       char *new_value;
141 #endif
142
143       /* We allocated this space; we can extend it.  */
144       new_environ =
145         (char **) (last_environ == NULL
146                    ? malloc ((size + 2) * sizeof (char *))
147                    : realloc (last_environ, (size + 2) * sizeof (char *)));
148       if (new_environ == NULL)
149         {
150           /* It's easier to set errno to ENOMEM than to rely on the
151              'malloc-posix' and 'realloc-posix' gnulib modules.  */
152           __set_errno (ENOMEM);
153           UNLOCK;
154           return -1;
155         }
156
157       /* If the whole entry is given add it.  */
158       if (combined != NULL)
159         /* We must not add the string to the search tree since it belongs
160            to the user.  */
161         new_environ[size] = (char *) combined;
162       else
163         {
164           /* See whether the value is already known.  */
165 #ifdef USE_TSEARCH
166 # ifdef _LIBC
167           new_value = (char *) alloca (namelen + 1 + vallen);
168           __mempcpy (__mempcpy (__mempcpy (new_value, name, namelen), "=", 1),
169                      value, vallen);
170 # else
171           new_value = (char *) malloca (namelen + 1 + vallen);
172           if (new_value == NULL)
173             {
174               __set_errno (ENOMEM);
175               UNLOCK;
176               return -1;
177             }
178           memcpy (new_value, name, namelen);
179           new_value[namelen] = '=';
180           memcpy (&new_value[namelen + 1], value, vallen);
181 # endif
182
183           new_environ[size] = KNOWN_VALUE (new_value);
184           if (new_environ[size] == NULL)
185 #endif
186             {
187               new_environ[size] = (char *) malloc (namelen + 1 + vallen);
188               if (new_environ[size] == NULL)
189                 {
190 #if defined USE_TSEARCH && !defined _LIBC
191                   freea (new_value);
192 #endif
193                   __set_errno (ENOMEM);
194                   UNLOCK;
195                   return -1;
196                 }
197
198 #ifdef USE_TSEARCH
199               memcpy (new_environ[size], new_value, namelen + 1 + vallen);
200 #else
201               memcpy (new_environ[size], name, namelen);
202               new_environ[size][namelen] = '=';
203               memcpy (&new_environ[size][namelen + 1], value, vallen);
204 #endif
205               /* And save the value now.  We cannot do this when we remove
206                  the string since then we cannot decide whether it is a
207                  user string or not.  */
208               STORE_VALUE (new_environ[size]);
209             }
210 #if defined USE_TSEARCH && !defined _LIBC
211           freea (new_value);
212 #endif
213         }
214
215       if (__environ != last_environ)
216         memcpy ((char *) new_environ, (char *) __environ,
217                 size * sizeof (char *));
218
219       new_environ[size + 1] = NULL;
220
221       last_environ = __environ = new_environ;
222     }
223   else if (replace)
224     {
225       char *np;
226
227       /* Use the user string if given.  */
228       if (combined != NULL)
229         np = (char *) combined;
230       else
231         {
232 #ifdef USE_TSEARCH
233           char *new_value;
234 # ifdef _LIBC
235           new_value = alloca (namelen + 1 + vallen);
236           __mempcpy (__mempcpy (__mempcpy (new_value, name, namelen), "=", 1),
237                      value, vallen);
238 # else
239           new_value = malloca (namelen + 1 + vallen);
240           if (new_value == NULL)
241             {
242               __set_errno (ENOMEM);
243               UNLOCK;
244               return -1;
245             }
246           memcpy (new_value, name, namelen);
247           new_value[namelen] = '=';
248           memcpy (&new_value[namelen + 1], value, vallen);
249 # endif
250
251           np = KNOWN_VALUE (new_value);
252           if (np == NULL)
253 #endif
254             {
255               np = (char *) malloc (namelen + 1 + vallen);
256               if (np == NULL)
257                 {
258 #if defined USE_TSEARCH && !defined _LIBC
259                   freea (new_value);
260 #endif
261                   __set_errno (ENOMEM);
262                   UNLOCK;
263                   return -1;
264                 }
265
266 #ifdef USE_TSEARCH
267               memcpy (np, new_value, namelen + 1 + vallen);
268 #else
269               memcpy (np, name, namelen);
270               np[namelen] = '=';
271               memcpy (&np[namelen + 1], value, vallen);
272 #endif
273               /* And remember the value.  */
274               STORE_VALUE (np);
275             }
276 #if defined USE_TSEARCH && !defined _LIBC
277           freea (new_value);
278 #endif
279         }
280
281       *ep = np;
282     }
283
284   UNLOCK;
285
286   return 0;
287 }
288
289 int
290 setenv (const char *name, const char *value, int replace)
291 {
292   if (name == NULL || *name == '\0' || strchr (name, '=') != NULL)
293     {
294       __set_errno (EINVAL);
295       return -1;
296     }
297
298   return __add_to_environ (name, value, NULL, replace);
299 }
300
301 /* The `clearenv' was planned to be added to POSIX.1 but probably
302    never made it.  Nevertheless the POSIX.9 standard (POSIX bindings
303    for Fortran 77) requires this function.  */
304 int
305 clearenv (void)
306 {
307   LOCK;
308
309   if (__environ == last_environ && __environ != NULL)
310     {
311       /* We allocated this environment so we can free it.  */
312       free (__environ);
313       last_environ = NULL;
314     }
315
316   /* Clear the environment pointer removes the whole environment.  */
317   __environ = NULL;
318
319   UNLOCK;
320
321   return 0;
322 }
323
324 #ifdef _LIBC
325 static void
326 free_mem (void)
327 {
328   /* Remove all traces.  */
329   clearenv ();
330
331   /* Now remove the search tree.  */
332   __tdestroy (known_values, free);
333   known_values = NULL;
334 }
335 text_set_element (__libc_subfreeres, free_mem);
336
337
338 # undef setenv
339 # undef clearenv
340 weak_alias (__setenv, setenv)
341 weak_alias (__clearenv, clearenv)
342 #endif
343
344 #endif /* _LIBC || !HAVE_SETENV */
345
346 /* The rest of this file is called into use when replacing an existing
347    but buggy setenv.  Known bugs include failure to diagnose invalid
348    name, and consuming a leading '=' from value.  */
349 #if HAVE_SETENV
350
351 # undef setenv
352 # define STREQ(a, b) (strcmp (a, b) == 0)
353
354 int
355 rpl_setenv (const char *name, const char *value, int replace)
356 {
357   int result;
358   if (!name || !*name || strchr (name, '='))
359     {
360       errno = EINVAL;
361       return -1;
362     }
363   /* Call the real setenv even if replace is 0, in case implementation
364      has underlying data to update, such as when environ changes.  */
365   result = setenv (name, value, replace);
366   if (result == 0 && replace && *value == '=')
367     {
368       char *tmp = getenv (name);
369       if (!STREQ (tmp, value))
370         {
371           int saved_errno;
372           size_t len = strlen (value);
373           tmp = malloca (len + 2);
374           /* Since leading '=' is eaten, double it up.  */
375           *tmp = '=';
376           memcpy (tmp + 1, value, len + 1);
377           result = setenv (name, tmp, replace);
378           saved_errno = errno;
379           freea (tmp);
380           errno = saved_errno;
381         }
382     }
383   return result;
384 }
385
386 #endif /* HAVE_SETENV */