Home | History | Annotate | Line # | Download | only in stdlib
_env.c revision 1.2
      1 /*	$NetBSD: _env.c,v 1.2 2010/11/14 22:04:36 tron Exp $ */
      2 
      3 /*-
      4  * Copyright (c) 2010 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Matthias Scheler.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     29  * POSSIBILITY OF SUCH DAMAGE.
     30  */
     31 
     32 #include <sys/rbtree.h>
     33 
     34 #include <assert.h>
     35 #include <errno.h>
     36 #include <limits.h>
     37 #include <stdlib.h>
     38 #include <stddef.h>
     39 #include <string.h>
     40 
     41 #include "env.h"
     42 #include "reentrant.h"
     43 #include "local.h"
     44 
     45 /*
     46  * Red-Black tree node for tracking memory used by environment variables.
     47  * The tree is sorted by the address of the nodes themselves.
     48  */
     49 typedef struct {
     50 	rb_node_t	rb_node;
     51 	size_t		length;
     52 	char		data[];
     53 } env_node_t;
     54 
     55 /* Compare functions for above tree. */
     56 static signed int env_tree_compare_nodes(void *, const void *, const void *);
     57 static signed int env_tree_compare_key(void *, const void *, const void *);
     58 
     59 /* Operations for above tree. */
     60 static const rb_tree_ops_t env_tree_ops = {
     61 	.rbto_compare_nodes = env_tree_compare_nodes,
     62 	.rbto_compare_key = env_tree_compare_key,
     63 	.rbto_node_offset = offsetof(env_node_t, rb_node),
     64 	.rbto_context = NULL
     65 };
     66 
     67 /* The single instance of above tree. */
     68 static rb_tree_t	env_tree;
     69 
     70 /* The allocated environment. */
     71 static char	**allocated_environ;
     72 static size_t	allocated_environ_size;
     73 
     74 #define	ENV_ARRAY_SIZE_MIN	16
     75 
     76 /* The lock protecting accces to the environment. */
     77 #ifdef _REENTRANT
     78 static rwlock_t env_lock = RWLOCK_INITIALIZER;
     79 #endif
     80 
     81 /* Compatibility function. */
     82 char *__findenv(const char *name, int *offsetp);
     83 
     84 __warn_references(__findenv,
     85     "warning: __findenv is an internal obsolete function.")
     86 
     87 /* Our initialization function. */
     88 void __libc_env_init(void);
     89 
     90 /*ARGSUSED*/
     91 static signed int
     92 env_tree_compare_nodes(void *ctx, const void *node_a, const void *node_b)
     93 {
     94 	uintptr_t addr_a, addr_b;
     95 
     96 	addr_a = (uintptr_t)node_a;
     97 	addr_b = (uintptr_t)node_b;
     98 
     99 	if (addr_a < addr_b)
    100 		return -1;
    101 
    102 	if (addr_a > addr_b)
    103 		return 1;
    104 
    105 	return 0;
    106 }
    107 
    108 static signed int
    109 env_tree_compare_key(void *ctx, const void *node, const void *key)
    110 {
    111 	return env_tree_compare_nodes(ctx, node,
    112 	    (const uint8_t *)key - offsetof(env_node_t, data));
    113 }
    114 
    115 /*
    116  * Determine the of the name in an environment string. Return 0 if the
    117  * name is not valid.
    118  */
    119 size_t
    120 __envvarnamelen(const char *str, bool withequal)
    121 {
    122 	size_t l_name;
    123 
    124 	if (str == NULL)
    125 		return 0;
    126 
    127 	l_name = strcspn(str, "=");
    128 	if (l_name == 0)
    129 		return 0;
    130 
    131 	if (withequal) {
    132 		if (str[l_name] != '=')
    133 			return 0;
    134 	} else {
    135 		if (str[l_name] == '=')
    136 			return 0;
    137 	}
    138 
    139 	return l_name;
    140 }
    141 
    142 /*
    143  * Free memory occupied by environment variable if possible. This function
    144  * must be called with the environment write locked.
    145  */
    146 void
    147 __freeenvvar(char *envvar)
    148 {
    149 	env_node_t *node;
    150 
    151 	_DIAGASSERT(envvar != NULL);
    152 	node = rb_tree_find_node(&env_tree, envvar);
    153 	if (node != NULL) {
    154 		rb_tree_remove_node(&env_tree, node);
    155 		free(node);
    156 	}
    157 }
    158 
    159 /*
    160  * Allocate memory for an environment variable. This function must be called
    161  * with the environment write locked.
    162  */
    163 char *
    164 __allocenvvar(size_t length)
    165 {
    166 	env_node_t *node;
    167 
    168 	node = malloc(sizeof(*node) + length);
    169 	if (node != NULL) {
    170 		node->length = length;
    171 		rb_tree_insert_node(&env_tree, node);
    172 		return node->data;
    173 	} else {
    174 		return NULL;
    175 	}
    176 }
    177 
    178 /*
    179  * Check whether an enviroment variable is writable. This function must be
    180  * called with the environment write locked as the caller will probably
    181  * overwrite the enviroment variable afterwards.
    182  */
    183 bool
    184 __canoverwriteenvvar(char *envvar, size_t length)
    185 {
    186 	env_node_t *node;
    187 
    188 	_DIAGASSERT(envvar != NULL);
    189 
    190 	node = rb_tree_find_node(&env_tree, envvar);
    191 	return (node != NULL && length <= node->length);
    192 }
    193 
    194 /*
    195  * Get a (new) slot in the environment. This function must be called with
    196  * the environment write locked.
    197  */
    198 ssize_t
    199 __getenvslot(const char *name, size_t l_name, bool allocate)
    200 {
    201 	size_t new_size, num_entries, required_size;
    202 	char **new_environ;
    203 
    204 	/* Search for an existing environment variable of the given name. */
    205 	num_entries = 0;
    206 	while (environ[num_entries] != NULL) {
    207 		if (strncmp(environ[num_entries], name, l_name) == 0 &&
    208 		    environ[num_entries][l_name] == '=') {
    209 			/* We found a match. */
    210 			return num_entries;
    211 		}
    212 		num_entries ++;
    213 	}
    214 
    215 	/* No match found, return if we don't want to allocate a new slot. */
    216 	if (!allocate)
    217 		return -1;
    218 
    219 	/* Create a new slot in the environment. */
    220 	required_size = num_entries + 1;
    221 	if (environ == allocated_environ &&
    222 	    required_size < allocated_environ_size) {
    223 		size_t offset;
    224 
    225 		/*
    226 		 * Scrub the environment if somebody erased its contents by
    227 		 * e.g. setting environ[0] to NULL.
    228 		 */
    229 		offset = required_size;
    230 		while (offset < allocated_environ_size &&
    231 		    environ[offset] != NULL) {
    232 			__freeenvvar(environ[offset]);
    233 			environ[offset] = NULL;
    234 			offset++;
    235 		}
    236 
    237 		/* Return a free slot. */
    238 		return num_entries;
    239 	}
    240 
    241 	/* Determine size of a new environment array. */
    242 	new_size = ENV_ARRAY_SIZE_MIN;
    243 	while (new_size <= required_size)
    244 		new_size <<= 1;
    245 
    246 	/* Allocate a new environment array. */
    247 	if (environ == allocated_environ) {
    248 		new_environ = realloc(environ,
    249 		    new_size * sizeof(*new_environ));
    250 		if (new_environ == NULL)
    251 			return -1;
    252 	} else {
    253 		free(allocated_environ);
    254 		allocated_environ = NULL;
    255 		allocated_environ_size = 0;
    256 
    257 		new_environ = malloc(new_size * sizeof(*new_environ));
    258 		if (new_environ == NULL)
    259 			return -1;
    260 		(void)memcpy(new_environ, environ,
    261 		    num_entries * sizeof(*new_environ));
    262 	}
    263 
    264 	/* Clear remaining entries. */
    265 	(void)memset(&new_environ[num_entries], 0,
    266 	    (new_size - num_entries) * sizeof(*new_environ));
    267 
    268 	/* Use the new environent array. */
    269 	environ = allocated_environ = new_environ;
    270 	allocated_environ_size = new_size;
    271 
    272 	/* Return a free slot. */
    273 	return num_entries;
    274 }
    275 
    276 /* Find a string in the environment. */
    277 char *
    278 __findenvvar(const char *name, size_t l_name)
    279 {
    280 	ssize_t offset;
    281 
    282 	offset = __getenvslot(name, l_name, false);
    283 	return (offset != -1) ? environ[offset] + l_name + 1 : NULL;
    284 }
    285 
    286 /* Compatibility interface, do *not* call this function. */
    287 char *
    288 __findenv(const char *name, int *offsetp)
    289 {
    290 	size_t l_name;
    291 	ssize_t offset;
    292 
    293 	l_name = __envvarnamelen(name, false);
    294 	if (l_name == 0)
    295 		return NULL;
    296 
    297 	offset = __getenvslot(name, l_name, false);
    298 	if (offset < 0 || offset > INT_MAX)
    299 		return NULL;
    300 
    301 	*offsetp = (int)offset;
    302 	return environ[offset] + l_name + 1;
    303 }
    304 
    305 #ifdef _REENTRANT
    306 
    307 /* Lock the environment for read. */
    308 bool
    309 __readlockenv(void)
    310 {
    311 	int error;
    312 
    313 	error = rwlock_rdlock(&env_lock);
    314 	if (error == 0)
    315 		return true;
    316 
    317 	errno = error;
    318 	return false;
    319 }
    320 
    321 /* Lock the environment for write. */
    322 bool
    323 __writelockenv(void)
    324 {
    325 	int error;
    326 
    327 	error = rwlock_wrlock(&env_lock);
    328 	if (error == 0)
    329 		return true;
    330 
    331 	errno = error;
    332 	return false;
    333 }
    334 
    335 /* Unlock the environment for write. */
    336 bool
    337 __unlockenv(void)
    338 {
    339 	int error;
    340 
    341 	error = rwlock_unlock(&env_lock);
    342 	if (error == 0)
    343 		return true;
    344 
    345 	errno = error;
    346 	return false;
    347 }
    348 
    349 #endif
    350 
    351 /* Initialize environment memory RB tree. */
    352 void
    353 __libc_env_init(void)
    354 {
    355 	rb_tree_init(&env_tree, &env_tree_ops);
    356 }
    357