crystal-lang / crystal

The Crystal Programming Language
https://crystal-lang.org
Apache License 2.0
19.36k stars 1.62k forks source link

Protect fork/exec on targets that don't support atomic CLOEXEC #14674

Closed ysbaddaden closed 3 months ago

ysbaddaden commented 3 months ago

In addition to the standard O_CLOEXEC flag to open (POSIX.1-2008), all modern POSIX systems implement non-standard syscalls (accept4, dup3 and pipe2) along with the SOCK_CLOEXEC flag, that atomically create file descriptors with the FD_CLOEXEC flag.

A notable exception is Darwin that only implements O_CLOEXEC.

We thus have to support falling back to accept, dup2 and pipe that won't set FD_CLOEXEC or SOCK_CLOEXEC atomically, which creates a time window during which another thread may fork the process before FD_CLOEXEC is set, which will leak the file descriptor to a child process.

This patch introduces a RWLock to prevent fork/exec in such situations.

Follow up of #14672, #14673 and #14675.

Prior art: Go does exactly that.