1 #include <stdlib.h>
2 #include <string.h>
3 #include <errno.h>
4
__env_rm_add(char * old,char * new)5 void __env_rm_add(char *old, char *new)
6 {
7 static char **env_alloced;
8 static size_t env_alloced_n;
9 for (size_t i=0; i < env_alloced_n; i++)
10 if (env_alloced[i] == old) {
11 env_alloced[i] = new;
12 free(old);
13 return;
14 } else if (!env_alloced[i] && new) {
15 env_alloced[i] = new;
16 new = 0;
17 }
18 if (!new) return;
19 char **t = realloc(env_alloced, sizeof *t * (env_alloced_n+1));
20 if (!t) return;
21 (env_alloced = t)[env_alloced_n++] = new;
22 }
23
setenv(const char * var,const char * value,int overwrite)24 int setenv(const char *var, const char *value, int overwrite)
25 {
26 char *s;
27 size_t l1, l2;
28
29 if (!var || !(l1 = __strchrnul(var, '=') - var) || var[l1]) {
30 errno = EINVAL;
31 return -1;
32 }
33 if (!overwrite && getenv(var)) return 0;
34
35 l2 = strlen(value);
36 s = malloc(l1+l2+2);
37 if (!s) return -1;
38 memcpy(s, var, l1);
39 s[l1] = '=';
40 memcpy(s+l1+1, value, l2+1);
41 return __putenv(s, l1, s);
42 }
43