[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.
git-svn-id: https://llvm.org/svn/llvm-project/compiler-rt/trunk@370121 91177308-0d34-0410-b5e6-96231b3b80d8
diff --git a/lib/sanitizer_common/sanitizer_mac.cpp b/lib/sanitizer_common/sanitizer_mac.cpp
index 8e59b26..8eb1dfb 100644
--- a/lib/sanitizer_common/sanitizer_mac.cpp
+++ b/lib/sanitizer_common/sanitizer_mac.cpp
@@ -268,20 +268,38 @@
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.