summaryrefslogtreecommitdiffstats
path: root/usr/klibc/setenv.c
blob: 45a7aad85b621117bfa7f6c8fc92dec12ecc4609 (plain)
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
/*
 * setenv.c
 */

#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "env.h"

int setenv(const char *name, const char *val, int overwrite)
{
	const char *z;
	char *s;
	size_t l1, l2;

	if (!name || !name[0]) {
		errno = EINVAL;
		return -1;
	}

	l1 = 0;
	for (z = name; *z; z++) {
		l1++;
		if (*z == '=') {
			errno = EINVAL;
			return -1;
		}
	}

	l2 = strlen(val);

	s = malloc(l1 + l2 + 2);
	if (!s)
		return -1;

	memcpy(s, name, l1);
	s[l1] = '=';
	memcpy(s + l1 + 1, val, l2 + 1);

	return __put_env(s, l1 + 1, overwrite);
}