Skip to content

Closing fd is thread unsafe on UNIX targets #16127

@ysbaddaden

Description

@ysbaddaden

UNIX targets reuse closed file descriptors which can lead to race conditions when a thread closes a fd while another thread is trying to read or write to the fd.

For example:

  • Thread 1: file = File.open("1.txt") => ok (fd=10)
  • Thread 1: file.read => checks file.closed? => false => ok
  • Thread 1: is preempted by the OS
  • Thread 2: file.close => LibC.close(10) => ok
  • Thread X: File.open("2.txt") => OS reuses fd => ok (fd=10) 💣
  • Thread 1: is woken by the OS
  • Thread 1: LibC.read(10) => reads from 2.txt 💥

It might not be easy to trigger, and this should be a very rare scenario since a File or Socket should most often not be shared across fibers. But as always with threads: if it can happen it will happen, and when it does it will be pretty bad (data corruption, secure data leak, ...).

Metadata

Metadata

Assignees

Type

Projects

Status

In Progress

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions