4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
23 * Copyright (c) 1989, 2010, Oracle and/or its affiliates. All rights reserved.
24 * Copyright 2016 Joyent, Inc.
27 /* Copyright (c) 1988 AT&T */
28 /* All Rights Reserved */
30 #pragma weak _putenv = putenv
34 #include <sys/types.h>
42 #define MIN_ENV_SIZE 128
44 extern const char **_environ
;
45 extern void clean_env();
48 * For performance and consistency reasons we expand the _environ list using
49 * the trusted "power of two, drop it on the floor" method. This allows for
50 * a lockless, single pass implementation of getenv(), yet the memory leak
51 * is bounded - in normal circumstances total wastage is never greater than
52 * 3x the space needed to hold any _environ list.
54 * The only abnormal circumstance is if an application modifies the _environ
55 * list pointer directly. Such an application does not conform to POSIX.1
56 * 2001. However, we also care about standards which did not foresee this
57 * issue. For this reason we keep a working copy of our notion of _environ in
58 * my_environ. If, when we are called upon to modify _environ, we ever detect
59 * a mismatch between _environ and my_environ we discard all our assumptions
60 * concerning the location and size of the _environ list. As an additional
61 * precaution we only ever update _environ once we have finished manipulating
64 * The setenv() API is inherently leaky but we are completely at the mercy
67 * To pacify leak detectors we chain all allocations which are at risk of
68 * being leaked in either of the above two scenarios. chunk_list must only
69 * be updated under the protection of update_lock.
71 * Although we don't allocate the original _environ list it is likely that
72 * we will leak this too. Accordingly, we create a reference in initenv().
73 * However, we can't be held responsible for such leaks in abnormal (see
74 * above) circumstances.
77 typedef struct chunk
{
81 static mutex_t update_lock
= DEFAULTMUTEX
;
82 static const char **orig_environ
= NULL
;
83 static const char **my_environ
= NULL
;
84 static const char **environ_base
= NULL
;
85 static int environ_size
= 0;
86 static int environ_gen
= 0;
87 static int initenv_done
= 0;
88 static chunk_t
*chunk_list
= NULL
;
91 * Compute the size an _environ list including the terminating NULL entry.
92 * This is the only way we have to determine the size of an _environ list
96 envsize(const char **e
)
103 for (size
= 1; *e
!= NULL
; e
++)
110 * Initialization for the following scenarios:
111 * 1. The very first time we reference the _environ list we must call in the
112 * NLSPATH janitor, make a reference to the original _environ list to keep
113 * leak detectors happy, initialize my_environ and environ_base, and then
114 * compute environ_size.
115 * 2. Whenever we detect that someone else has hijacked _environ (something
116 * very abnormal) we need to reinitialize my_environ and environ_base,
117 * and then recompute environ_size.
119 * The local globals my_environ, environ_base and environ_size may be used
120 * by others only if initenv_done is true and only under the protection of
121 * update_lock. However, our callers, who must NOT be holding update_lock,
122 * may safely test initenv_done or my_environ against _environ just prior to
123 * calling us because we test these again whilst holding update_lock.
128 if ((my_environ
!= _environ
) || !initenv_done
) {
129 lmutex_lock(&update_lock
);
130 if ((my_environ
!= _environ
) || !initenv_done
) {
132 /* Call the NLSPATH janitor in. */
135 /* Pacify leak detectors in normal operation. */
136 orig_environ
= _environ
;
139 my_environ
= _environ
;
140 environ_base
= my_environ
;
141 environ_size
= envsize(environ_base
);
145 lmutex_unlock(&update_lock
);
151 * Search an _environ list for a particular entry. If name_only is set, then
152 * string must be the entry name only, and we return the value of the first
153 * match. Otherwise, string must be of the form "name=value", and we return
154 * the address of the first matching entry.
157 findenv(const char **e
, const char *string
, int name_only
, char **value
)
168 target
= name_only
? '\0' : '=';
170 for (; (s2
= *e
) != NULL
; e
++) {
173 /* Fast comparison for first char. */
177 /* Slow comparison for rest of string. */
178 while (*s1
== *s2
&& *s2
!= '=') {
183 if (*s1
== target
&& *s2
== '=') {
184 *value
= (char *)s2
+ 1;
192 * Common code for putenv() and setenv(). We support the lockless getenv()
193 * by inserting new entries at the bottom of the list, and by growing the
194 * list using the trusted "power of two, drop it on the floor" method. We
195 * use a lock (update_lock) to protect all updates to the _environ list, but
196 * we are obliged to release this lock whenever we call malloc() or free().
197 * A generation number (environ_gen) is bumped whenever names are added to,
198 * or removed from, the _environ list so that we can detect collisions with
203 * -1 : with errno set
204 * -2 : an entry already existed and overwrite was zero
207 addtoenv(char *string
, int overwrite
)
212 const char **new_environ
;
213 const char **new_base
;
219 lmutex_lock(&update_lock
);
223 * If the name already exists just overwrite the existing
224 * entry -- except when we were called by setenv() without
225 * the overwrite flag.
227 if ((p
= findenv(my_environ
, string
, 0, &value
)) != NULL
) {
230 * Replace the value in situ. No name was
231 * added, so there is no need to bump the
235 lmutex_unlock(&update_lock
);
239 lmutex_unlock(&update_lock
);
244 /* Try to insert the new entry at the bottom of the list. */
245 if (environ_base
< my_environ
) {
247 * The new value must be visible before we decrement
248 * the _environ list pointer.
250 my_environ
[-1] = string
;
253 _environ
= my_environ
;
256 * We've added a name, so bump the generation number.
260 lmutex_unlock(&update_lock
);
265 * There is no room. Attempt to allocate a new _environ list
266 * which is at least double the size of the current one. See
267 * comment above concerning locking and malloc() etc.
269 new_size
= environ_size
* 2;
270 if (new_size
< MIN_ENV_SIZE
)
271 new_size
= MIN_ENV_SIZE
;
273 old_gen
= environ_gen
;
274 lmutex_unlock(&update_lock
);
276 new_chunk
= malloc(sizeof (chunk_t
) +
277 new_size
* sizeof (char *));
278 if (new_chunk
== NULL
) {
283 lmutex_lock(&update_lock
);
286 * If no other thread added or removed names while the lock
287 * was dropped, it is time to break out of this loop.
289 if (environ_gen
== old_gen
)
293 * At least one name has been added or removed, so we need to
294 * try again. It is very likely that we will find sufficient
295 * space the next time around.
297 lmutex_unlock(&update_lock
);
299 lmutex_lock(&update_lock
);
302 /* Add the new chunk to chunk_list to hide potential future leak. */
303 new_chunk
->next
= chunk_list
;
304 chunk_list
= new_chunk
;
306 /* Copy the old _environ list into the top of the new _environ list. */
307 new_base
= (const char **)(new_chunk
+ 1);
308 new_environ
= &new_base
[(new_size
- 1) - environ_size
];
309 (void) memcpy(new_environ
, my_environ
, environ_size
* sizeof (char *));
311 /* Insert the new entry at the bottom of the new _environ list. */
312 new_environ
[-1] = string
;
315 /* Ensure that the new _environ list is visible to all. */
318 /* Make the switch (dropping the old _environ list on the floor). */
319 environ_base
= new_base
;
320 my_environ
= new_environ
;
321 _environ
= my_environ
;
322 environ_size
= new_size
;
324 /* We've added a name, so bump the generation number. */
327 lmutex_unlock(&update_lock
);
332 * All the work for putenv() is done in addtoenv().
338 * Historically a call to putenv() with no '=' in the string would work
339 * great until someone called getenv() on that particular environment
340 * variable again. As we've always treated this as valid, rather than
341 * teaching the rest of the environment code how to handle something
342 * without an '=' sign, it instead just calls unsetenv().
344 if (strchr(string
, '=') == NULL
)
345 return (unsetenv(string
));
347 return (addtoenv(string
, 1));
351 * setenv() is a little more complex than putenv() because we have to allocate
352 * and construct an _environ entry on behalf of the caller. The bulk of the
353 * work is still done in addtoenv().
357 setenv(const char *envname
, const char *envval
, int overwrite
)
365 if (envname
== NULL
|| *envname
== 0 || strchr(envname
, '=') != NULL
) {
370 name_len
= strlen(envname
);
371 val_len
= strlen(envval
);
373 new_chunk
= malloc(sizeof (chunk_t
) + name_len
+ val_len
+ 2);
374 if (new_chunk
== NULL
) {
378 new_string
= (char *)(new_chunk
+ 1);
380 (void) memcpy(new_string
, envname
, name_len
);
381 new_string
[name_len
] = '=';
382 (void) memcpy(new_string
+ name_len
+ 1, envval
, val_len
);
383 new_string
[name_len
+ 1 + val_len
] = 0;
385 if ((res
= addtoenv(new_string
, overwrite
)) < 0) {
388 /* The name already existed, but not an error. */
391 /* i.e. res == -1 which means only one thing. */
397 /* Hide potential leak of new_string. */
398 lmutex_lock(&update_lock
);
399 new_chunk
->next
= chunk_list
;
400 chunk_list
= new_chunk
;
401 lmutex_unlock(&update_lock
);
407 * unsetenv() is tricky because we need to compress the _environ list in a way
408 * which supports a lockless getenv(). The approach here is to move the first
409 * entry from the enrivon list into the space occupied by the entry to be
410 * deleted, and then to increment _environ. This has the added advantage of
411 * making _any_ incremental linear search of the _environ list consistent (i.e.
412 * we will not break any naughty apps which read the list without our help).
415 unsetenv(const char *name
)
420 if (name
== NULL
|| *name
== 0 || strchr(name
, '=') != NULL
) {
427 lmutex_lock(&update_lock
);
430 * Find the target, overwrite it with the first entry, increment the
433 if ((p
= findenv(my_environ
, name
, 1, &value
)) != NULL
) {
434 /* Overwrite target with the first entry. */
437 /* Ensure that the moved entry is visible to all. */
440 /* Shrink the _environ list. */
442 _environ
= my_environ
;
444 /* Make sure addtoenv() knows that we've removed a name. */
448 lmutex_unlock(&update_lock
);
453 * Dump entire environment.
459 * Just drop the entire environment list on the floor, as it
460 * would be non-trivial to try and free the used memory.
462 static const char *nullp
= NULL
;
464 lmutex_lock(&update_lock
);
471 lmutex_unlock(&update_lock
);
477 * At last, a lockless implementation of getenv()!
480 getenv(const char *name
)
486 if (findenv(_environ
, name
, 1, &value
) != NULL
)