From aa4f0d5bcfac802346755e24f34902a10cd7eb50 Mon Sep 17 00:00:00 2001
From: Benoit Daloze <eregontp@gmail.com>
Date: Wed, 4 Apr 2012 22:37:49 +0200
Subject: [PATCH] Fix File.readlink when chdir and avoid NPE

Existence test is moved in the catch block since readlink should succeed even if target does not exist.
---
 src/org/jruby/RubyFile.java |   14 ++++++++------
 1 file changed, 8 insertions(+), 6 deletions(-)

diff --git a/src/org/jruby/RubyFile.java b/src/org/jruby/RubyFile.java
index 77db870..35ca057 100644
--- a/src/org/jruby/RubyFile.java
+++ b/src/org/jruby/RubyFile.java
@@ -1709,24 +1709,26 @@ public class RubyFile extends RubyIO implements EncodingCapable {
     @JRubyMethod(required = 1, meta = true)
     public static IRubyObject readlink(ThreadContext context, IRubyObject recv, IRubyObject path) {
         Ruby runtime = context.getRuntime();
+        JRubyFile link = file(path);
         
         try {
-            String realPath = runtime.getPosix().readlink(path.convertToString().getUnicodeValue());
-        
-            if (!RubyFileTest.exist_p(recv, path).isTrue()) {
-                throw runtime.newErrnoENOENTError(path.toString());
-            }
-        
+            String realPath = runtime.getPosix().readlink(link.toString());
+
             if (!RubyFileTest.symlink_p(recv, path).isTrue()) {
                 throw runtime.newErrnoEINVALError(path.toString());
             }
         
             if (realPath == null) {
                 //FIXME: When we get JNA3 we need to properly write this to errno.
+                throw runtime.newErrnoFromLastPOSIXErrno();
             }
 
             return runtime.newString(realPath);
         } catch (IOException e) {
+            if (!RubyFileTest.exist_p(recv, path).isTrue()) {
+                throw runtime.newErrnoENOENTError(link.toString());
+            }
+
             throw runtime.newIOError(e.getMessage());
         }
     }
-- 
1.7.9.4

