Skip to content

Commit 48f2559

Browse files
committed
fix(cli): read PATH at its real length and probe Windows shim dirs (#221)
Two independent reasons `install` missed opencode on Windows 11: 1. find_in_path() copied PATH into a fixed 4 KB stack buffer through cbm_safe_getenv(), and that helper REFUSES a value it cannot fit instead of truncating it. On a machine whose PATH exceeds 4096 characters the whole PATH was therefore skipped before a single directory was probed. 2. The fallback list had no Windows-shaped entries, and it probed only the bare name, so npm's %APPDATA%\npm, mise's %LOCALAPPDATA%\mise\shims and scoop's %USERPROFILE%\scoop\shims could never match a .cmd shim. - Add cbm_env_dup() to platform.c: the allocating sibling of cbm_safe_getenv, memory-core owned, wide-read on Windows so a non-ASCII PATH is not mangled by the ANSI code page. cli.c no longer needs <windows.h> in the middle of the file, nor any raw allocation. - find_in_path() now exits once, so the PATH copy is freed on every path instead of leaking on each success. - Keep the existing pipx (~/.local/bin) and cargo (~/.cargo/bin) fallbacks, built from the home_dir argument rather than cbm_get_home_dir(), and add the npm/mise/scoop locations. PATHEXT is probed for every fallback directory, not only for PATH entries. - Bound the fallback loop by NUM_PATHS, not NUM_RETRIES. - Hoist the PATHEXT list into one file-scope constant and add braces to every one-line statement. Regression guards in tests/repro/repro_issue221.c: a PATH longer than 4096 characters whose LAST entry holds the fixture, and the Windows fallback shims driven through APPDATA / LOCALAPPDATA / the home_dir argument. Both are red against the previous code and green with this change. The PATH case is not Windows-specific: the same 4 KB cap hid entries on macOS and Linux. No raw allocator call site is added under src/, so the memory-core ratchet is untouched; clang-format and the no-skips policy both pass locally. Signed-off-by: Kris <[email protected]>
1 parent 80eb92a commit 48f2559

4 files changed

Lines changed: 379 additions & 28 deletions

File tree

‎src/cli/cli.c‎

Lines changed: 87 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
#include "foundation/platform.h"
2323
#include "foundation/constants.h"
2424
#include "foundation/log.h"
25+
#include "foundation/mem_core.h"
2526
#include "foundation/sha256.h"
2627
#include "cli/client_adapter.h"
2728
#include "mcp/mcp.h" // cbm_mcp_tool_input_schema — CLI flag parser + per-tool --help
@@ -1076,36 +1077,50 @@ static bool is_executable(const char *path) {
10761077
#endif
10771078
}
10781079

1080+
/* Windows ships CLIs as extension-bearing shims -- .cmd from npm, .ps1 from
1081+
* mise, .exe from scoop -- so a bare-name probe never matches there. One
1082+
* definition serves both the PATH scan and the fallback-directory probe (#221). */
1083+
#ifdef _WIN32
1084+
static const char *const WIN_EXEC_EXTS[] = {".exe", ".cmd", ".bat", ".ps1", NULL};
1085+
#endif
1086+
10791087
/* Search for an executable named `name` in the PATH environment variable.
1080-
* Returns the full path in `out` (max out_sz) if found, else empty string. */
1088+
* Returns the full path in `out` (max out_sz) if found, else empty string.
1089+
*
1090+
* The PATH copy is sized to the REAL value, not to a fixed 4 KB stack buffer.
1091+
* That buffer was the first root cause of #221: a Windows dev machine's PATH
1092+
* routinely runs past 4096 characters, and cbm_safe_getenv() REFUSES a value it
1093+
* cannot fit rather than truncating it -- so find_in_path() returned false
1094+
* before looking at a single directory, and opencode (installed through
1095+
* mise/npm/scoop and present on PATH) read as "not installed". The same 4 KB
1096+
* cap hid entries on macOS/Linux too; the fix is not Windows-specific. */
10811097
static bool find_in_path(const char *name, char *out, size_t out_sz) {
1082-
char path_copy[CLI_BUF_4K];
1083-
if (!cbm_safe_getenv("PATH", path_copy, sizeof(path_copy), NULL)) {
1098+
char *path_copy = cbm_env_dup("PATH");
1099+
if (!path_copy) {
10841100
return false;
10851101
}
1086-
char *saveptr;
1102+
1103+
/* One exit. PATH is a full live copy of the environment, the scan has
1104+
* several ways to stop, and the previous shape returned straight out of the
1105+
* loop -- which is exactly what leaked a PATH-sized allocation per call. */
1106+
bool found = false;
1107+
char *saveptr = NULL;
10871108
char *dir = strtok_r(path_copy, PATH_DELIM, &saveptr);
1088-
while (dir) {
1109+
while (dir != NULL && !found) {
10891110
snprintf(out, out_sz, "%s/%s", dir, name);
1090-
if (is_executable(out)) {
1091-
return true;
1092-
}
1111+
found = is_executable(out);
10931112
#ifdef _WIN32
1094-
/* On Windows executables carry an extension (PATHEXT). A CLI like
1095-
* opencode is often installed as a .cmd / .ps1 / .exe shim (e.g. via
1096-
* mise or npm), so the bare-name probe above misses it (#221). Try the
1097-
* common executable extensions before moving to the next PATH entry. */
1098-
static const char *const win_exts[] = {".exe", ".cmd", ".bat", ".ps1", NULL};
1099-
for (int i = 0; win_exts[i]; i++) {
1100-
snprintf(out, out_sz, "%s/%s%s", dir, name, win_exts[i]);
1101-
if (is_executable(out)) {
1102-
return true;
1103-
}
1113+
/* PATHEXT variants for THIS entry, before moving to the next one. */
1114+
for (int i = 0; !found && WIN_EXEC_EXTS[i] != NULL; i++) {
1115+
snprintf(out, out_sz, "%s/%s%s", dir, name, WIN_EXEC_EXTS[i]);
1116+
found = is_executable(out);
11041117
}
11051118
#endif
11061119
dir = strtok_r(NULL, PATH_DELIM, &saveptr);
11071120
}
1108-
return false;
1121+
1122+
cbm_free(CBM_MEM_CLASS_OTHER, path_copy);
1123+
return found;
11091124
}
11101125

11111126
const char *cbm_find_cli(const char *name, const char *home_dir) {
@@ -1119,22 +1134,66 @@ const char *cbm_find_cli(const char *name, const char *home_dir) {
11191134
if (!home_dir || !home_dir[0]) {
11201135
return "";
11211136
}
1137+
/* PATH-independent fallbacks, tried in order. Every home-derived entry is
1138+
* built from the `home_dir` ARGUMENT and not from cbm_get_home_dir(): a
1139+
* dry-run scan or a test passes a synthetic home and must not be shown the
1140+
* host's agents. `/` separators are fine on Windows -- the wide-safe file
1141+
* layer accepts them, and the rest of this file already composes paths so. */
11221142
enum { NUM_PATHS = 5 };
11231143
char paths[NUM_PATHS][CLI_BUF_512];
1124-
snprintf(paths[0], sizeof(paths[0]), "/usr/local/bin/%s", name);
1125-
snprintf(paths[1], sizeof(paths[1]), "%s/.npm/bin/%s", home_dir, name);
1126-
snprintf(paths[2], sizeof(paths[2]), "%s/.local/bin/%s", home_dir, name);
1127-
snprintf(paths[3], sizeof(paths[3]), "%s/.cargo/bin/%s", home_dir, name);
1128-
#ifdef __APPLE__
1129-
snprintf(paths[4], sizeof(paths[4]), "/opt/homebrew/bin/%s", name);
1144+
memset(paths, 0, sizeof(paths));
1145+
int n = 0;
1146+
#ifdef _WIN32
1147+
/* Locations that were already probed on Windows before #221 and are real
1148+
* there: pipx installs into ~/.local/bin and cargo into ~/.cargo/bin, so
1149+
* replacing the list rather than extending it would make pipx- and
1150+
* cargo-installed agents disappear. */
1151+
snprintf(paths[n++], sizeof(paths[0]), "%s/.local/bin/%s", home_dir, name);
1152+
snprintf(paths[n++], sizeof(paths[0]), "%s/.cargo/bin/%s", home_dir, name);
1153+
/* Windows-shaped locations (issue #221, second root cause): npm puts its
1154+
* global bin under %APPDATA%\npm, and mise and scoop expose shims under
1155+
* %LOCALAPPDATA%\mise\shims and %USERPROFILE%\scoop\shims. Each is read
1156+
* through its own environment seam, so the list stays testable. */
1157+
const char *appdata = cbm_app_config_dir();
1158+
if (appdata) {
1159+
snprintf(paths[n++], sizeof(paths[0]), "%s/npm/%s", appdata, name);
1160+
}
1161+
const char *localapp = cbm_app_local_dir();
1162+
if (localapp) {
1163+
snprintf(paths[n++], sizeof(paths[0]), "%s/mise/shims/%s", localapp, name);
1164+
}
1165+
snprintf(paths[n++], sizeof(paths[0]), "%s/scoop/shims/%s", home_dir, name);
11301166
#else
1131-
paths[4][0] = '\0';
1167+
snprintf(paths[n++], sizeof(paths[0]), "/usr/local/bin/%s", name);
1168+
snprintf(paths[n++], sizeof(paths[0]), "%s/.npm/bin/%s", home_dir, name);
1169+
snprintf(paths[n++], sizeof(paths[0]), "%s/.local/bin/%s", home_dir, name);
1170+
snprintf(paths[n++], sizeof(paths[0]), "%s/.cargo/bin/%s", home_dir, name);
1171+
#ifdef __APPLE__
1172+
snprintf(paths[n++], sizeof(paths[0]), "/opt/homebrew/bin/%s", name);
1173+
#endif
11321174
#endif
1133-
for (int i = 0; i < NUM_RETRIES; i++) {
1134-
if (paths[i][0] && is_executable(paths[i])) {
1175+
/* NUM_PATHS, not NUM_RETRIES: both are 5 today, so the old bound only
1176+
* looked right by coincidence -- what the loop means is the list length. */
1177+
for (int i = 0; i < NUM_PATHS; i++) {
1178+
if (!paths[i][0]) {
1179+
continue;
1180+
}
1181+
if (is_executable(paths[i])) {
11351182
snprintf(buf, sizeof(buf), "%s", paths[i]);
11361183
return buf;
11371184
}
1185+
#ifdef _WIN32
1186+
/* The npm/mise/scoop shims carry an extension, so every fallback
1187+
* directory needs the same PATHEXT probe the PATH scan got. */
1188+
for (int e = 0; WIN_EXEC_EXTS[e] != NULL; e++) {
1189+
char extpath[CLI_BUF_512];
1190+
snprintf(extpath, sizeof(extpath), "%s%s", paths[i], WIN_EXEC_EXTS[e]);
1191+
if (is_executable(extpath)) {
1192+
snprintf(buf, sizeof(buf), "%s", extpath);
1193+
return buf;
1194+
}
1195+
}
1196+
#endif
11381197
}
11391198
return "";
11401199
}

‎src/foundation/platform.c‎

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77

88
#include "foundation/compat.h"
99
#include "foundation/constants.h"
10+
#include "foundation/mem_core.h"
1011
#include "foundation/platform_internal.h"
1112
#include <ctype.h>
1213
#include <errno.h>
@@ -437,6 +438,76 @@ const char *cbm_safe_getenv(const char *name, char *buf, size_t buf_sz, const ch
437438
return NULL;
438439
}
439440

441+
/* See platform.h. The long-value sibling of cbm_safe_getenv: there is no caller
442+
* buffer to overrun, so a PATH past 4 KB is read in full instead of being
443+
* refused (#221). Both the wide staging buffer and the UTF-8 result are
444+
* allocated through the memory core, which is also the only allocator the
445+
* caller may release them with -- keeping the memory-core ratchet honest means
446+
* this file adds no raw allocation site to pay for the new read. */
447+
char *cbm_env_dup(const char *name) {
448+
if (!name || !name[0]) {
449+
return NULL;
450+
}
451+
#ifdef _WIN32
452+
/* Same wide route as cbm_safe_getenv: _environ holds ANSI-code-page bytes,
453+
* so a non-ASCII PATH would arrive mojibake'd or with '?' substituted --
454+
* invalid in a Windows path and fatal to every file API downstream. */
455+
wchar_t wname[CBM_SZ_256];
456+
int wn = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, name, -1, wname, CBM_SZ_256);
457+
if (wn <= 0) {
458+
return NULL;
459+
}
460+
SetLastError(ERROR_SUCCESS);
461+
DWORD needed = GetEnvironmentVariableW(wname, NULL, 0U);
462+
DWORD lookup_error = GetLastError();
463+
if (needed == 0U) {
464+
if (lookup_error != ERROR_ENVVAR_NOT_FOUND) {
465+
/* Present but empty. Distinct from unset, and callers are entitled
466+
* to tell the two apart, so return "" and not NULL. */
467+
return cbm_mem_strdup(CBM_MEM_CLASS_OTHER, "");
468+
}
469+
return NULL;
470+
}
471+
wchar_t *wvalue = cbm_calloc(CBM_MEM_CLASS_OTHER, (size_t)needed * sizeof(*wvalue));
472+
if (!wvalue) {
473+
return NULL;
474+
}
475+
SetLastError(ERROR_SUCCESS);
476+
DWORD got = GetEnvironmentVariableW(wname, wvalue, needed);
477+
DWORD read_error = GetLastError();
478+
if (got >= needed || (got == 0U && read_error != ERROR_SUCCESS)) {
479+
cbm_free(CBM_MEM_CLASS_OTHER, wvalue);
480+
return NULL;
481+
}
482+
int utf8_size =
483+
WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, wvalue, -1, NULL, 0, NULL, NULL);
484+
char *utf8 = utf8_size > 0 ? cbm_alloc(CBM_MEM_CLASS_OTHER, (size_t)utf8_size) : NULL;
485+
int converted = utf8 ? WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, wvalue, -1, utf8,
486+
utf8_size, NULL, NULL)
487+
: 0;
488+
if (!utf8 || converted != utf8_size) {
489+
cbm_free(CBM_MEM_CLASS_OTHER, utf8);
490+
cbm_free(CBM_MEM_CLASS_OTHER, wvalue);
491+
return NULL;
492+
}
493+
cbm_free(CBM_MEM_CLASS_OTHER, wvalue);
494+
return utf8;
495+
#else
496+
/* Same environ walk as cbm_safe_getenv: getenv() returns a pointer another
497+
* thread can invalidate with setenv(), so the value is copied out here. */
498+
char **env = CBM_ENVIRON;
499+
if (env) {
500+
size_t name_len = strlen(name);
501+
for (; *env; env++) {
502+
if (strncmp(*env, name, name_len) == 0 && (*env)[name_len] == '=') {
503+
return cbm_mem_strdup(CBM_MEM_CLASS_OTHER, *env + name_len + SKIP_ONE);
504+
}
505+
}
506+
}
507+
return NULL;
508+
#endif
509+
}
510+
440511
/* See platform.h. The shape here is the one src/main.c:1104 already uses for
441512
* --port=: an end pointer says where the read stopped, errno catches a number
442513
* too large, and *end == '\0' catches anything left over. */

‎src/foundation/platform.h‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,19 @@ int cbm_default_worker_count(bool initial);
138138
* Returns NULL when the variable is unset and fallback is NULL. */
139139
const char *cbm_safe_getenv(const char *name, char *buf, size_t buf_sz, const char *fallback);
140140

141+
/* Allocating sibling of cbm_safe_getenv, for a value that must not be capped at
142+
* a caller-chosen size. A Windows PATH routinely runs past the 4096-byte buffer
143+
* cbm_safe_getenv's callers pass, and the copy helper REPORTS that as failure
144+
* rather than truncating -- so the whole PATH was skipped and every directory
145+
* past the cut became invisible (#221).
146+
*
147+
* Returns a UTF-8 copy owned by the memory core: release it with
148+
* cbm_free(CBM_MEM_CLASS_OTHER, ptr), never free(). NULL when the variable is
149+
* unset or cannot be read; a variable that exists but is empty yields "".
150+
* On Windows the value is read with the wide API and converted, the same route
151+
* cbm_safe_getenv takes, so a non-ASCII value survives intact. */
152+
char *cbm_env_dup(const char *name);
153+
141154
/* Read an environment variable as a whole number.
142155
*
143156
* Answers true only when the variable is set, is not empty, and reads cleanly

0 commit comments

Comments
 (0)