Skip to content

Commit 014c5c6

Browse files
authored
修复无法获取长度超过 MAX_PATH 的环境变量值的问题 (#7)
1 parent bd0829c commit 014c5c6

File tree

1 file changed

+24
-11
lines changed

1 file changed

+24
-11
lines changed

HMCL/platform.cpp

Lines changed: 24 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -70,18 +70,31 @@ std::optional<std::pair<HLPath, std::wstring>> HLGetSelfPath() {
7070
}
7171

7272
std::optional<std::wstring> HLGetEnvVar(LPCWSTR name) {
73-
DWORD res, size = MAX_PATH;
74-
std::wstring out = {};
75-
out.resize(size);
76-
while ((res = GetEnvironmentVariableW(name, &out[0], size)) == size) {
77-
out.resize(size += MAX_PATH);
78-
}
79-
if (res != 0) {
80-
out.resize(size - MAX_PATH + res);
81-
return std::optional{out};
82-
} else {
83-
return std::nullopt;
73+
DWORD size = MAX_PATH;
74+
std::wstring out(size, L'\0');
75+
76+
while (size < 32 * 1024) {
77+
SetLastError(ERROR_SUCCESS);
78+
DWORD res = GetEnvironmentVariableW(name, &out[0], size);
79+
if (res == 0 && GetLastError() != ERROR_SUCCESS) {
80+
return std::nullopt;
81+
}
82+
83+
if (res < size) {
84+
out.resize(res);
85+
return std::optional{out};
86+
}
87+
88+
if (res == size) {
89+
// I think it's not possible, but I'm not really sure, so do something to avoid an infinite loop.
90+
size = res + 1;
91+
} else {
92+
size = res;
93+
}
94+
out.resize(size);
8495
}
96+
97+
return std::nullopt;
8598
}
8699

87100
std::optional<HLPath> HLGetEnvPath(LPCWSTR name) {

0 commit comments

Comments
 (0)