blob: 0a458968669a6280f070271a80a6069af9152b43 [file] [log] [blame]
Rich Felker0b44a032011-02-12 00:22:29 -05001#include <stdlib.h>
2#include <string.h>
3#include <errno.h>
4
5int __putenv(char *s, int a);
6
7int setenv(const char *var, const char *value, int overwrite)
8{
9 char *s;
10 int l1, l2;
11
Rich Felker649af9f2011-07-28 20:43:40 -040012 if (!var || !*var || strchr(var, '=')) {
Rich Felker0b44a032011-02-12 00:22:29 -050013 errno = EINVAL;
14 return -1;
15 }
16 if (!overwrite && getenv(var)) return 0;
17
18 l1 = strlen(var);
19 l2 = strlen(value);
20 s = malloc(l1+l2+2);
Rich Felker54378702013-10-04 15:49:55 -040021 if (s) {
22 memcpy(s, var, l1);
23 s[l1] = '=';
24 memcpy(s+l1+1, value, l2);
25 s[l1+l2+1] = 0;
26 if (!__putenv(s, 1)) return 0;
Rich Felker0b44a032011-02-12 00:22:29 -050027 }
Rich Felker54378702013-10-04 15:49:55 -040028 free(s);
29 errno = ENOMEM;
30 return -1;
Rich Felker0b44a032011-02-12 00:22:29 -050031}