Skip to content

Commit d313666

Browse files
committed
[sanitizer_common] Close superfluous file descriptors in spawned process
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
1 parent 50c094a commit d313666

File tree

1 file changed

+23
-5
lines changed

1 file changed

+23
-5
lines changed

compiler-rt/lib/sanitizer_common/sanitizer_mac.cpp

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -268,20 +268,38 @@ static fd_t internal_spawn_impl(const char *argv[], pid_t *pid) {
268268
slave_fd = internal_open(slave_pty_name, O_RDWR);
269269
if (slave_fd == kInvalidFd) return kInvalidFd;
270270

271+
// File descriptor actions
271272
posix_spawn_file_actions_t acts;
272273
res = posix_spawn_file_actions_init(&acts);
273274
if (res != 0) return kInvalidFd;
274275

275-
auto fa_cleanup = at_scope_exit([&] {
276+
auto acts_cleanup = at_scope_exit([&] {
276277
posix_spawn_file_actions_destroy(&acts);
277278
});
278279

279-
char **env = GetEnviron();
280280
res = posix_spawn_file_actions_adddup2(&acts, slave_fd, STDIN_FILENO) ||
281281
posix_spawn_file_actions_adddup2(&acts, slave_fd, STDOUT_FILENO) ||
282-
posix_spawn_file_actions_addclose(&acts, slave_fd) ||
283-
posix_spawn_file_actions_addclose(&acts, master_fd) ||
284-
posix_spawn(pid, argv[0], &acts, NULL, const_cast<char **>(argv), env);
282+
posix_spawn_file_actions_addclose(&acts, slave_fd);
283+
if (res != 0) return kInvalidFd;
284+
285+
// Spawn attributes
286+
posix_spawnattr_t attrs;
287+
res = posix_spawnattr_init(&attrs);
288+
if (res != 0) return kInvalidFd;
289+
290+
auto attrs_cleanup = at_scope_exit([&] {
291+
posix_spawnattr_destroy(&attrs);
292+
});
293+
294+
// In the spawned process, close all file descriptors that are not explicitly
295+
// described by the file actions object. This is Darwin-specific extension.
296+
res = posix_spawnattr_setflags(&attrs, POSIX_SPAWN_CLOEXEC_DEFAULT);
297+
if (res != 0) return kInvalidFd;
298+
299+
// posix_spawn
300+
char **argv_casted = const_cast<char **>(argv);
301+
char **env = GetEnviron();
302+
res = posix_spawn(pid, argv[0], &acts, &attrs, argv_casted, env);
285303
if (res != 0) return kInvalidFd;
286304

287305
// Disable echo in the new terminal, disable CR.

0 commit comments

Comments
 (0)