From 64ae8d07bd6640bcf5de0c5c756fa667ea06e643 Mon Sep 17 00:00:00 2001 From: "K. Lange" Date: Tue, 14 Aug 2018 14:39:48 +0900 Subject: [PATCH] fixup environ handling --- libc/main.c | 39 +++++++++++++++++++++++++++++++++++ libc/stdlib/putenv.c | 48 +++++++++++++------------------------------- 2 files changed, 53 insertions(+), 34 deletions(-) diff --git a/libc/main.c b/libc/main.c index 557bd0ad..5badac43 100644 --- a/libc/main.c +++ b/libc/main.c @@ -1,5 +1,6 @@ #include #include +#include #include #include @@ -77,6 +78,44 @@ static void _libc_init(void) { break; } } + if (!environ) { + environ = malloc(sizeof(char *) * 4); + environ[0] = NULL; + environ[1] = NULL; + environ[2] = NULL; + environ[3] = NULL; + _environ_size = 4; + } else { + /* Find actual size */ + int size = 0; + + char ** tmp = environ; + while (*tmp) { + size++; + tmp++; + } + + if (size < 4) { + _environ_size = 4; + } else { + /* Multiply by two */ + _environ_size = size * 2; + } + + char ** new_environ = malloc(sizeof(char*) * _environ_size); + int i = 0; + while (i < _environ_size && environ[i]) { + new_environ[i] = environ[i]; + i++; + } + + while (i < _environ_size) { + new_environ[i] = NULL; + i++; + } + + environ = new_environ; + } _argv_0 = __get_argv()[0]; } diff --git a/libc/stdlib/putenv.c b/libc/stdlib/putenv.c index 6cbea154..b41146e0 100644 --- a/libc/stdlib/putenv.c +++ b/libc/stdlib/putenv.c @@ -15,34 +15,6 @@ static int why_no_strnstr(char * a, char * b, int n) { } int putenv(char * string) { - if (_environ_size == 0) { - /* Find actual size */ - int size = 0; - - char ** tmp = environ; - while (*tmp) { - size++; - tmp++; - } - - /* Multiply by two */ - _environ_size = size * 2; - - char ** new_environ = malloc(sizeof(char*) * _environ_size); - int i = 0; - while (environ[i]) { - new_environ[i] = environ[i]; - i++; - } - - while (i < _environ_size) { - new_environ[i] = NULL; - i++; - } - - environ = new_environ; - } - char name[strlen(string)]; strcpy(name, string); char * c = strchr(name, '='); @@ -54,19 +26,27 @@ int putenv(char * string) { int s = strlen(name); int i; - for (i = 0; environ[i]; ++i) { + for (i = 0; i < (_environ_size - 1) && environ[i]; ++i) { if (!why_no_strnstr(name, environ[i], s)) { environ[i] = string; return 0; } } /* Not found */ - if (i >= _environ_size) { - environ = realloc(environ, _environ_size * 2); - for (int i = _environ_size; i < _environ_size * 2; ++i) { - environ[i] = NULL; + if (i == _environ_size - 1) { + int _new_environ_size = _environ_size * 2; + char ** new_environ = malloc(sizeof(char*) * _new_environ_size); + int j = 0; + while (j < _new_environ_size && environ[j]) { + new_environ[j] = environ[j]; + j++; } - _environ_size *= 2; + while (j < _new_environ_size) { + new_environ[j] = NULL; + j++; + } + _environ_size = _new_environ_size; + environ = new_environ; } environ[i] = string;