Proposed fix (not sure about the error message saying "fstat(2)", now...)

Subject: [PATCH] avoid rb_bug on BasicSocket.for_fd(-1)

* ext/socket/init.c (rsock_init_sock): check FD after validating
* test/socket/test_basicsocket.rb (test_for_fd): new
  [ruby-core:72418] [Bug #11854]
---
 ext/socket/init.c               |  2 +-
 test/socket/test_basicsocket.rb | 11 +++++++++++
 2 files changed, 12 insertions(+), 1 deletion(-)

diff --git a/ext/socket/init.c b/ext/socket/init.c
index d071102..bd06926 100644
--- a/ext/socket/init.c
+++ b/ext/socket/init.c
@@ -61,10 +61,10 @@ rsock_init_sock(VALUE sock, int fd)
 {
     rb_io_t *fp;
 
-    rb_update_max_fd(fd);
     if (!is_socket(fd))
         rb_raise(rb_eArgError, "not a socket file descriptor");
 
+    rb_update_max_fd(fd);
     MakeOpenFile(sock, fp);
     fp->fd = fd;
     fp->mode = FMODE_READWRITE|FMODE_DUPLEX;
diff --git a/test/socket/test_basicsocket.rb b/test/socket/test_basicsocket.rb
index 227034e..52732f1 100644
--- a/test/socket/test_basicsocket.rb
+++ b/test/socket/test_basicsocket.rb
@@ -133,4 +133,15 @@ def test_close_write
     end
   end
 
+  def test_for_fd
+    assert_raise(Errno::EBADF, '[ruby-core:72418] [Bug #11854]') do
+      BasicSocket.for_fd(-1)
+    end
+    inet_stream do |sock|
+      s = BasicSocket.for_fd(sock.fileno)
+      assert_instance_of BasicSocket, s
+      s.autoclose = false
+      sock.close
+    end
+  end
 end if defined?(BasicSocket)
-- 
EW