Skip to content

Commit 239ecb6

Browse files
committed
Back to original implementation
Signed-off-by: Michael Carroll <mjcarroll@intrinsic.ai>
1 parent c0f0542 commit 239ecb6

File tree

1 file changed

+7
-42
lines changed

1 file changed

+7
-42
lines changed

src/Environment.cc

+7-42
Original file line numberDiff line numberDiff line change
@@ -22,14 +22,7 @@
2222
#include <string>
2323
#include <vector>
2424

25-
#ifdef _WIN32
26-
#include <winbase.h>
27-
#include <windows.h>
28-
#endif
29-
30-
#ifndef _WIN32
3125
extern char ** environ;
32-
#endif
3326

3427
namespace gz
3528
{
@@ -134,55 +127,27 @@ bool clearenv()
134127
/////////////////////////////////////////////////
135128
EnvironmentMap env()
136129
{
137-
EnvironmentMap ret;
130+
// Portable method for reading environment variables
131+
// Ref: https://stackoverflow.com/a/71483564/460065
132+
char **currentEnv {nullptr};
138133
#ifdef _WIN32
139-
DWORD environment_block_size = GetEnvironmentBlockSize();
140-
141-
// Allocate a buffer to store the environment block.
142-
LPCH env_buf = (LPCH)malloc(environment_block_size);
143-
if (env_buf == nullptr) {
144-
return {};
145-
}
146-
// Get the environment block.
147-
if (!GetEnvironmentVariables(env_buf, environment_block_size)) {
148-
free(env_buf);
149-
return {};
150-
}
151-
// Parse the environment block into an unordered_map.
152-
LPCH env_var = env_buf;
153-
while (*env_var != '\0') {
154-
// Split the environment variable into a key-value pair.
155-
char* equal_sign = strchr(env_var, '=');
156-
if (equal_sign == nullptr) {
157-
continue;
158-
}
159-
160-
// Get the key and value of the environment variable.
161-
std::string key(env_var, equal_sign - env_var);
162-
std::string value(equal_sign + 1);
163-
164-
// Add the key-value pair to the unordered_map.
165-
ret[key] = value;
166-
167-
// Advance to the next environment variable.
168-
env_var = equal_sign + 1;
169-
}
170-
free(env_buf);
134+
currentEnv = *__p_environ();
171135
#else
172-
char **currentEnv = environ;
136+
currentEnv = environ;
137+
#endif
173138
// In the case that clearenv() was just called
174139
// currentEnv will be nullptr
175140
if (currentEnv == nullptr)
176141
return {};
177142

143+
EnvironmentMap ret;
178144
for (; *currentEnv; ++currentEnv)
179145
{
180146
std::string var(*currentEnv);
181147
auto key = var.substr(0, var.find('='));
182148
var.erase(0, var.find('=') + 1);
183149
ret[key] = var;
184150
}
185-
#endif
186151
return ret;
187152
}
188153

0 commit comments

Comments
 (0)