Skip to content

Commit

Permalink
Avoid __p_error on Windows
Browse files Browse the repository at this point in the history
Signed-off-by: Michael Carroll <[email protected]>
  • Loading branch information
mjcarroll committed Nov 1, 2023
1 parent 55451cc commit 9d7eb95
Showing 1 changed file with 36 additions and 9 deletions.
45 changes: 36 additions & 9 deletions src/Environment.cc
Original file line number Diff line number Diff line change
Expand Up @@ -127,28 +127,55 @@ bool clearenv()
/////////////////////////////////////////////////
EnvironmentMap env()
{
// Portable method for reading environment variables
// Ref: https://stackoverflow.com/a/71483564/460065
char **currentEnv {nullptr};
#if defined(WIN) && (_MSC_VER >= 1900)
currentEnv = *__p_environ();
#else
currentEnv = environ;
#endif
EnvironmentMap ret;
#ifdef _WIN32
DWORD environment_block_size = GetEnvironmentBlockSize();

// Allocate a buffer to store the environment block.
LPCH env_buf = (LPCH)malloc(environment_block_size);
if (env_buf == nullptr) {
return {};
}
// Get the environment block.
if (!GetEnvironmentVariables(env_buf, environment_block_size)) {
free(env_buf);
return {};
}
// Parse the environment block into an unordered_map.
LPCH env_var = env_buf;
while (*env_var != '\0') {
// Split the environment variable into a key-value pair.
char* equal_sign = strchr(env_var, '=');
if (equal_sign == nullptr) {
continue;
}

// Get the key and value of the environment variable.
std::string key(env_var, equal_sign - env_var);
std::string value(equal_sign + 1);

// Add the key-value pair to the unordered_map.
ret[key] = value;

// Advance to the next environment variable.
env_var = equal_sign + 1;
}
free(env_buf);
#else
char **currentEnv = environ;
// In the case that clearenv() was just called
// currentEnv will be nullptr
if (currentEnv == nullptr)
return {};

EnvironmentMap ret;
for (; *currentEnv; ++currentEnv)
{
std::string var(*currentEnv);
auto key = var.substr(0, var.find('='));
var.erase(0, var.find('=') + 1);
ret[key] = var;
}
#endif
return ret;
}

Expand Down

0 comments on commit 9d7eb95

Please sign in to comment.