1#include <stdlib.h> 2#include <string.h> 3 4#include "libc.h" 5#include "env_impl.h" 6 7char** __env_map; 8 9int __putenv(char* s, int a) { 10 int i = 0, j = 0; 11 char* z = strchr(s, '='); 12 char** newenv = 0; 13 char** newmap = 0; 14 static char** oldenv; 15 16 if (!z) 17 return unsetenv(s); 18 if (z == s) 19 return -1; 20 for (; __environ[i] && memcmp(s, __environ[i], z - s + 1); i++) 21 ; 22 if (a) { 23 if (!__env_map) { 24 __env_map = calloc(2, sizeof(char*)); 25 if (__env_map) 26 __env_map[0] = s; 27 } else { 28 for (; __env_map[j] && __env_map[j] != __environ[i]; j++) 29 ; 30 if (!__env_map[j]) { 31 newmap = realloc(__env_map, sizeof(char*) * (j + 2)); 32 if (newmap) { 33 __env_map = newmap; 34 __env_map[j] = s; 35 __env_map[j + 1] = NULL; 36 } 37 } else { 38 free(__env_map[j]); 39 __env_map[j] = s; 40 } 41 } 42 } 43 if (!__environ[i]) { 44 newenv = malloc(sizeof(char*) * (i + 2)); 45 if (!newenv) { 46 if (a && __env_map) 47 __env_map[j] = 0; 48 return -1; 49 } 50 memcpy(newenv, __environ, sizeof(char*) * i); 51 newenv[i] = s; 52 newenv[i + 1] = 0; 53 __environ = newenv; 54 free(oldenv); 55 oldenv = __environ; 56 } 57 58 __environ[i] = s; 59 return 0; 60} 61 62int putenv(char* s) { 63 return __putenv(s, 0); 64} 65