diff --git a/libc/init.cpp b/libc/init.cpp index a8ac106d..dd3e8413 100644 --- a/libc/init.cpp +++ b/libc/init.cpp @@ -26,8 +26,7 @@ #include #include -extern "C" { char program_invocation_name_data[256] = ""; } -extern "C" { char* program_invocation_name = program_invocation_name_data; } +extern "C" { char* program_invocation_name; } extern "C" { char* program_invocation_short_name; } extern "C" void init_error_functions(); @@ -45,9 +44,14 @@ static char* find_last_elem(char* str) extern "C" void initialize_standard_library(int argc, char* argv[]) { - if ( argc ) - strcpy(program_invocation_name, argv[0]); - program_invocation_short_name = find_last_elem(program_invocation_name); + // We got ourselves a little bootstrap problem. We'd like these variables to + // be available during early startup - however, we can't create a copy yet + // because the heap isn't initialized yet. Instead, we'll simply point at + // the original value - we're safe since argv[0] is not supposed to be + // modified until main is run. Once we heap is up, we'll strdup. + const char* argv0 = argc ? argv[0] : ""; + program_invocation_name = (char*) argv0; + program_invocation_short_name = find_last_elem((char*) argv0); // Initialize stuff such as errno. init_error_functions(); @@ -60,4 +64,8 @@ extern "C" void initialize_standard_library(int argc, char* argv[]) // Initialize stdio. init_stdio(); + + // We can now create a copy of the program name variables safely. + program_invocation_name = strdup(program_invocation_name); + program_invocation_short_name = find_last_elem(program_invocation_name); }