From d3136661bac0509328231005957fb27adc8ce717 Mon Sep 17 00:00:00 2001 From: Julian Lettner Date: Tue, 27 Aug 2019 22:12:26 +0000 Subject: [PATCH] [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 --- .../lib/sanitizer_common/sanitizer_mac.cpp | 28 +++++++++++++++---- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/compiler-rt/lib/sanitizer_common/sanitizer_mac.cpp b/compiler-rt/lib/sanitizer_common/sanitizer_mac.cpp index 8e59b2691c5837..8eb1dfbdea6f6a 100644 --- a/compiler-rt/lib/sanitizer_common/sanitizer_mac.cpp +++ b/compiler-rt/lib/sanitizer_common/sanitizer_mac.cpp @@ -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(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(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.