| 147 | /* ── setenv / unsetenv (Windows lacks them) ──────────────────── */ |
| 148 | #ifdef _WIN32 |
| 149 | static inline int cbm_setenv(const char *name, const char *value, int overwrite) { |
| 150 | (void)overwrite; |
| 151 | if (!name || !value) { |
| 152 | return EINVAL; |
| 153 | } |
| 154 | int name_chars = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, name, -1, NULL, 0); |
| 155 | int value_chars = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, value, -1, NULL, 0); |
| 156 | wchar_t *wide_name = |
| 157 | name_chars > 0 ? (wchar_t *)malloc((size_t)name_chars * sizeof(*wide_name)) : NULL; |
| 158 | wchar_t *wide_value = |
| 159 | value_chars > 0 ? (wchar_t *)malloc((size_t)value_chars * sizeof(*wide_value)) : NULL; |
| 160 | bool converted = |
| 161 | wide_name && wide_value && |
| 162 | MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, name, -1, wide_name, name_chars) > 0 && |
| 163 | MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, value, -1, wide_value, value_chars) > 0; |
| 164 | if (!converted) { |
| 165 | free(wide_name); |
| 166 | free(wide_value); |
| 167 | return EINVAL; |
| 168 | } |
| 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); |
| 174 | if (status == 0 && !SetEnvironmentVariableW(wide_name, wide_value)) { |
| 175 | status = EINVAL; |
| 176 | } |
| 177 | free(wide_name); |
| 178 | free(wide_value); |
| 179 | return status; |
| 180 | } |
| 181 | static inline int cbm_unsetenv(const char *name) { |
| 182 | if (!name) { |
| 183 | return EINVAL; |
no outgoing calls