Skip to content

Commit

Permalink
[sanitizer_common] Close superfluous file descriptors in spawned process
Browse files Browse the repository at this point in the history
Use attribute flag `POSIX_SPAWN_CLOEXEC_DEFAULT` in the call to
`posix_spawn`.

If this flag is set, then only file descriptors explicitly described by
the file_actions argument are available in the spawned process; all of
the other file descriptors are automatically closed in the spawned
process.

POSIX_SPAWN_CLOEXEC_DEFAULT is an Apple-specific extension.

llvm-svn: 370121
  • Loading branch information
yln committed Aug 27, 2019
1 parent 50c094a commit d313666
Showing 1 changed file with 23 additions and 5 deletions.
28 changes: 23 additions & 5 deletions compiler-rt/lib/sanitizer_common/sanitizer_mac.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -268,20 +268,38 @@ static fd_t internal_spawn_impl(const char *argv[], pid_t *pid) {
slave_fd = internal_open(slave_pty_name, O_RDWR);
if (slave_fd == kInvalidFd) return kInvalidFd;

// File descriptor actions
posix_spawn_file_actions_t acts;
res = posix_spawn_file_actions_init(&acts);
if (res != 0) return kInvalidFd;

auto fa_cleanup = at_scope_exit([&] {
auto acts_cleanup = at_scope_exit([&] {
posix_spawn_file_actions_destroy(&acts);
});

char **env = GetEnviron();
res = posix_spawn_file_actions_adddup2(&acts, slave_fd, STDIN_FILENO) ||
posix_spawn_file_actions_adddup2(&acts, slave_fd, STDOUT_FILENO) ||
posix_spawn_file_actions_addclose(&acts, slave_fd) ||
posix_spawn_file_actions_addclose(&acts, master_fd) ||
posix_spawn(pid, argv[0], &acts, NULL, const_cast<char **>(argv), env);
posix_spawn_file_actions_addclose(&acts, slave_fd);
if (res != 0) return kInvalidFd;

// Spawn attributes
posix_spawnattr_t attrs;
res = posix_spawnattr_init(&attrs);
if (res != 0) return kInvalidFd;

auto attrs_cleanup = at_scope_exit([&] {
posix_spawnattr_destroy(&attrs);
});

// In the spawned process, close all file descriptors that are not explicitly
// described by the file actions object. This is Darwin-specific extension.
res = posix_spawnattr_setflags(&attrs, POSIX_SPAWN_CLOEXEC_DEFAULT);
if (res != 0) return kInvalidFd;

// posix_spawn
char **argv_casted = const_cast<char **>(argv);
char **env = GetEnviron();
res = posix_spawn(pid, argv[0], &acts, &attrs, argv_casted, env);
if (res != 0) return kInvalidFd;

// Disable echo in the new terminal, disable CR.
Expand Down

0 comments on commit d313666

Please sign in to comment.