Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 14 additions & 6 deletions src/platform/posix/procsub_file.c
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@
#include "shell.h"
#include "libft.h"
#include "sys.h"
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>

Expand Down Expand Up @@ -68,18 +70,24 @@ static int run_into_fd(t_shell *state, const char *cmd, int fd)
}

/* Create the temp file and record it so the session cleans it up. Returns
the path (owned by the caller), or NULL. */
the path (owned by the caller), or NULL.
The name comes from mkstemp, not from the pid: a =(cmd) made inside
$( ) outlives its subshell, so /tmp keeps files from processes long
gone, and a later shell given the same pid found its name taken. The
O_EXCL open failed, the word vanished without a word, and `cat =(...)`
read its stdin instead. mkstemp keeps O_EXCL's safety and retries a
taken name itself. */
char *create_procsub_file(t_shell *state, const char *cmd)
{
t_procsub_entry entry;
char buf[64];
int fd;

ft_snprintf(buf, sizeof(buf), "%s/hsh%d-%d", TMP_DIR,
(int)getpid(), (int)state->proc_subs.len);
fd = open(buf, O_RDWR | O_CREAT | O_EXCL, 0600);
ft_strlcpy(buf, TMP_DIR "/hsh.XXXXXX", sizeof(buf));
fd = mkstemp(buf);
if (fd < 0)
return (NULL);
return (ft_eprintf("%s: =(...): cannot create a temporary file: "
"%s\n", state->ctx, strerror(errno)), NULL);
if (cmd && *cmd && run_into_fd(state, cmd, fd) < 0)
return (close(fd), unlink(buf), NULL);
if (!cmd || !*cmd)
Expand Down
11 changes: 11 additions & 0 deletions tests/zsh_procsub_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,17 @@ def temp_file_cases():
check("temp: path was printed", bool(re.match(r"^/.*", path)), True)
if path:
check("temp: cleaned up after exit", os.path.exists(path), False)
# A file left in /tmp by another process must never block a new one.
# The name used to be /tmp/hsh<pid>-<n>, opened O_EXCL: a leftover
# from an earlier process that had the same pid (a =(cmd) made inside
# $( ) outlives its subshell) failed the open, the word vanished, and
# `cat` read its stdin instead -- no error, status 0. It surfaced as
# zsh_glob_test's eqsub/reads-back failing about once in 150 runs.
out, _ = run_zsh(': > /tmp/hsh$$-0; : > /tmp/hsh$$-1\n'
'cat =(echo hi) </dev/null\n'
'rm -f /tmp/hsh$$-0 /tmp/hsh$$-1')
check("temp: a leftover file under the old name does not block it",
out, "hi")


def churn_cases():
Expand Down
Loading