| 1 | #include <stdlib.h> |
| 2 | #include <string.h> |
| 3 | #include <unistd.h> |
| 4 | |
| 5 | static void dummy(char *old, char *new) {} |
| 6 | weak_alias(dummy, __env_rm_add); |
| 7 | |
| 8 | int __putenv(char *s, size_t l, char *r) |
| 9 | { |
| 10 | #ifdef __wasilibc_unmodified_upstream // Lazy environment variable init. |
| 11 | #else |
| 12 | // This specialized header is included within the function body to arranges for |
| 13 | // the environment variables to be lazily initialized. It redefined `__environ`, |
| 14 | // so don't remove or reorder it with respect to other code. |
| 15 | #include "wasi/libc-environ-compat.h" |
| 16 | #endif |
| 17 | 	size_t i=0; |
| 18 | 	if (__environ) { |
| 19 | 		for (char **e = __environ; *e; e++, i++) |
| 20 | 			if (!strncmp(s, *e, l+1)) { |
| 21 | 				char *tmp = *e; |
| 22 | 				*e = s; |
| 23 | 				__env_rm_add(tmp, r); |
| 24 | 				return 0; |
| 25 | 			} |
| 26 | 	} |
| 27 | 	static char **oldenv; |
| 28 | 	char **newenv; |
| 29 | 	if (__environ == oldenv) { |
| 30 | 		newenv = realloc(oldenv, sizeof *newenv * (i+2)); |
| 31 | 		if (!newenv) goto oom; |
| 32 | 	} else { |
| 33 | 		newenv = malloc(sizeof *newenv * (i+2)); |
| 34 | 		if (!newenv) goto oom; |
| 35 | 		if (i) memcpy(newenv, __environ, sizeof *newenv * i); |
| 36 | 		free(oldenv); |
| 37 | 	} |
| 38 | 	newenv[i] = s; |
| 39 | 	newenv[i+1] = 0; |
| 40 | 	__environ = oldenv = newenv; |
| 41 | 	if (r) __env_rm_add(0, r); |
| 42 | 	return 0; |
| 43 | oom: |
| 44 | 	free(r); |
| 45 | 	return -1; |
| 46 | } |
| 47 | |
| 48 | int putenv(char *s) |
| 49 | { |
| 50 | 	size_t l = __strchrnul(s, '=') - s; |
| 51 | 	if (!l || !s[l]) return unsetenv(s); |
| 52 | 	return __putenv(s, l, 0); |
| 53 | } |