MCPcopy Create free account
hub / github.com/DeusData/codebase-memory-mcp / cbm_native_getenv

Function cbm_native_getenv

src/foundation/platform.c:403–468  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

401}
402
403const char *cbm_native_getenv(const char *name, char *buf, size_t buf_sz, const char *fallback) {
404 if (!name || !name[0] || !buf || buf_sz == 0) {
405 return NULL;
406 }
407 buf[0] = '\0';
408#ifdef _WIN32
409 /* #996 Layer 2: _environ holds ANSI-code-page bytes, NOT UTF-8. A
410 * non-ASCII value (USERPROFILE of C:\Users\Kovács János, or a Greek/CJK
411 * CBM_CACHE_DIR) arrives here either mojibake'd or with unrepresentable
412 * characters replaced by '?', which is INVALID in Windows paths — every
413 * downstream wide-safe file API then fails no matter how correct it is.
414 * Read the value wide and convert to genuine UTF-8, matching the
415 * UTF-8-path convention the rest of the codebase (cbm_fopen, _wmkdir,
416 * SQLite VFS) already assumes. */
417 {
418 wchar_t wname[CBM_SZ_256];
419 int wn = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, name, -1, wname, CBM_SZ_256);
420 if (wn > 0) {
421 SetLastError(ERROR_SUCCESS);
422 DWORD needed = GetEnvironmentVariableW(wname, NULL, 0U);
423 DWORD environment_error = GetLastError();
424 if (needed == 0U) {
425 if (environment_error == ERROR_ENVVAR_NOT_FOUND) {
426 return fallback ? platform_copy_environment_value(buf, buf_sz, fallback) : NULL;
427 }
428 /* An existing empty variable is distinct from a missing one. */
429 return buf;
430 }
431 wchar_t *wval = calloc((size_t)needed, sizeof(*wval));
432 if (!wval) {
433 return NULL;
434 }
435 SetLastError(ERROR_SUCCESS);
436 DWORD got = GetEnvironmentVariableW(wname, wval, needed);
437 DWORD read_error = GetLastError();
438 if (got >= needed || (got == 0U && read_error != ERROR_SUCCESS)) {
439 free(wval);
440 return NULL;
441 }
442 char *utf8 = cbm_wide_to_utf8(wval);
443 free(wval);
444 if (!utf8) {
445 return NULL;
446 }
447 const char *copied = platform_copy_environment_value(buf, buf_sz, utf8);
448 free(utf8);
449 return copied;
450 }
451 return NULL;
452 }
453#else
454 char **env = CBM_ENVIRON;
455 if (env) {
456 size_t nlen = strlen(name);
457 for (; *env; env++) {
458 if (strncmp(*env, name, nlen) == 0 && (*env)[nlen] == '=') {
459 return platform_copy_environment_value(buf, buf_sz, *env + nlen + SKIP_ONE);
460 }

Callers 3

inherited_valueFunction · 0.85
cbm_runtime_getenvFunction · 0.85
cbm_safe_getenvFunction · 0.85

Calls 2

cbm_wide_to_utf8Function · 0.85

Tested by

no test coverage detected