Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix IO::FileDescriptor.new for closed fd #14697

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions spec/std/io/file_descriptor_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,17 @@ private def shell_command(command)
end

describe IO::FileDescriptor do
describe "#initialize" do
it "handles closed file descriptor gracefully" do
a, b = IO.pipe
a.close
b.close

fd = IO::FileDescriptor.new(a.fd)
fd.closed?.should be_true
end
end

it "reopen STDIN with the right mode", tags: %w[slow] do
code = %q(puts "#{STDIN.blocking} #{STDIN.info.type}")
compile_source(code) do |binpath|
Expand Down
15 changes: 13 additions & 2 deletions src/crystal/system/win32/file_descriptor.cr
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,19 @@ module Crystal::System::FileDescriptor
raise NotImplementedError.new("Crystal::System::FileDescriptor#system_close_on_exec=") if close_on_exec
end

private def system_closed?
false
private def system_closed? : Bool
file_type = LibC.GetFileType(windows_handle)

if file_type == LibC::FILE_TYPE_UNKNOWN
case error = WinError.value
when .error_invalid_handle?
return true
else
raise IO::Error.from_os_error("Unable to get info", error, target: self)
end
else
false
end
end

def self.fcntl(fd, cmd, arg = 0)
Expand Down
5 changes: 5 additions & 0 deletions src/io/file_descriptor.cr
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,13 @@ class IO::FileDescriptor < IO

def initialize(fd : Handle, blocking = nil, *, @close_on_finalize = true)
@volatile_fd = Atomic.new(fd)
@closed = true # This is necessary so we can reference `self` in `system_closed?` (in case of an exception)

# TODO: Refactor to avoid calling `GetFileType` twice on Windows (once in `system_closed?` and once in `system_info`)
@closed = system_closed?

return if @closed

if blocking.nil?
blocking =
case system_info.type
Expand Down
Loading