closes bpo-28557: error message for bad raw readinto (GH-7496)

Co-authored-by: Benjamin Peterson <benjamin@python.org>
diff --git a/Lib/test/test_io.py b/Lib/test/test_io.py
index 7b8511b..c0d67a17 100644
--- a/Lib/test/test_io.py
+++ b/Lib/test/test_io.py
@@ -1587,6 +1587,22 @@
         with self.assertRaisesRegex(TypeError, "BufferedReader"):
             self.tp(io.BytesIO(), 1024, 1024, 1024)
 
+    def test_bad_readinto_value(self):
+        rawio = io.BufferedReader(io.BytesIO(b"12"))
+        rawio.readinto = lambda buf: -1
+        bufio = self.tp(rawio)
+        with self.assertRaises(OSError) as cm:
+            bufio.readline()
+        self.assertIsNone(cm.exception.__cause__)
+
+    def test_bad_readinto_type(self):
+        rawio = io.BufferedReader(io.BytesIO(b"12"))
+        rawio.readinto = lambda buf: b''
+        bufio = self.tp(rawio)
+        with self.assertRaises(OSError) as cm:
+            bufio.readline()
+        self.assertIsInstance(cm.exception.__cause__, TypeError)
+
 
 class PyBufferedReaderTest(BufferedReaderTest):
     tp = pyio.BufferedReader
diff --git a/Misc/ACKS b/Misc/ACKS
index 0fc1954..87f0ded 100644
--- a/Misc/ACKS
+++ b/Misc/ACKS
@@ -1678,6 +1678,7 @@
 John Szakmeister
 Piotr Szczepaniak
 Amir Szekely
+David Szotten
 Maciej Szulik
 Joel Taddei
 Arfrever Frehtes Taifersar Arahesis
diff --git a/Misc/NEWS.d/next/Library/2018-06-07-22-04-01.bpo-28557.ViNJnK.rst b/Misc/NEWS.d/next/Library/2018-06-07-22-04-01.bpo-28557.ViNJnK.rst
new file mode 100644
index 0000000..4137e2f
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2018-06-07-22-04-01.bpo-28557.ViNJnK.rst
@@ -0,0 +1 @@
+Improve the error message for a misbehaving ``rawio.readinto``
diff --git a/Modules/_io/bufferedio.c b/Modules/_io/bufferedio.c
index f8e21f2..5984d34 100644
--- a/Modules/_io/bufferedio.c
+++ b/Modules/_io/bufferedio.c
@@ -1483,6 +1483,15 @@
     }
     n = PyNumber_AsSsize_t(res, PyExc_ValueError);
     Py_DECREF(res);
+
+    if (n == -1 && PyErr_Occurred()) {
+        _PyErr_FormatFromCause(
+            PyExc_OSError,
+            "raw readinto() failed"
+        );
+        return -1;
+    }
+
     if (n < 0 || n > len) {
         PyErr_Format(PyExc_OSError,
                      "raw readinto() returned invalid length %zd "