aboutsummaryrefslogblamecommitdiffstats
path: root/libexec_copy_environ.c
blob: 2c7e19f3c0801de068b3bbf5721631f6bc11c02d (plain) (tree)


















































                                                                         
/* See LICENSE file for copyright and license details. */
#include "common.h"
#ifndef TEST


int
libexec_copy_environ(struct libexec_command *cmd, const char *const *env)
{
	size_t i, n;
	char **new_env;

	if (!cmd) {
		errno = EINVAL;
		return -1;
	}

	if (!env)
		env = *(const char *const **)(void *)&environ;

	n = 0;
	while (env[n])
		n++;

	new_env = calloc((n + 1), sizeof(*cmd->environ));
	if (!new_env)
		return -1;

	for (i = 0; i < n; i++) {
		new_env[i] = strdup(env[i]);
		if (!new_env[i]) {
			while (i--)
				free(new_env[i]);
			free(new_env);
			return -1;
		}
	}

	if (cmd->environ) {
		for (i = 0; cmd->environ[i]; i++)
			free(cmd->environ[i]);
		free(cmd->environ);
	}

	cmd->environ = new_env;
	return 0;
}


#else
LIBEXEC_CONST__ int main(void) {return 0;} /* TODO test */
#endif