import less(1)
[unleashed/tickless.git] / usr / src / lib / libc / port / gen / getenv.c
blobdf8b7e4228fa821ed0d5be69aa550add65db9a1a
1 /*
2 * CDDL HEADER START
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]
19 * CDDL HEADER END
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
32 #include "lint.h"
33 #include <mtlib.h>
34 #include <sys/types.h>
35 #include <thread.h>
36 #include <synch.h>
37 #include <stdlib.h>
38 #include <errno.h>
39 #include <string.h>
40 #include <atomic.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
62 * our working copy.
64 * The setenv() API is inherently leaky but we are completely at the mercy
65 * of the application.
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 {
78 struct chunk *next;
79 } chunk_t;
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
93 * we didn't allocate.
95 static int
96 envsize(const char **e)
98 int size;
100 if (e == NULL)
101 return (0);
103 for (size = 1; *e != NULL; e++)
104 size++;
106 return (size);
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.
125 static void
126 initenv()
128 if ((my_environ != _environ) || !initenv_done) {
129 lmutex_lock(&update_lock);
130 if ((my_environ != _environ) || !initenv_done) {
131 if (!initenv_done) {
132 /* Call the NLSPATH janitor in. */
133 clean_env();
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);
142 membar_producer();
143 initenv_done = 1;
145 lmutex_unlock(&update_lock);
147 membar_consumer();
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.
156 static const char **
157 findenv(const char **e, const char *string, int name_only, char **value)
159 char target;
160 const char *s1;
161 const char *s2;
163 *value = NULL;
165 if (e == NULL)
166 return (NULL);
168 target = name_only ? '\0' : '=';
170 for (; (s2 = *e) != NULL; e++) {
171 s1 = string;
173 /* Fast comparison for first char. */
174 if (*s1 != *s2)
175 continue;
177 /* Slow comparison for rest of string. */
178 while (*s1 == *s2 && *s2 != '=') {
179 s1++;
180 s2++;
183 if (*s1 == target && *s2 == '=') {
184 *value = (char *)s2 + 1;
185 return (e);
188 return (NULL);
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
199 * other updaters.
201 * Return values
202 * 0 : success
203 * -1 : with errno set
204 * -2 : an entry already existed and overwrite was zero
206 static int
207 addtoenv(char *string, int overwrite)
209 char *value;
210 const char **p;
211 chunk_t *new_chunk;
212 const char **new_environ;
213 const char **new_base;
214 int new_size;
215 int old_gen;
217 initenv();
219 lmutex_lock(&update_lock);
221 for (;;) {
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) {
228 if (overwrite) {
230 * Replace the value in situ. No name was
231 * added, so there is no need to bump the
232 * generation number.
234 *p = string;
235 lmutex_unlock(&update_lock);
236 return (0);
237 } else {
238 /* No change. */
239 lmutex_unlock(&update_lock);
240 return (-2);
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;
251 membar_producer();
252 my_environ--;
253 _environ = my_environ;
256 * We've added a name, so bump the generation number.
258 environ_gen++;
260 lmutex_unlock(&update_lock);
261 return (0);
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) {
279 errno = ENOMEM;
280 return (-1);
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)
290 break;
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);
298 free(new_chunk);
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;
313 new_environ--;
315 /* Ensure that the new _environ list is visible to all. */
316 membar_producer();
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. */
325 environ_gen++;
327 lmutex_unlock(&update_lock);
328 return (0);
332 * All the work for putenv() is done in addtoenv().
335 putenv(char *string)
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)
359 chunk_t *new_chunk;
360 char *new_string;
361 size_t name_len;
362 size_t val_len;
363 int res;
365 if (envname == NULL || *envname == 0 || strchr(envname, '=') != NULL) {
366 errno = EINVAL;
367 return (-1);
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) {
375 errno = ENOMEM;
376 return (-1);
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) {
386 free(new_chunk);
387 if (res == -2) {
388 /* The name already existed, but not an error. */
389 return (0);
390 } else {
391 /* i.e. res == -1 which means only one thing. */
392 errno = ENOMEM;
393 return (-1);
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);
403 return (0);
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)
417 const char **p;
418 char *value;
420 if (name == NULL || *name == 0 || strchr(name, '=') != NULL) {
421 errno = EINVAL;
422 return (-1);
425 initenv();
427 lmutex_lock(&update_lock);
430 * Find the target, overwrite it with the first entry, increment the
431 * _environ pointer.
433 if ((p = findenv(my_environ, name, 1, &value)) != NULL) {
434 /* Overwrite target with the first entry. */
435 *p = my_environ[0];
437 /* Ensure that the moved entry is visible to all. */
438 membar_producer();
440 /* Shrink the _environ list. */
441 my_environ++;
442 _environ = my_environ;
444 /* Make sure addtoenv() knows that we've removed a name. */
445 environ_gen++;
448 lmutex_unlock(&update_lock);
449 return (0);
453 * Dump entire environment.
456 clearenv(void)
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);
465 _environ = &nullp;
466 my_environ = NULL;
467 environ_base = NULL;
468 environ_size = 0;
469 environ_gen++;
470 membar_producer();
471 lmutex_unlock(&update_lock);
473 return (0);
477 * At last, a lockless implementation of getenv()!
479 char *
480 getenv(const char *name)
482 char *value;
484 initenv();
486 if (findenv(_environ, name, 1, &value) != NULL)
487 return (value);
489 return (NULL);