From: Stefano Rivera <stefanor@debian.org>
Date: Sat, 19 Dec 2020 11:10:47 -0800
Subject: Core: Fix fcntl segfault

Bug-Upstream: https://foss.heptapod.net/pypy/pypy/-/issues/3172
Origin: upstream, https://foss.heptapod.net/pypy/pypy/-/commit/dcaafc40bdfe0186e1aa407dd730c1a2a457f962
---
 pypy/module/_io/interp_bufferedio.py    |  2 ++
 pypy/module/_io/test/test_bufferedio.py | 18 ++++++++++++++++++
 2 files changed, 20 insertions(+)

diff --git a/pypy/module/_io/interp_bufferedio.py b/pypy/module/_io/interp_bufferedio.py
index 287ae2f..c279da5 100644
--- a/pypy/module/_io/interp_bufferedio.py
+++ b/pypy/module/_io/interp_bufferedio.py
@@ -470,6 +470,8 @@ class BufferedMixin:
         else:
             raise oefmt(space.w_ValueError,
                         "read length must be positive or -1")
+        if res is None:
+            return space.w_None
         return space.newbytes(res)
 
     @unwrap_spec(size=int)
diff --git a/pypy/module/_io/test/test_bufferedio.py b/pypy/module/_io/test/test_bufferedio.py
index 6caff0f..1b0e869 100644
--- a/pypy/module/_io/test/test_bufferedio.py
+++ b/pypy/module/_io/test/test_bufferedio.py
@@ -405,6 +405,24 @@ class AppTestBufferedReader:
         f.close()
         self.posix.close(fdout)
 
+    def test_read_nonblocking_crash(self):
+        import _io as io
+        try:
+            import fcntl
+        except ImportError:
+            skip('fcntl missing')
+        fdin, fdout = self.posix.pipe()
+        f = io.open(fdin, "rb")
+        fl = fcntl.fcntl(f, fcntl.F_GETFL)
+        fcntl.fcntl(f, fcntl.F_SETFL, fl | self.posix.O_NONBLOCK)
+        s = f.read(12)
+        assert s == None
+        self.posix.close(fdout)
+
+        s = f.read(12)
+        assert s == b''
+        f.close()
+
 
 class AppTestBufferedReaderWithThreads(AppTestBufferedReader):
     spaceconfig = dict(usemodules=['_io', 'thread', 'time'])
