Skip to content

Local code intelligence for developers and AI agents. Connect code, docs and infrastructure in a persistent graph, with CBM Lens, MCP tools, agent integrations and change-aware test selection.

fix(windows): set UTF-8 environment values through wide CRT

News255463126650
diff --git a/src/foundation/compat.h b/src/foundation/compat.h
index 821d901f0..3080930f8 100644
--- a/src/foundation/compat.h
+++ b/src/foundation/compat.h
@@ -166,11 +166,9 @@ static inline int cbm_setenv(const char *name, const char *value, int overwrite)
free(wide_value);
return EINVAL;
}
- /* Keep the CRT's narrow environment useful for legacy getenv callers,
- * then repair the process-wide Windows environment with the actual UTF-16
- * value. _putenv_s alone routes UTF-8 path bytes through the active ANSI
- * code page, which corrupts non-ASCII cache roots inherited by children. */
- int status = _putenv_s(name, value);
+ /* _putenv_s can reject UTF-8 bytes outside the active ANSI code page.
+ * Narrow getenv returns bytes in that code page after this wide update. */
+ int status = _wputenv_s(wide_name, wide_value);
if (status == 0 && !SetEnvironmentVariableW(wide_name, wide_value)) {
status = EINVAL;
}
diff --git a/tests/test_platform.c b/tests/test_platform.c
index 5995a4b01..77d325d91 100644
--- a/tests/test_platform.c
+++ b/tests/test_platform.c
@@ -869,8 +869,8 @@ TEST(platform_env_long_refuses_what_it_cannot_read) {
* setter must update that same wide environment; _putenv_s alone interprets
* UTF-8 path bytes through the active ANSI code page. */
TEST(platform_setenv_preserves_utf8_in_wide_environment) {
- static const char utf8[] = "C:/cbm-cache-\xce\x94-\xe6\x97\xa5\xe6\x9c\xac";
- static const wchar_t wide[] = L"C:/cbm-cache-\u0394-\u65e5\u672c";
+ static const char utf8[] = "C:/cbm-cache-\xce\x94-\xe6\x97\xa5\xe6\x9c\xac-\xe4\xb8\x81";
+ static const wchar_t wide[] = L"C:/cbm-cache-\u0394-\u65e5\u672c-\u4e01";
ASSERT_EQ(cbm_setenv("CBM_CACHE_DIR", utf8, 1), 0);
wchar_t observed_wide[128];
ASSERT_EQ(GetEnvironmentVariableW(L"CBM_CACHE_DIR", observed_wide, 128), (DWORD)(wcslen(wide)));
@@ -878,6 +878,14 @@ TEST(platform_setenv_preserves_utf8_in_wide_environment) {
char observed_utf8[128];
ASSERT_NOT_NULL(cbm_safe_getenv("CBM_CACHE_DIR", observed_utf8, sizeof(observed_utf8), NULL));
ASSERT_STR_EQ(observed_utf8, utf8);
+ /* Narrow getenv must agree with the CRT's active ANSI code page. */
+ char expected_narrow[128];
+ ASSERT_GT(WideCharToMultiByte(CP_ACP, 0, wide, -1, expected_narrow,
+ (int)sizeof(expected_narrow), NULL, NULL),
+ 0);
+ const char *observed_narrow = getenv("CBM_CACHE_DIR");
+ ASSERT_NOT_NULL(observed_narrow);
+ ASSERT_STR_EQ(observed_narrow, expected_narrow);
(void)cbm_unsetenv("CBM_CACHE_DIR");
PASS();
}