xref: /titanic_41/usr/src/lib/libc/port/gen/getenv.c (revision 1c42de6d020629af774dd9e9fc81be3f3ed9398e)
1 /*
2  * CDDL HEADER START
3  *
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.
7  *
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.
12  *
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]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 /*	Copyright (c) 1988 AT&T	*/
30 /*	  All Rights Reserved  	*/
31 
32 
33 #pragma	weak putenv = _putenv
34 #pragma	weak setenv = _setenv
35 #pragma	weak unsetenv = _unsetenv
36 
37 #include "synonyms.h"
38 #include <mtlib.h>
39 
40 #include <sys/types.h>
41 #include <thread.h>
42 #include <synch.h>
43 #include <stdlib.h>
44 #include <errno.h>
45 #include <string.h>
46 #include <atomic.h>
47 
48 #define	MIN_ENV_SIZE		128
49 
50 extern const char		**environ;
51 extern void			clean_env();
52 
53 /*
54  * For performance and consistency reasons we expand the environ list using
55  * the trusted "power of two, drop it on the floor" method. This allows for
56  * a lockless, single pass implementation of getenv(), yet the memory leak
57  * is bounded - in normal circumstances total wastage is never greater than
58  * 3x the space needed to hold any environ list.
59  *
60  * The only abnormal circumstance is if an application modifies the environ
61  * list pointer directly. Such an application does not conform to POSIX.1
62  * 2001. However, we also care about standards which did not foresee this
63  * issue. For this reason we keep a working copy of our notion of environ in
64  * my_environ. If, when we are called upon to modify environ, we ever detect
65  * a mismatch between environ and my_environ we discard all our assumptions
66  * concerning the location and size of the environ list. As an additional
67  * precaution we only ever update environ once we have finished manipulating
68  * our working copy.
69  *
70  * The setenv() API is inherently leaky but we are completely at the mercy
71  * of the application.
72  *
73  * To pacify leak detectors we chain all allocations which are at risk of
74  * being leaked in either of the above two scenarios. chunk_list must only
75  * be updated under the protection of update_lock.
76  *
77  * Although we don't allocate the original environ list it is likely that
78  * we will leak this too. Accordingly, we create a reference in initenv().
79  * However, we can't be held responsible for such leaks in abnormal (see
80  * above) circumstances.
81  */
82 
83 typedef struct chunk {
84 	struct chunk		*next;
85 } chunk_t;
86 
87 static mutex_t			update_lock = DEFAULTMUTEX;
88 static const char		**orig_environ = NULL;
89 static const char		**my_environ = NULL;
90 static const char		**environ_base = NULL;
91 static int			environ_size = 0;
92 static int			environ_gen = 0;
93 static int			initenv_done = 0;
94 static chunk_t			*chunk_list = NULL;
95 
96 /*
97  * Compute the size an environ list including the terminating NULL entry.
98  * This is the only way we have to determine the size of an environ list
99  * we didn't allocate.
100  */
101 static int
102 envsize(const char **e)
103 {
104 	int			size;
105 
106 	if (e == NULL)
107 		return (0);
108 
109 	for (size = 1; *e != NULL; e++)
110 		size++;
111 
112 	return (size);
113 }
114 
115 /*
116  * Initialization for the following scenarios:
117  * 1. The very first time we reference the environ list we must call in the
118  *    NLSPATH janitor, make a reference to the original environ list to keep
119  *    leak detectors happy, initialize my_environ and environ_base, and then
120  *    compute environ_size.
121  * 2. Whenever we detect that someone else has hijacked environ (something
122  *    very abnormal) we need to reinitialize my_environ and environ_base,
123  *    and then recompute environ_size.
124  *
125  * The local globals my_environ, environ_base and environ_size may be used
126  * by others only if initenv_done is true and only under the protection of
127  * update_lock. However, our callers, who must NOT be holding update_lock,
128  * may safely test initenv_done or my_environ against environ just prior to
129  * calling us because we test these again whilst holding update_lock.
130  */
131 static void
132 initenv()
133 {
134 	if ((my_environ != environ) || !initenv_done) {
135 		lmutex_lock(&update_lock);
136 		if ((my_environ != environ) || !initenv_done) {
137 			if (!initenv_done) {
138 				/* Call the NLSPATH janitor in. */
139 				clean_env();
140 
141 				/* Pacify leak detectors in normal operation. */
142 				orig_environ = environ;
143 #ifdef __lint
144 				my_environ = orig_environ;
145 #endif
146 			}
147 
148 			my_environ = environ;
149 			environ_base = my_environ;
150 			environ_size = envsize(environ_base);
151 			membar_producer();
152 			initenv_done = 1;
153 		}
154 		lmutex_unlock(&update_lock);
155 	}
156 	membar_consumer();
157 }
158 
159 /*
160  * Search an environ list for a particular entry. If name_only is set, then
161  * string must be the entry name only, and we return the value of the first
162  * match. Otherwise, string must be of the form "name=value", and we return
163  * the address of the first matching entry.
164  */
165 static const char **
166 findenv(const char **e, const char *string, int name_only, char **value)
167 {
168 	char			target;
169 	const char		*s1;
170 	const char		*s2;
171 
172 	*value = NULL;
173 
174 	if (e == NULL)
175 		return (NULL);
176 
177 	target = name_only ? '\0' : '=';
178 
179 	for (; (s2 = *e) != NULL; e++) {
180 		s1 =  string;
181 
182 		/* Fast comparison for first char. */
183 		if (*s1 != *s2)
184 			continue;
185 
186 		/* Slow comparison for rest of string. */
187 		while (*s1 == *s2 && *s2 != '=') {
188 			s1++;
189 			s2++;
190 		}
191 
192 		if (*s1 == target && *s2 == '=') {
193 			*value = (char *)s2 + 1;
194 			return (e);
195 		}
196 	}
197 	return (NULL);
198 }
199 
200 /*
201  * Common code for putenv() and setenv(). We support the lockless getenv()
202  * by inserting new entries at the bottom of the list, and by growing the
203  * list using the trusted "power of two, drop it on the floor" method. We
204  * use a lock (update_lock) to protect all updates to the environ list, but
205  * we are obliged to release this lock whenever we call malloc() or free().
206  * A generation number (environ_gen) is bumped whenever names are added to,
207  * or removed from, the environ list so that we can detect collisions with
208  * other updaters.
209  *
210  * Return values
211  *   0 : success
212  *  -1 : with errno set
213  *  -2 : an entry already existed and overwrite was zero
214  */
215 static int
216 addtoenv(char *string, int overwrite)
217 {
218 	char			*value;
219 	const char		**p;
220 	chunk_t			*new_chunk;
221 	const char		**new_environ;
222 	const char		**new_base;
223 	int			new_size;
224 	int			old_gen;
225 
226 	initenv();
227 
228 	lmutex_lock(&update_lock);
229 
230 	for (;;) {
231 		/*
232 		 * If the name already exists just overwrite the existing
233 		 * entry -- except when we were called by setenv() without
234 		 * the overwrite flag.
235 		 */
236 		if ((p = findenv(my_environ, string, 0, &value)) != NULL) {
237 			if (overwrite) {
238 				/*
239 				 * Replace the value in situ. No name was
240 				 * added, so there is no need to bump the
241 				 * generation number.
242 				 */
243 				*p = string;
244 				lmutex_unlock(&update_lock);
245 				return (0);
246 			} else {
247 				/* No change. */
248 				lmutex_unlock(&update_lock);
249 				return (-2);
250 			}
251 		}
252 
253 		/* Try to insert the new entry at the bottom of the list. */
254 		if (environ_base < my_environ) {
255 			/*
256 			 * The new value must be visible before we decrement
257 			 * the environ list pointer.
258 			 */
259 			my_environ[-1] = string;
260 			membar_producer();
261 			my_environ--;
262 			environ = my_environ;
263 
264 			/*
265 			 * We've added a name, so bump the generation number.
266 			 */
267 			environ_gen++;
268 
269 			lmutex_unlock(&update_lock);
270 			return (0);
271 		}
272 
273 		/*
274 		 * There is no room. Attempt to allocate a new environ list
275 		 * which is at least double the size of the current one. See
276 		 * comment above concerning locking and malloc() etc.
277 		 */
278 		new_size = environ_size * 2;
279 		if (new_size < MIN_ENV_SIZE)
280 			new_size = MIN_ENV_SIZE;
281 
282 		old_gen = environ_gen;
283 		lmutex_unlock(&update_lock);
284 
285 		new_chunk = malloc(sizeof (chunk_t) +
286 		    new_size * sizeof (char *));
287 		if (new_chunk == NULL) {
288 			errno = ENOMEM;
289 			return (-1);
290 		}
291 
292 		lmutex_lock(&update_lock);
293 
294 		/*
295 		 * If no other thread added or removed names while the lock
296 		 * was dropped, it is time to break out of this loop.
297 		 */
298 		if (environ_gen == old_gen)
299 			break;
300 
301 		/*
302 		 * At least one name has been added or removed, so we need to
303 		 * try again. It is very likely that we will find sufficient
304 		 * space the next time around.
305 		 */
306 		lmutex_unlock(&update_lock);
307 		free(new_chunk);
308 		lmutex_lock(&update_lock);
309 	}
310 
311 	/* Add the new chunk to chunk_list to hide potential future leak. */
312 	new_chunk->next = chunk_list;
313 	chunk_list = new_chunk;
314 
315 	/* Copy the old environ list into the top of the new environ list. */
316 	new_base = (const char **)(new_chunk + 1);
317 	new_environ = &new_base[(new_size - 1) - environ_size];
318 	(void) memcpy(new_environ, my_environ, environ_size * sizeof (char *));
319 
320 	/* Insert the new entry at the bottom of the new environ list. */
321 	new_environ[-1] = string;
322 	new_environ--;
323 
324 	/* Ensure that the new environ list is visible to all. */
325 	membar_producer();
326 
327 	/* Make the switch (dropping the old environ list on the floor). */
328 	environ_base = new_base;
329 	my_environ = new_environ;
330 	environ = my_environ;
331 	environ_size = new_size;
332 
333 	/* We've added a name, so bump the generation number. */
334 	environ_gen++;
335 
336 	lmutex_unlock(&update_lock);
337 	return (0);
338 }
339 
340 /*
341  * All the work for putenv() is done in addtoenv().
342  */
343 int
344 putenv(char *string)
345 {
346 	return (addtoenv(string, 1));
347 }
348 
349 /*
350  * setenv() is a little more complex than putenv() because we have to allocate
351  * and construct an environ entry on behalf of the caller. The bulk of the
352  * work is still done in addtoenv().
353  */
354 
355 int
356 setenv(const char *envname, const char *envval, int overwrite)
357 {
358 	chunk_t			*new_chunk;
359 	char			*new_string;
360 	size_t			name_len;
361 	size_t			val_len;
362 	int			res;
363 
364 	if (envname == NULL || *envname == 0 || strchr(envname, '=') != NULL) {
365 		errno = EINVAL;
366 		return (-1);
367 	}
368 
369 	name_len = strlen(envname);
370 	val_len = strlen(envval);
371 
372 	new_chunk = malloc(sizeof (chunk_t) + name_len + val_len + 2);
373 	if (new_chunk == NULL) {
374 		errno = ENOMEM;
375 		return (-1);
376 	}
377 	new_string = (char *)(new_chunk + 1);
378 
379 	(void) memcpy(new_string, envname, name_len);
380 	new_string[name_len] = '=';
381 	(void) memcpy(new_string + name_len + 1, envval, val_len);
382 	new_string[name_len + 1 + val_len] = 0;
383 
384 	if ((res = addtoenv(new_string, overwrite)) < 0) {
385 		free(new_chunk);
386 		if (res == -2) {
387 			/* The name already existed, but not an error. */
388 			return (0);
389 		} else {
390 			/* i.e. res == -1 which means only one thing. */
391 			errno = ENOMEM;
392 			return (-1);
393 		}
394 	}
395 
396 	/* Hide potential leak of new_string. */
397 	lmutex_lock(&update_lock);
398 	new_chunk->next = chunk_list;
399 	chunk_list = new_chunk;
400 	lmutex_unlock(&update_lock);
401 
402 	return (0);
403 }
404 
405 /*
406  * unsetenv() is tricky because we need to compress the environ list in a way
407  * which supports a lockless getenv(). The approach here is to move the first
408  * entry from the enrivon list into the space occupied by the entry to be
409  * deleted, and then to increment environ. This has the added advantage of
410  * making _any_ incremental linear search of the environ list consistent (i.e.
411  * we will not break any naughty apps which read the list without our help).
412  */
413 int
414 unsetenv(const char *name)
415 {
416 	const char		**p;
417 	char			*value;
418 
419 	if (name == NULL || *name == 0 || strchr(name, '=') != NULL) {
420 		errno = EINVAL;
421 		return (-1);
422 	}
423 
424 	initenv();
425 
426 	lmutex_lock(&update_lock);
427 
428 	/*
429 	 * Find the target, overwrite it with the first entry, increment the
430 	 * environ pointer.
431 	 */
432 	if ((p = findenv(my_environ, name, 1, &value)) != NULL) {
433 		/* Overwrite target with the first entry. */
434 		*p = my_environ[0];
435 
436 		/* Ensure that the moved entry is visible to all.  */
437 		membar_producer();
438 
439 		/* Shrink the environ list. */
440 		my_environ++;
441 		environ = my_environ;
442 
443 		/* Make sure addtoenv() knows that we've removed a name. */
444 		environ_gen++;
445 	}
446 
447 	lmutex_unlock(&update_lock);
448 	return (0);
449 }
450 
451 /*
452  * At last, a lockless implementation of getenv()!
453  */
454 char *
455 getenv(const char *name)
456 {
457 	char			*value;
458 
459 	initenv();
460 
461 	if (findenv(environ, name, 1, &value) != NULL)
462 		return (value);
463 
464 	return (NULL);
465 }
466