Update copyright notices with scripts/update-copyrights.
[jlayton/glibc.git] / stdlib / setenv.c
1 /* Copyright (C) 1992-2013 Free Software Foundation, Inc.
2    This file is part of the GNU C Library.
3
4    The GNU C Library is free software; you can redistribute it and/or
5    modify it under the terms of the GNU Lesser General Public
6    License as published by the Free Software Foundation; either
7    version 2.1 of the License, or (at your option) any later version.
8
9    The GNU C Library 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 GNU
12    Lesser General Public License for more details.
13
14    You should have received a copy of the GNU Lesser General Public
15    License along with the GNU C Library; if not, see
16    <http://www.gnu.org/licenses/>.  */
17
18 #if HAVE_CONFIG_H
19 # include <config.h>
20 #endif
21
22 #include <errno.h>
23 #if !_LIBC
24 # if !defined errno && !defined HAVE_ERRNO_DECL
25 extern int errno;
26 # endif
27 # define __set_errno(ev) ((errno) = (ev))
28 #endif
29
30 #if _LIBC || HAVE_STDLIB_H
31 # include <stdlib.h>
32 #endif
33 #if _LIBC || HAVE_STRING_H
34 # include <string.h>
35 #endif
36 #if _LIBC || HAVE_UNISTD_H
37 # include <unistd.h>
38 #endif
39
40 #if !_LIBC
41 # define __environ      environ
42 # ifndef HAVE_ENVIRON_DECL
43 extern char **environ;
44 # endif
45 #endif
46
47 #if _LIBC
48 /* This lock protects against simultaneous modifications of `environ'.  */
49 # include <bits/libc-lock.h>
50 __libc_lock_define_initialized (static, envlock)
51 # define LOCK   __libc_lock_lock (envlock)
52 # define UNLOCK __libc_lock_unlock (envlock)
53 #else
54 # define LOCK
55 # define UNLOCK
56 #endif
57
58 /* In the GNU C library we must keep the namespace clean.  */
59 #ifdef _LIBC
60 # define setenv __setenv
61 # define unsetenv __unsetenv
62 # define clearenv __clearenv
63 # define tfind __tfind
64 # define tsearch __tsearch
65 #endif
66
67 /* In the GNU C library implementation we try to be more clever and
68    allow arbitrarily many changes of the environment given that the used
69    values are from a small set.  Outside glibc this will eat up all
70    memory after a while.  */
71 #if defined _LIBC || (defined HAVE_SEARCH_H && defined HAVE_TSEARCH \
72                       && defined __GNUC__)
73 # define USE_TSEARCH    1
74 # include <search.h>
75
76 /* This is a pointer to the root of the search tree with the known
77    values.  */
78 static void *known_values;
79
80 # define KNOWN_VALUE(Str) \
81   ({                                                                          \
82     void *value = tfind (Str, &known_values, (__compar_fn_t) strcmp);         \
83     value != NULL ? *(char **) value : NULL;                                  \
84   })
85 # define STORE_VALUE(Str) \
86   tsearch (Str, &known_values, (__compar_fn_t) strcmp)
87
88 #else
89 # undef USE_TSEARCH
90
91 # define KNOWN_VALUE(Str) NULL
92 # define STORE_VALUE(Str) do { } while (0)
93
94 #endif
95
96
97 /* If this variable is not a null pointer we allocated the current
98    environment.  */
99 static char **last_environ;
100
101
102 /* This function is used by `setenv' and `putenv'.  The difference between
103    the two functions is that for the former must create a new string which
104    is then placed in the environment, while the argument of `putenv'
105    must be used directly.  This is all complicated by the fact that we try
106    to reuse values once generated for a `setenv' call since we can never
107    free the strings.  */
108 int
109 __add_to_environ (name, value, combined, replace)
110      const char *name;
111      const char *value;
112      const char *combined;
113      int replace;
114 {
115   register char **ep;
116   register 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 || __builtin_expect (*ep == NULL, 1))
137     {
138       const size_t varlen = namelen + 1 + vallen;
139       char **new_environ;
140
141       /* We allocated this space; we can extend it.  */
142       new_environ = (char **) realloc (last_environ,
143                                        (size + 2) * sizeof (char *));
144       if (new_environ == NULL)
145         {
146           UNLOCK;
147           return -1;
148         }
149
150       /* If the whole entry is given add it.  */
151       if (combined != NULL)
152         /* We must not add the string to the search tree since it belongs
153            to the user.  */
154         new_environ[size] = (char *) combined;
155       else
156         {
157           /* See whether the value is already known.  */
158 #ifdef USE_TSEARCH
159           char *new_value;
160           int use_alloca = __libc_use_alloca (varlen);
161           if (__builtin_expect (use_alloca, 1))
162             new_value = (char *) alloca (varlen);
163           else
164             {
165               new_value = malloc (varlen);
166               if (new_value == NULL)
167                 {
168                   UNLOCK;
169                   if (last_environ == NULL)
170                     free (new_environ);
171                   return -1;
172                 }
173             }
174 # ifdef _LIBC
175           __mempcpy (__mempcpy (__mempcpy (new_value, name, namelen), "=", 1),
176                      value, vallen);
177 # else
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 (__builtin_expect (new_environ[size] == NULL, 1))
185 #endif
186             {
187 #ifdef USE_TSEARCH
188               if (__builtin_expect (! use_alloca, 0))
189                 new_environ[size] = new_value;
190               else
191 #endif
192                 {
193                   new_environ[size] = (char *) malloc (varlen);
194                   if (__builtin_expect (new_environ[size] == NULL, 0))
195                     {
196                       UNLOCK;
197                       return -1;
198                     }
199
200 #ifdef USE_TSEARCH
201                   memcpy (new_environ[size], new_value, varlen);
202 #else
203                   memcpy (new_environ[size], name, namelen);
204                   new_environ[size][namelen] = '=';
205                   memcpy (&new_environ[size][namelen + 1], value, vallen);
206 #endif
207                 }
208
209               /* And save the value now.  We cannot do this when we remove
210                  the string since then we cannot decide whether it is a
211                  user string or not.  */
212               STORE_VALUE (new_environ[size]);
213             }
214         }
215
216       if (__environ != last_environ)
217         memcpy ((char *) new_environ, (char *) __environ,
218                 size * sizeof (char *));
219
220       new_environ[size + 1] = NULL;
221
222       last_environ = __environ = new_environ;
223     }
224   else if (replace)
225     {
226       char *np;
227
228       /* Use the user string if given.  */
229       if (combined != NULL)
230         np = (char *) combined;
231       else
232         {
233           const size_t varlen = namelen + 1 + vallen;
234 #ifdef USE_TSEARCH
235           char *new_value;
236           int use_alloca = __libc_use_alloca (varlen);
237           if (__builtin_expect (use_alloca, 1))
238             new_value = (char *) alloca (varlen);
239           else
240             {
241               new_value = malloc (varlen);
242               if (new_value == NULL)
243                 {
244                   UNLOCK;
245                   return -1;
246                 }
247             }
248 # ifdef _LIBC
249           __mempcpy (__mempcpy (__mempcpy (new_value, name, namelen), "=", 1),
250                      value, vallen);
251 # else
252           memcpy (new_value, name, namelen);
253           new_value[namelen] = '=';
254           memcpy (&new_value[namelen + 1], value, vallen);
255 # endif
256
257           np = KNOWN_VALUE (new_value);
258           if (__builtin_expect (np == NULL, 1))
259 #endif
260             {
261 #ifdef USE_TSEARCH
262               if (__builtin_expect (! use_alloca, 0))
263                 np = new_value;
264               else
265 #endif
266                 {
267                   np = malloc (varlen);
268                   if (__builtin_expect (np == NULL, 0))
269                     {
270                       UNLOCK;
271                       return -1;
272                     }
273
274 #ifdef USE_TSEARCH
275                   memcpy (np, new_value, varlen);
276 #else
277                   memcpy (np, name, namelen);
278                   np[namelen] = '=';
279                   memcpy (&np[namelen + 1], value, vallen);
280 #endif
281                 }
282               /* And remember the value.  */
283               STORE_VALUE (np);
284             }
285         }
286
287       *ep = np;
288     }
289
290   UNLOCK;
291
292   return 0;
293 }
294
295 int
296 setenv (name, value, replace)
297      const char *name;
298      const char *value;
299      int replace;
300 {
301   if (name == NULL || *name == '\0' || strchr (name, '=') != NULL)
302     {
303       __set_errno (EINVAL);
304       return -1;
305     }
306
307   return __add_to_environ (name, value, NULL, replace);
308 }
309
310 int
311 unsetenv (name)
312      const char *name;
313 {
314   size_t len;
315   char **ep;
316
317   if (name == NULL || *name == '\0' || strchr (name, '=') != NULL)
318     {
319       __set_errno (EINVAL);
320       return -1;
321     }
322
323   len = strlen (name);
324
325   LOCK;
326
327   ep = __environ;
328   if (ep != NULL)
329     while (*ep != NULL)
330       if (!strncmp (*ep, name, len) && (*ep)[len] == '=')
331         {
332           /* Found it.  Remove this pointer by moving later ones back.  */
333           char **dp = ep;
334
335           do
336             dp[0] = dp[1];
337           while (*dp++);
338           /* Continue the loop in case NAME appears again.  */
339         }
340       else
341         ++ep;
342
343   UNLOCK;
344
345   return 0;
346 }
347
348 /* The `clearenv' was planned to be added to POSIX.1 but probably
349    never made it.  Nevertheless the POSIX.9 standard (POSIX bindings
350    for Fortran 77) requires this function.  */
351 int
352 clearenv ()
353 {
354   LOCK;
355
356   if (__environ == last_environ && __environ != NULL)
357     {
358       /* We allocated this environment so we can free it.  */
359       free (__environ);
360       last_environ = NULL;
361     }
362
363   /* Clear the environment pointer removes the whole environment.  */
364   __environ = NULL;
365
366   UNLOCK;
367
368   return 0;
369 }
370 #ifdef _LIBC
371 libc_freeres_fn (free_mem)
372 {
373   /* Remove all traces.  */
374   clearenv ();
375
376   /* Now remove the search tree.  */
377   __tdestroy (known_values, free);
378   known_values = NULL;
379 }
380
381 # undef setenv
382 # undef unsetenv
383 # undef clearenv
384 weak_alias (__setenv, setenv)
385 weak_alias (__unsetenv, unsetenv)
386 weak_alias (__clearenv, clearenv)
387 #endif