Skip to content

Commit 9e3500b

Browse files
committed
l-layer: a program may be started where the system says so; Windows musl and PureDarwin start programs
The interpreter decided whether a name may be started by stat's execute bits. A system that keeps no execute permission reports none there: Windows under openkal's C library, and PureDarwin, whose root volume is ext4, which openkal-macos does not claim execute bits for (mcpplibs/openkal-macos#53). access(X_OK) asks the system that decides, and is the right question on Unix too (the owner's bit says nothing about another user's file). lexec.c's search and lselfpath.c's argv[0] fallback both ask it now. Under openkal's C library (CMD_LIBC_MUSL): - fork reports ENOSYS where openkal.space is absent (Windows): the program is started with posix_spawn instead, its argument zero in the system's spelling (cmd.exe takes a '/' in its own name for a switch); - the search follows the system's conventions, which openkal states (kal_env_system): on Windows PATH is split on ';', a name with a volume is not searched for, and a name without a suffix is tried with each suffix PATHEXT lists, as the C library's own search does. Measured: x86_64-windows-musl (wine) and PureDarwin (twice) give the whole script, the program start included; linux-gnu, x86_64/i686-linux-musl unchanged; every musl row builds; make -std=c89 gives main's two warnings. CI: neither row leaves the program start out any more.
1 parent 316e998 commit 9e3500b

6 files changed

Lines changed: 205 additions & 46 deletions

File tree

‎.github/mcpp/test.bat‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ if not exist okt echo okt removed
2222
rem end of files
2323
set /a X=6*7
2424
echo X=%X%
25-
rem process: a program the interpreter starts, itself (a run where no program can be started leaves this part out)
25+
rem process: a program the interpreter starts, through COMSPEC: itself, on Windows the system's (a run where no program can be started leaves this part out)
2626
"%COMSPEC%" /c exit 3
2727
echo child=%errorlevel%
2828
rem end of process

‎.github/workflows/mcpp.yml‎

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -50,11 +50,9 @@ jobs:
5050
for t in ${{ matrix.targets }}; do
5151
echo "::group::$t"
5252
# The script of the row: node and an openkal image under okrun start no
53-
# program of this one (prepare.sh); on x86_64-windows-musl the interpreter
54-
# does not find a program named by a path with a drive letter (measured:
55-
# 'C:/Windows/system32/cmd.exe' is not recognized). Both line endings: a
56-
# batch file from Unix ends its lines in LF alone, one from Windows in CR LF.
57-
case "$t" in wasm32-emscripten|*-openkal|x86_64-windows-musl) np=no-process ;; *) np= ;; esac
53+
# program of this one (prepare.sh). Both line endings: a batch file from
54+
# Unix ends its lines in LF alone, one from Windows in CR LF.
55+
case "$t" in wasm32-emscripten|*-openkal) np=no-process ;; *) np= ;; esac
5856
sh .github/mcpp/prepare.sh "chk-$t" $np
5957
tr -d '\r' < "chk-$t/test.bat" > test.bat
6058
awk '{ printf "%s\r\n", $0 }' test.bat > test-crlf.bat
@@ -171,9 +169,7 @@ jobs:
171169
- { target: aarch64-windows-gnu, check: artifact }
172170
# Run on an Intel Mac (the job macos-x86_64), and here in PureDarwin: xnu with
173171
# no macOS above it, booted from its project's developer preview (an experiment).
174-
# In PureDarwin the script starts no program: openkal-macos reports no execute
175-
# bit there (mcpplibs/openkal-macos#53), by which the interpreter finds one.
176-
- { target: x86_64-macos-musl, check: artifact, run: true, refusal: true, run_process: false }
172+
- { target: x86_64-macos-musl, check: artifact, run: true, refusal: true }
177173
- { target: x86_64-freebsd, check: run }
178174
- { target: aarch64-freebsd, check: run }
179175
- { target: x86_64-netbsd, check: run }
@@ -257,7 +253,7 @@ jobs:
257253
set -euo pipefail
258254
t='${{ matrix.target }}'
259255
export "MCPP_TARGET_$(echo "$t" | tr 'a-z-' 'A-Z_')_RUNNER_ENABLED=true"
260-
sh .github/mcpp/prepare.sh check $([ '${{ matrix.process }}' = false ] || [ '${{ matrix.run_process }}' = false ] && echo no-process)
256+
sh .github/mcpp/prepare.sh check $([ '${{ matrix.process }}' = false ] && echo no-process)
261257
if [ '${{ matrix.foldcase }}' = true ]; then export CHECK_FOLD_CASE=1; fi
262258
mcpp run cmd.exe --release --target "$t" --file check/test.bat=TEST.BAT -- /c TEST.BAT > run.txt
263259
sh check/check.sh run.txt

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,7 @@ mcpp pack cmd.exe --profile web --target wasm32-emscripten --pkg-format web
189189
<details>
190190
<summary>More targets: Linux, Windows, macOS, FreeBSD, NetBSD, OpenBSD, Android, WebAssembly, openkal images, UEFI, DOS, System V, GNU/Hurd and Haiku</summary>
191191

