Skip to content

Commit 2554631

Browse files
committed
fix(windows): set UTF-8 environment values through wide CRT
Signed-off-by: News <knewstimek@users.noreply.github.com>
1 parent e783f73 commit 2554631

2 files changed

Lines changed: 13 additions & 7 deletions

File tree

‎src/foundation/compat.h‎

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -166,11 +166,9 @@ static inline int cbm_setenv(const char *name, const char *value, int overwrite)
166166
free(wide_value);
167167
return EINVAL;
168168
}
169-
/* Keep the CRT's narrow environment useful for legacy getenv callers,
170-
* then repair the process-wide Windows environment with the actual UTF-16
171-
* value. _putenv_s alone routes UTF-8 path bytes through the active ANSI
172-
* code page, which corrupts non-ASCII cache roots inherited by children. */
173-
int status = _putenv_s(name, value);
169+
/* _putenv_s can reject UTF-8 bytes outside the active ANSI code page.
170+
* Narrow getenv returns bytes in that code page after this wide update. */
171+
int status = _wputenv_s(wide_name, wide_value);
174172
if (status == 0 && !SetEnvironmentVariableW(wide_name, wide_value)) {
175173
status = EINVAL;
176174
}

‎tests/test_platform.c‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -869,15 +869,23 @@ TEST(platform_env_long_refuses_what_it_cannot_read) {
869869
* setter must update that same wide environment; _putenv_s alone interprets
870870
* UTF-8 path bytes through the active ANSI code page. */
871871
TEST(platform_setenv_preserves_utf8_in_wide_environment) {
872-
static const char utf8[] = "C:/cbm-cache-\xce\x94-\xe6\x97\xa5\xe6\x9c\xac";
873-
static const wchar_t wide[] = L"C:/cbm-cache-\u0394-\u65e5\u672c";
872+
static const char utf8[] = "C:/cbm-cache-\xce\x94-\xe6\x97\xa5\xe6\x9c\xac-\xe4\xb8\x81";
873+
static const wchar_t wide[] = L"C:/cbm-cache-\u0394-\u65e5\u672c-\u4e01";
874874
ASSERT_EQ(cbm_setenv("CBM_CACHE_DIR", utf8, 1), 0);
875875
wchar_t observed_wide[128];
876876
ASSERT_EQ(GetEnvironmentVariableW(L"CBM_CACHE_DIR", observed_wide, 128), (DWORD)(wcslen(wide)));
877877
ASSERT_EQ(wcscmp(observed_wide, wide), 0);
878878
char observed_utf8[128];
879879
ASSERT_NOT_NULL(cbm_safe_getenv("CBM_CACHE_DIR", observed_utf8, sizeof(observed_utf8), NULL));
880880
ASSERT_STR_EQ(observed_utf8, utf8);
881+
/* Narrow getenv must agree with the CRT's active ANSI code page. */
882+
char expected_narrow[128];
883+
ASSERT_GT(WideCharToMultiByte(CP_ACP, 0, wide, -1, expected_narrow,
884+
(int)sizeof(expected_narrow), NULL, NULL),
885+
0);
886+
const char *observed_narrow = getenv("CBM_CACHE_DIR");
887+
ASSERT_NOT_NULL(observed_narrow);
888+
ASSERT_STR_EQ(observed_narrow, expected_narrow);
881889
(void)cbm_unsetenv("CBM_CACHE_DIR");
882890
PASS();
883891
}

0 commit comments

Comments
 (0)