2 * Copyright (c) 2007-2008 Sean C. Farley <scf@FreeBSD.org>
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer,
10 * without modification, immediately at the beginning of the file.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 * $FreeBSD: src/lib/libc/stdlib/getenv.c,v 1.15 2008/08/03 22:47:23 scf Exp $
29 #include "namespace.h"
30 #include <sys/types.h>
37 #include "un-namespace.h"
40 static const char CorruptEnvFindMsg[] = "environment corrupt; unable to find ";
41 static const char CorruptEnvValueMsg[] =
42 "environment corrupt; missing value for ";
46 * Standard environ. environ variable is exposed to entire process.
48 * origEnviron: Upon cleanup on unloading of library or failure, this
49 * allows environ to return to as it was before.
50 * environSize: Number of variables environ can hold. Can only
52 * intEnviron: Internally-built environ. Exposed via environ during
53 * (re)builds of the environment.
56 static char **origEnviron;
57 static char **intEnviron = NULL;
58 static int environSize = 0;
61 * Array of environment variables built from environ. Each element records:
62 * name: Pointer to name=value string
63 * name length: Length of name not counting '=' character
64 * value: Pointer to value within same string as name
65 * value size: Size (not length) of space for value not counting the
67 * active state: true/false value to signify whether variable is active.
68 * Useful since multiple variables with the same name can
69 * co-exist. At most, one variable can be active at any
71 * putenv: Created from putenv() call. This memory must not be
74 static struct envVars {
84 * Environment array information.
86 * envActive: Number of active variables in array.
87 * envVarsSize: Size of array.
88 * envVarsTotal: Number of total variables in array (active or not).
90 static int envActive = 0;
91 static int envVarsSize = 0;
92 static int envVarsTotal = 0;
95 /* Deinitialization of new environment. */
96 static void __attribute__ ((destructor)) __clean_env_destructor(void);
100 * A simple version of warnx() to avoid the bloat of including stdio in static
104 __env_warnx(const char *msg, const char *name, size_t nameLen)
106 static const char nl[] = "\n";
107 static const char progSep[] = ": ";
109 _write(STDERR_FILENO, _getprogname(), strlen(_getprogname()));
110 _write(STDERR_FILENO, progSep, sizeof(progSep) - 1);
111 _write(STDERR_FILENO, msg, strlen(msg));
112 _write(STDERR_FILENO, name, nameLen);
113 _write(STDERR_FILENO, nl, sizeof(nl) - 1);
120 * Inline strlen() for performance. Also, perform check for an equals sign.
121 * Cheaper here than peforming a strchr() later.
124 __strleneq(const char *str)
128 for (s = str; *s != '\0'; ++s)
137 * Comparison of an environment name=value to a name.
140 strncmpeq(const char *nameValue, const char *name, size_t nameLen)
142 if (strncmp(nameValue, name, nameLen) == 0 && nameValue[nameLen] == '=')
150 * Using environment, returns pointer to value associated with name, if any,
151 * else NULL. If the onlyActive flag is set to true, only variables that are
152 * active are returned else all are.
155 __findenv(const char *name, size_t nameLen, int *envNdx, bool onlyActive)
160 * Find environment variable from end of array (more likely to be
161 * active). A variable created by putenv is always active or it is not
162 * tracked in the array.
164 for (ndx = *envNdx; ndx >= 0; ndx--)
165 if (envVars[ndx].putenv) {
166 if (strncmpeq(envVars[ndx].name, name, nameLen)) {
168 return (envVars[ndx].name + nameLen +
171 } else if ((!onlyActive || envVars[ndx].active) &&
172 (envVars[ndx].nameLen == nameLen &&
173 strncmpeq(envVars[ndx].name, name, nameLen))) {
175 return (envVars[ndx].value);
183 * Using environ, returns pointer to value associated with name, if any, else
184 * NULL. Used on the original environ passed into the program.
187 __findenv_environ(const char *name, size_t nameLen)
191 /* Find variable within environ. */
192 for (envNdx = 0; environ[envNdx] != NULL; envNdx++)
193 if (strncmpeq(environ[envNdx], name, nameLen))
194 return (&(environ[envNdx][nameLen + sizeof("=") - 1]));
201 * Remove variable added by putenv() from variable tracking array.
204 __remove_putenv(int envNdx)
207 if (envVarsTotal > envNdx)
208 memmove(&(envVars[envNdx]), &(envVars[envNdx + 1]),
209 (envVarsTotal - envNdx) * sizeof (*envVars));
210 memset(&(envVars[envVarsTotal]), 0, sizeof (*envVars));
217 * Deallocate the environment built from environ as well as environ then set
218 * both to NULL. Eases debugging of memory leaks.
221 __clean_env(bool freeVars)
225 /* Deallocate environment and environ if created by *env(). */
226 if (envVars != NULL) {
227 for (envNdx = envVarsTotal - 1; envNdx >= 0; envNdx--)
228 /* Free variables or deactivate them. */
229 if (envVars[envNdx].putenv) {
231 __remove_putenv(envNdx);
234 free(envVars[envNdx].name);
236 envVars[envNdx].active = false;
244 /* Restore original environ if it has not updated by program. */
245 if (origEnviron != NULL) {
246 if (environ == intEnviron)
247 environ = origEnviron;
259 * Using the environment, rebuild the environ array for use by other C library
260 * calls that depend upon it.
263 __rebuild_environ(int newEnvironSize)
270 /* Resize environ. */
271 if (newEnvironSize > environSize) {
272 tmpEnvironSize = newEnvironSize * 2;
273 tmpEnviron = realloc(intEnviron, sizeof (*intEnviron) *
274 (tmpEnvironSize + 1));
275 if (tmpEnviron == NULL)
277 environSize = tmpEnvironSize;
278 intEnviron = tmpEnviron;
280 envActive = newEnvironSize;
282 /* Assign active variables to environ. */
283 for (envNdx = envVarsTotal - 1, environNdx = 0; envNdx >= 0; envNdx--)
284 if (envVars[envNdx].active)
285 intEnviron[environNdx++] = envVars[envNdx].name;
286 intEnviron[environNdx] = NULL;
288 /* Always set environ which may have been replaced by program. */
289 environ = intEnviron;
296 * Enlarge new environment.
302 struct envVars *tmpEnvVars;
305 if (envVarsTotal > envVarsSize) {
306 newEnvVarsSize = envVarsTotal * 2;
307 tmpEnvVars = realloc(envVars, sizeof (*envVars) *
309 if (tmpEnvVars == NULL) {
313 envVarsSize = newEnvVarsSize;
314 envVars = tmpEnvVars;
322 * Using environ, build an environment for use by standard C library calls.
333 /* Check for non-existant environment. */
334 if (environ == NULL || environ[0] == NULL)
337 /* Count environment variables. */
338 for (env = environ, envVarsTotal = 0; *env != NULL; env++)
340 envVarsSize = envVarsTotal * 2;
342 /* Create new environment. */
343 envVars = calloc(1, sizeof (*envVars) * envVarsSize);
347 /* Copy environ values and keep track of them. */
348 for (envNdx = envVarsTotal - 1; envNdx >= 0; envNdx--) {
349 envVars[envNdx].putenv = false;
350 envVars[envNdx].name =
351 strdup(environ[envVarsTotal - envNdx - 1]);
352 if (envVars[envNdx].name == NULL)
354 envVars[envNdx].value = strchr(envVars[envNdx].name, '=');
355 if (envVars[envNdx].value != NULL) {
356 envVars[envNdx].value++;
357 envVars[envNdx].valueSize =
358 strlen(envVars[envNdx].value);
360 __env_warnx(CorruptEnvValueMsg, envVars[envNdx].name,
361 strlen(envVars[envNdx].name));
367 * Find most current version of variable to make active. This
368 * will prevent multiple active variables from being created
369 * during this initialization phase.
371 nameLen = envVars[envNdx].value - envVars[envNdx].name - 1;
372 envVars[envNdx].nameLen = nameLen;
373 activeNdx = envVarsTotal - 1;
374 if (__findenv(envVars[envNdx].name, nameLen, &activeNdx,
376 __env_warnx(CorruptEnvFindMsg, envVars[envNdx].name,
381 envVars[activeNdx].active = true;
384 /* Create a new environ. */
385 origEnviron = environ;
387 if (__rebuild_environ(envVarsTotal) == 0)
400 * Destructor function with default argument to __clean_env().
403 __clean_env_destructor(void)
412 * Returns the value of a variable or NULL if none are found.
415 getenv(const char *name)
420 /* Check for malformed name. */
421 if (name == NULL || (nameLen = __strleneq(name)) == 0) {
427 * An empty environment (environ or its first value) regardless if
428 * environ has been copied before will return a NULL.
430 * If the environment is not empty, find an environment variable via
431 * environ if environ has not been copied via an *env() call or been
432 * replaced by a running program, otherwise, use the rebuilt
435 if (environ == NULL || environ[0] == NULL)
437 else if (envVars == NULL || environ != intEnviron)
438 return (__findenv_environ(name, nameLen));
440 envNdx = envVarsTotal - 1;
441 return (__findenv(name, nameLen, &envNdx, true));
447 * Set the value of a variable. Older settings are labeled as inactive. If an
448 * older setting has enough room to store the new value, it will be reused. No
449 * previous variables are ever freed here to avoid causing a segmentation fault
452 * The variables nameLen and valueLen are passed into here to allow the caller
453 * to calculate the length by means besides just strlen().
456 __setenv(const char *name, size_t nameLen, const char *value, int overwrite)
464 /* Find existing environment variable large enough to use. */
465 envNdx = envVarsTotal - 1;
466 newEnvActive = envActive;
467 valueLen = strlen(value);
469 if (__findenv(name, nameLen, &envNdx, false) != NULL) {
470 /* Deactivate entry if overwrite is allowed. */
471 if (envVars[envNdx].active) {
474 envVars[envNdx].active = false;
478 /* putenv() created variable cannot be reused. */
479 if (envVars[envNdx].putenv)
480 __remove_putenv(envNdx);
482 /* Entry is large enough to reuse. */
483 else if (envVars[envNdx].valueSize >= valueLen)
487 /* Create new variable if none was found of sufficient size. */
489 /* Enlarge environment. */
490 envNdx = envVarsTotal;
491 if (!__enlarge_env())
494 /* Create environment entry. */
495 envVars[envNdx].name = malloc(nameLen + sizeof ("=") +
497 if (envVars[envNdx].name == NULL) {
501 envVars[envNdx].nameLen = nameLen;
502 envVars[envNdx].valueSize = valueLen;
504 /* Save name of name/value pair. */
505 env = stpcpy(envVars[envNdx].name, name);
506 if ((envVars[envNdx].name)[nameLen] != '=')
507 env = stpcpy(env, "=");
510 env = envVars[envNdx].value;
512 /* Save value of name/value pair. */
514 envVars[envNdx].value = env;
515 envVars[envNdx].active = true;
518 /* No need to rebuild environ if an active variable was reused. */
519 if (reuse && newEnvActive == envActive)
522 return (__rebuild_environ(newEnvActive));
527 * If the program attempts to replace the array of environment variables
528 * (environ) environ or sets the first varible to NULL, then deactivate all
529 * variables and merge in the new list from environ.
532 __merge_environ(void)
538 * Internally-built environ has been replaced or cleared (detected by
539 * using the count of active variables against a NULL as the first value
540 * in environ). Clean up everything.
542 if (intEnviron != NULL && (environ != intEnviron || (envActive > 0 &&
543 environ[0] == NULL))) {
544 /* Deactivate all environment variables. */
551 * Insert new environ into existing, yet deactivated,
554 origEnviron = environ;
555 if (origEnviron != NULL)
556 for (env = origEnviron; *env != NULL; env++) {
557 if ((equals = strchr(*env, '=')) == NULL) {
558 __env_warnx(CorruptEnvValueMsg, *env,
563 if (__setenv(*env, equals - *env, equals + 1,
574 * The exposed setenv() that peforms a few tests before calling the function
575 * (__setenv()) that does the actual work of inserting a variable into the
579 setenv(const char *name, const char *value, int overwrite)
583 /* Check for malformed name. */
584 if (name == NULL || (nameLen = __strleneq(name)) == 0) {
589 /* Initialize environment. */
590 if (__merge_environ() == -1 || (envVars == NULL && __build_env() == -1))
593 return (__setenv(name, nameLen, value, overwrite));
598 * Insert a "name=value" string into the environment. Special settings must be
599 * made to keep setenv() from reusing this memory block and unsetenv() from
600 * allowing it to be tracked.
610 /* Check for malformed argument. */
611 if (string == NULL || (equals = strchr(string, '=')) == NULL ||
612 (nameLen = equals - string) == 0) {
617 /* Initialize environment. */
618 if (__merge_environ() == -1 || (envVars == NULL && __build_env() == -1))
621 /* Deactivate previous environment variable. */
622 envNdx = envVarsTotal - 1;
623 newEnvActive = envActive;
624 if (__findenv(string, nameLen, &envNdx, true) != NULL) {
625 /* Reuse previous putenv slot. */
626 if (envVars[envNdx].putenv) {
627 envVars[envNdx].name = string;
628 return (__rebuild_environ(envActive));
631 envVars[envNdx].active = false;
635 /* Enlarge environment. */
636 envNdx = envVarsTotal;
637 if (!__enlarge_env())
640 /* Create environment entry. */
641 envVars[envNdx].name = string;
642 envVars[envNdx].nameLen = -1;
643 envVars[envNdx].value = NULL;
644 envVars[envNdx].valueSize = -1;
645 envVars[envNdx].putenv = true;
646 envVars[envNdx].active = true;
649 return (__rebuild_environ(newEnvActive));
654 * Unset variable with the same name by flagging it as inactive. No variable is
658 unsetenv(const char *name)
663 /* Check for malformed name. */
664 if (name == NULL || (nameLen = __strleneq(name)) == 0) {
669 /* Initialize environment. */
670 if (__merge_environ() == -1 || (envVars == NULL && __build_env() == -1))
673 /* Deactivate specified variable. */
674 envNdx = envVarsTotal - 1;
675 if (__findenv(name, nameLen, &envNdx, true) != NULL) {
676 envVars[envNdx].active = false;
677 if (envVars[envNdx].putenv)
678 __remove_putenv(envNdx);
679 __rebuild_environ(envActive - 1);