192-
**runs**: a test batch script gives the same output as on Linux x86_64 (checked by `.github/workflows/mcpp.yml`); **starts**: the interpreter starts and exits; **builds**: not run. The script's part that starts a program (the interpreter itself, through `%COMSPEC%`) is left out where no program can be started: the browser and node (WebAssembly), an openkal image under okrun (it starts a program but not an image, mcpplibs/openkal-image#42), UEFI, both DOS rows, `x86_64-windows-musl`, whose interpreter does not yet find a program named by a path with a drive letter, and PureDarwin, where openkal-macos reports no execute bit (mcpplibs/openkal-macos#53).
192+
**runs**: a test batch script gives the same output as on Linux x86_64 (checked by `.github/workflows/mcpp.yml`); **starts**: the interpreter starts and exits; **builds**: not run. The script's part that starts a program (through `%COMSPEC%`: the interpreter itself, on Windows the system's) is left out where no program can be started: the browser and node (WebAssembly), an openkal image under okrun (it starts a program but not an image, mcpplibs/openkal-image#42), UEFI and both DOS rows.
193193

194194
<table>
195195
<tr><th>Target</th><th>Verified</th><th>Build command</th></tr>

‎README.zh_CN.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -193,7 +193,7 @@ mcpp pack cmd.exe --profile web --target wasm32-emscripten --pkg-format web
193193
<details>
194194
<summary>更多目标:Linux、Windows、macOS、FreeBSD、Android、WebAssembly、openkal 映像、UEFI、DOS、System V、GNU/Hurd 与 Haiku</summary>
195195

196-
**运行**:测试批处理输出与 Linux x86_64 相同(由 `.github/workflows/mcpp.yml` 检查);**启动**:解释器能启动并退出;**构建**:未运行。脚本中启动程序的部分(经 `%COMSPEC%` 启动解释器自身)在无法启动程序的行上省略:浏览器与 node(WebAssembly)、okrun 下的 openkal 映像(能启动程序,但不能启动映像,见 mcpplibs/openkal-image#42)、UEFI、两个 DOS 行、`x86_64-windows-musl`(其解释器尚不能找到以盘符路径命名的程序),以及 PureDarwin(openkal-macos 在其上不报告可执行位,见 mcpplibs/openkal-macos#53)。
196+
**运行**:测试批处理输出与 Linux x86_64 相同(由 `.github/workflows/mcpp.yml` 检查);**启动**:解释器能启动并退出;**构建**:未运行。脚本中启动程序的部分(经 `%COMSPEC%` 启动:解释器自身,Windows 上为系统的解释器)在无法启动程序的行上省略:浏览器与 node(WebAssembly)、okrun 下的 openkal 映像(能启动程序,但不能启动映像,见 mcpplibs/openkal-image#42)、UEFI 与两个 DOS 行。
197197

198198
<table>
199199
<tr><th>目标</th><th>验证</th><th>构建命令</th></tr>

‎lexec.c‎

Lines changed: 194 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,114 @@ static void child_redirect_to_null(int target)
7171
close(fd);
7272
}
7373

74+
#if defined(CMD_LIBC_MUSL)
75+
/* openkal's C library composes fork upon openkal.space, which a system that
76+
* starts only named programs (Windows) does not have: fork reports ENOSYS
77+
* there, and posix_spawn starts the program instead. It places the three
78+
* streams; a program START detaches forms a group of its own (setsid is not
79+
* answered there), and a priority START asks for is not applied. */
80+
#include <spawn.h>
81+
#include <openkal/env.h>
82+
83+
extern char **environ;
84+
85+
/* Whether the system's conventions are Windows': openkal states them
86+
* (kal_env_system), and its C library searches by the same rule. */
87+
static int windows_conventions(void)
88+
{
89+
char name[16];
90+
91+
return kal_env_system(name, sizeof(name)) == 7 &&
92+
memcmp(name, "windows", 7) == 0;
93+
}
94+
95+
/* Argument zero in Windows' spelling, in ZERO: cmd turned a typed '\'
96+
* into '/' to find the program, and a Windows program reads its own name
97+
* from its command line, where cmd.exe takes a '/' for a switch. Returns
98+
* ARGV itself elsewhere, and a copy of it to free here; NULL when no copy
99+
* could be made. */
100+
static char **system_argv(char *const argv[], char *zero, size_t size)
101+
{
102+
char **copy;
103+
size_t n;
104+
char *p;
105+
106+
if (!windows_conventions() || argv[0] == NULL ||
107+
strchr(argv[0], '/') == NULL || strlen(argv[0]) >= size)
108+
return (char **)argv;
109+
for (n = 0; argv[n] != NULL; n++)
110+
;
111+
copy = (char **)malloc((n + 1) * sizeof(*copy));
112+
if (copy == NULL)
113+
return NULL;
114+
memcpy(copy, argv, (n + 1) * sizeof(*copy));
115+
strcpy(zero, argv[0]);
116+
for (p = zero; *p != '\0'; p++)
117+
if (*p == '/')
118+
*p = '\\';
119+
copy[0] = zero;
120+
return copy;
121+
}
122+
123+
static int spawn_program(const char *path,
124+
char *const argv[],
125+
char *const envp[],
126+
const int fds[3],
127+
int detached,
128+
pid_t *pid)
129+
{
130+
posix_spawn_file_actions_t actions;
131+
posix_spawnattr_t attr;
132+
char zero[4096];
133+
char **args;
134+
int i, r;
135+
136+
args = system_argv(argv, zero, sizeof(zero));
137+
if (args == NULL)
138+
return -1;
139+
posix_spawn_file_actions_init(&actions);
140+
posix_spawnattr_init(&attr);
141+
for (i = 0; i < 3; i++) {
142+
if (fds[i] >= 0 && fds[i] != i)
143+
posix_spawn_file_actions_adddup2(&actions, fds[i], i);
144+
else if (fds[i] < 0 && detached)
145+
posix_spawn_file_actions_addopen(&actions, i, "/dev/null",
146+
i == 0 ? O_RDONLY : O_WRONLY, 0);
147+
}
148+
if (detached) {
149+
posix_spawnattr_setflags(&attr, POSIX_SPAWN_SETPGROUP);
150+
posix_spawnattr_setpgroup(&attr, 0);
151+
}
152+
r = posix_spawn(pid, path, &actions, &attr, args,
153+
envp != NULL ? envp : environ);
154+
posix_spawnattr_destroy(&attr);
155+
posix_spawn_file_actions_destroy(&actions);
156+
if (args != (char **)argv)
157+
free(args);
158+
if (r != 0) {
159+
errno = r;
160+
return -1;
161+
}
162+
return 0;
163+
}
164+
165+
#else
166+
#define windows_conventions() 0
167+
#endif
168+
169+
/* Whether NAME is a file this process may start. access(X_OK) asks the
170+
* system that decides: the owner's execute bit is the wrong question for
171+
* another user's file, and a system that keeps no execute permission
172+
* (Windows, under openkal's C library) reports none in stat while access
173+
* answers yes. */
174+
static int is_runnable(const char *name)
175+
{
176+
struct stat st;
177+
178+
return stat(name, &st) == 0 && S_ISREG(st.st_mode) &&
179+
access(name, X_OK) == 0;
180+
}
181+
74182
/* -------------------------------------------------------------------------
75183
* Raw fork / exit (used by cparser.c to run pipelines concurrently)
76184
* ---------------------------------------------------------------------- */
@@ -102,6 +210,17 @@ int libcmd_exec_sync(const char *path,
102210
int wstatus;
103211

104212
pid = fork();
213+
#if defined(CMD_LIBC_MUSL)
214+
if (pid < 0 && errno == ENOSYS) {
215+
int fds[3];
216+
217+
fds[0] = stdin_fd;
218+
fds[1] = stdout_fd;
219+
fds[2] = stderr_fd;
220+
if (spawn_program(path, argv, envp, fds, 0, &pid) < 0)
221+
return -1;
222+
}
223+
#endif
105224
if (pid < 0)
106225
return -1;
107226

@@ -138,6 +257,17 @@ int libcmd_exec_async(const char *path,
138257
pid_t pid;
139258

140259
pid = fork();
260+
#if defined(CMD_LIBC_MUSL)
261+
if (pid < 0 && errno == ENOSYS) {
262+
int fds[3];
263+
264+
fds[0] = stdin_fd;
265+
fds[1] = stdout_fd;
266+
fds[2] = stderr_fd;
267+
if (spawn_program(path, argv, envp, fds, 1, &pid) < 0)
268+
return -1;
269+
}
270+
#endif
141271
if (pid < 0)
142272
return -1;
143273

@@ -175,59 +305,92 @@ int libcmd_wait_pid(int pid, libcmd_exit_info_t *exit_info)
175305
return 0;
176306
}
177307

308+
/* Tries DIR/NAME then SUFFIX (DIR is LEN long; none when LEN is 0) and
309+
* writes the name to OUT when it may be started. */
310+
static int try_candidate(const char *dir, size_t len,
311+
const char *name,
312+
const char *suffix, size_t suffix_len,
313+
char *out, size_t out_size)
314+
{
315+
char candidate[4096];
316+
size_t n = len, name_len = strlen(name);
317+
318+
if (len + 1 + name_len + suffix_len + 1 > sizeof(candidate))
319+
return -1;
320+
memcpy(candidate, dir, len);
321+
if (len > 0)
322+
candidate[n++] = '/';
323+
memcpy(candidate + n, name, name_len);
324+
memcpy(candidate + n + name_len, suffix, suffix_len);
325+
candidate[n + name_len + suffix_len] = '\0';
326+
if (!is_runnable(candidate))
327+
return -1;
328+
return libcmd_sprintf_s(out, out_size, "%s", candidate) >= 0 ? 0 : -1;
329+
}
330+
331+
/* Tries NAME in DIR as the system would: as given, or, under Windows'
332+
* conventions and for a name without a suffix, with each suffix PATHEXT
333+
* lists in its order and not as given (Windows' own rule). */
334+
static int try_in_dir(const char *dir, size_t len, const char *name, int win,
335+
char *out, size_t out_size)
336+
{
337+
const char *suffix, *end;
338+
339+
if (!win || strchr(name, '.') != NULL)
340+
return try_candidate(dir, len, name, "", 0, out, out_size);
341+
suffix = getenv("PATHEXT");
342+
if (suffix == NULL)
343+
suffix = ".COM;.EXE;.BAT;.CMD";
344+
while (*suffix != '\0') {
345+
end = strchr(suffix, ';');
346+
if (end == NULL)
347+
end = suffix + strlen(suffix);
348+
if (end > suffix &&
349+
try_candidate(dir, len, name, suffix, (size_t)(end - suffix),
350+
out, out_size) == 0)
351+
return 0;
352+
suffix = (*end == ';') ? end + 1 : end;
353+
}
354+
return -1;
355+
}
356+
178357
int libcmd_find_exec(const char *name,
179358
const char *path_env,
180359
char *out,
181360
size_t out_size)
182361
{
183362
const char *start, *end;
184-
char candidate[4096];
185-
struct stat st;
363+
int win = windows_conventions();
364+
char sep = win ? ';' : ':';
186365

187366
if (name == NULL || out == NULL || out_size == 0)
188367
return -1;
189368

190-
/* Absolute or relative path with directory separator */
191-
if (strchr(name, '/') != NULL) {
192-
if (stat(name, &st) == 0 && (st.st_mode & S_IXUSR)) {
193-
return libcmd_sprintf_s(out, out_size, "%s", name) >= 0 ? 0 : -1;
194-
}
195-
return -1;
196-
}
369+
/* A name with a directory (or, under Windows' conventions, a volume)
370+
* is not searched for */
371+
if (strchr(name, '/') != NULL || (win && strchr(name, ':') != NULL))
372+
return try_in_dir("", 0, name, win, out, out_size);
197373

198374
if (path_env == NULL)
199-
path_env = "/usr/local/bin:/usr/bin:/bin";
375+
path_env = win ? "" : "/usr/local/bin:/usr/bin:/bin";
200376

201377
/* Windows cmd semantics: the current directory is searched before
202378
* PATH, so "build.sh" runs without a "./" prefix after cd. */
203-
if (stat(name, &st) == 0 &&
204-
S_ISREG(st.st_mode) &&
205-
(st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))) {
206-
return libcmd_sprintf_s(out, out_size, "./%s", name) >= 0 ? 0 : -1;
207-
}
379+
if (try_in_dir(".", 1, name, win, out, out_size) == 0)
380+
return 0;
208381

209382
start = path_env;
210383
while (start && *start) {
211-
end = strchr(start, ':');
384+
end = strchr(start, sep);
212385
if (end == NULL)
213386
end = start + strlen(start);
214387

215-
if (end > start) {
216-
if ((size_t)(end - start) + strlen(name) + 2 < sizeof(candidate)) {
217-
memcpy(candidate, start, (size_t)(end - start));
218-
candidate[end - start] = '/';
219-
strcpy(candidate + (end - start) + 1, name);
220-
221-
if (stat(candidate, &st) == 0 &&
222-
S_ISREG(st.st_mode) &&
223-
(st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))) {
224-
return libcmd_sprintf_s(out, out_size,
225-
"%s", candidate) >= 0 ? 0 : -1;
226-
}
227-
}
228-
}
388+
if (end > start &&
389+
try_in_dir(start, (size_t)(end - start), name, win,
390+
out, out_size) == 0)
391+
return 0;
229392

230-
start = (*end == ':') ? end + 1 : NULL;
393+
start = (*end == sep) ? end + 1 : NULL;
231394
}
232395

233396
return -1;

‎lselfpath.c‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -59,15 +59,15 @@ void libcmd_init_self(const char *argv0)
5959
self_cwd[0] = '\0';
6060
}
6161

62-
/* Return 1 if 'path' is a regular executable file. */
62+
/* Return 1 if 'path' is a regular file this process may execute
63+
* (access(X_OK): a system may keep no execute bits for stat to report). */
6364
static int is_executable_file(const char *path)
6465
{
6566
struct stat st;
6667

6768
if (stat(path, &st) != 0)
6869
return 0;
69-
return S_ISREG(st.st_mode) &&
70-
(st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH));
70+
return S_ISREG(st.st_mode) && access(path, X_OK) == 0;
7171
}
7272

7373
/*

0 commit comments

Comments
 (0)