aboutsummaryrefslogtreecommitdiffstats
path: root/libexec_copy_environ.c
blob: 2c7e19f3c0801de068b3bbf5721631f6bc11c02d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/* 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