|
22 | 22 | #include <string>
|
23 | 23 | #include <vector>
|
24 | 24 |
|
25 |
| -#ifdef _WIN32 |
26 |
| -#include <winbase.h> |
27 |
| -#include <windows.h> |
28 |
| -#endif |
29 |
| - |
30 |
| -#ifndef _WIN32 |
31 | 25 | extern char ** environ;
|
32 |
| -#endif |
33 | 26 |
|
34 | 27 | namespace gz
|
35 | 28 | {
|
@@ -134,55 +127,27 @@ bool clearenv()
|
134 | 127 | /////////////////////////////////////////////////
|
135 | 128 | EnvironmentMap env()
|
136 | 129 | {
|
137 |
| - EnvironmentMap ret; |
| 130 | + // Portable method for reading environment variables |
| 131 | + // Ref: https://stackoverflow.com/a/71483564/460065 |
| 132 | + char **currentEnv {nullptr}; |
138 | 133 | #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(); |
171 | 135 | #else
|
172 |
| - char **currentEnv = environ; |
| 136 | + currentEnv = environ; |
| 137 | +#endif |
173 | 138 | // In the case that clearenv() was just called
|
174 | 139 | // currentEnv will be nullptr
|
175 | 140 | if (currentEnv == nullptr)
|
176 | 141 | return {};
|
177 | 142 |
|
| 143 | + EnvironmentMap ret; |
178 | 144 | for (; *currentEnv; ++currentEnv)
|
179 | 145 | {
|
180 | 146 | std::string var(*currentEnv);
|
181 | 147 | auto key = var.substr(0, var.find('='));
|
182 | 148 | var.erase(0, var.find('=') + 1);
|
183 | 149 | ret[key] = var;
|
184 | 150 | }
|
185 |
| -#endif |
186 | 151 | return ret;
|
187 | 152 | }
|
188 | 153 |
|
|
0 commit comments