Skip to content

Commit 3e1d305

Browse files
ylnJulian Lettner
authored and
Julian Lettner
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 (cherry picked from commit d313666)
1 parent 9b795bf commit 3e1d305

File tree

1 file changed

+23
-5
lines changed

1 file changed

+23
-5
lines changed

compiler-rt/lib/sanitizer_common/sanitizer_mac.cc

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

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

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

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

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

0 commit comments

Comments
 (0)