diff -r 39873557ff4f -r 9bb6b71f172d Include/pyerrors.h --- a/Include/pyerrors.h Wed Jul 13 23:39:53 2011 +0200 +++ b/Include/pyerrors.h Thu Jul 14 01:01:27 2011 +0200 @@ -45,18 +45,18 @@ PyObject *myerrno; PyObject *strerror; PyObject *filename; -} PyEnvironmentErrorObject; +#ifdef MS_WINDOWS + PyObject *winerror; +#endif + Py_ssize_t written; /* only for BlockingIOError, -1 otherwise */ +} PyIOErrorObject; +/* Compatibility typedefs */ +typedef PyIOErrorObject PyEnvironmentErrorObject; #ifdef MS_WINDOWS -typedef struct { - PyException_HEAD - PyObject *myerrno; - PyObject *strerror; - PyObject *filename; - PyObject *winerror; -} PyWindowsErrorObject; +typedef PyIOErrorObject PyWindowsErrorObject; #endif -#endif +#endif /* !Py_LIMITED_API */ /* Error handling definitions */ @@ -132,11 +132,10 @@ PyAPI_DATA(PyObject *) PyExc_AssertionError; PyAPI_DATA(PyObject *) PyExc_AttributeError; +PyAPI_DATA(PyObject *) PyExc_BufferError; PyAPI_DATA(PyObject *) PyExc_EOFError; PyAPI_DATA(PyObject *) PyExc_FloatingPointError; -PyAPI_DATA(PyObject *) PyExc_EnvironmentError; PyAPI_DATA(PyObject *) PyExc_IOError; -PyAPI_DATA(PyObject *) PyExc_OSError; PyAPI_DATA(PyObject *) PyExc_ImportError; PyAPI_DATA(PyObject *) PyExc_IndexError; PyAPI_DATA(PyObject *) PyExc_KeyError; @@ -160,6 +159,25 @@ PyAPI_DATA(PyObject *) PyExc_UnicodeTranslateError; PyAPI_DATA(PyObject *) PyExc_ValueError; PyAPI_DATA(PyObject *) PyExc_ZeroDivisionError; + +PyAPI_DATA(PyObject *) PyExc_BlockingIOError; +PyAPI_DATA(PyObject *) PyExc_ConnectionError; +PyAPI_DATA(PyObject *) PyExc_ConnectionAbortedError; +PyAPI_DATA(PyObject *) PyExc_ConnectionRefusedError; +PyAPI_DATA(PyObject *) PyExc_ConnectionResetError; +PyAPI_DATA(PyObject *) PyExc_FileDescriptorError; +PyAPI_DATA(PyObject *) PyExc_FileExistsError; +PyAPI_DATA(PyObject *) PyExc_FileNotFoundError; +PyAPI_DATA(PyObject *) PyExc_FileSystemError; +PyAPI_DATA(PyObject *) PyExc_IsADirectoryError; +PyAPI_DATA(PyObject *) PyExc_NotADirectoryError; +PyAPI_DATA(PyObject *) PyExc_PermissionError; +PyAPI_DATA(PyObject *) PyExc_TimeoutError; + + +/* Compatibility aliases */ +PyAPI_DATA(PyObject *) PyExc_EnvironmentError; +PyAPI_DATA(PyObject *) PyExc_OSError; #ifdef MS_WINDOWS PyAPI_DATA(PyObject *) PyExc_WindowsError; #endif @@ -167,8 +185,6 @@ PyAPI_DATA(PyObject *) PyExc_VMSError; #endif -PyAPI_DATA(PyObject *) PyExc_BufferError; - PyAPI_DATA(PyObject *) PyExc_RecursionErrorInst; /* Predefined warning categories */ diff -r 39873557ff4f -r 9bb6b71f172d Lib/multiprocessing/connection.py --- a/Lib/multiprocessing/connection.py Wed Jul 13 23:39:53 2011 +0200 +++ b/Lib/multiprocessing/connection.py Thu Jul 14 01:01:27 2011 +0200 @@ -321,7 +321,7 @@ firstchunk = overlapped.getbuffer() assert lenfirstchunk == len(firstchunk) except IOError as e: - if e.errno == win32.ERROR_BROKEN_PIPE: + if e.winerror == win32.ERROR_BROKEN_PIPE: raise EOFError raise buf.write(firstchunk) @@ -669,7 +669,7 @@ try: win32.ConnectNamedPipe(handle, win32.NULL) except WindowsError as e: - if e.args[0] != win32.ERROR_PIPE_CONNECTED: + if e.winerror != win32.ERROR_PIPE_CONNECTED: raise return PipeConnection(handle) @@ -692,8 +692,8 @@ 0, win32.NULL, win32.OPEN_EXISTING, 0, win32.NULL ) except WindowsError as e: - if e.args[0] not in (win32.ERROR_SEM_TIMEOUT, - win32.ERROR_PIPE_BUSY) or _check_timeout(t): + if e.winerror not in (win32.ERROR_SEM_TIMEOUT, + win32.ERROR_PIPE_BUSY) or _check_timeout(t): raise else: break diff -r 39873557ff4f -r 9bb6b71f172d Lib/test/exception_hierarchy.txt --- a/Lib/test/exception_hierarchy.txt Wed Jul 13 23:39:53 2011 +0200 +++ b/Lib/test/exception_hierarchy.txt Thu Jul 14 01:01:27 2011 +0200 @@ -11,13 +11,22 @@ +-- AssertionError +-- AttributeError +-- BufferError - +-- EnvironmentError - | +-- IOError - | +-- OSError - | +-- WindowsError (Windows) - | +-- VMSError (VMS) +-- EOFError +-- ImportError + +-- IOError + | +-- BlockingIOError + | +-- ConnectionError + | | +-- ConnectionAbortedError + | | +-- ConnectionRefusedError + | | +-- ConnectionResetError + | +-- FileDescriptorError + | +-- FileSystemError + | | +-- FileExistsError + | | +-- FileNotFoundError + | | +-- IsADirectoryError + | | +-- NotADirectoryError + | +-- PermissionError + | +-- TimeoutError +-- LookupError | +-- IndexError | +-- KeyError diff -r 39873557ff4f -r 9bb6b71f172d Lib/test/test_exceptions.py --- a/Lib/test/test_exceptions.py Wed Jul 13 23:39:53 2011 +0200 +++ b/Lib/test/test_exceptions.py Thu Jul 14 01:01:27 2011 +0200 @@ -191,11 +191,34 @@ except NameError: pass else: - self.assertEqual(str(WindowsError(1001)), "1001") - self.assertEqual(str(WindowsError(1001, "message")), - "[Error 1001] message") - self.assertEqual(WindowsError(1001, "message").errno, 22) - self.assertEqual(WindowsError(1001, "message").winerror, 1001) + self.assertIs(WindowsError, IOError) + self.assertEqual(str(IOError(1001)), "1001") + self.assertEqual(str(IOError(1001, "message")), + "[Errno 1001] message") + # POSIX errno (9 aka EBADF) is untranslated + w = IOError(9, 'foo', 'bar') + self.assertEqual(w.errno, 9) + self.assertEqual(w.winerror, None) + self.assertEqual("[Errno 9] foo: 'bar'", str(w)) + # ERROR_PATH_NOT_FOUND (win error 3) becomes ENOENT (2) + w = IOError(0, 'foo', 'bar', 3) + self.assertEqual(w.errno, 2) + self.assertEqual(w.winerror, 3) + self.assertEqual(w.strerror, 'foo') + self.assertEqual(w.filename, 'bar') + # Unknown win error becomes EINVAL (22) + w = IOError(0, 'foo', None, 1001) + self.assertEqual(w.errno, 22) + self.assertEqual(w.winerror, 1001) + self.assertEqual(w.strerror, 'foo') + self.assertEqual(w.filename, None) + self.assertEqual("[Error 1001] foo", str(w)) + # Non-numeric "errno" + w = IOError('bar', 'foo') + self.assertEqual(w.errno, 'bar') + self.assertEqual(w.winerror, None) + self.assertEqual(w.strerror, 'foo') + self.assertEqual(w.filename, None) def testAttributes(self): # test that exception attributes are happy @@ -273,11 +296,12 @@ 'start' : 0, 'end' : 1}), ] try: + # More tests are in test_WindowsError exceptionList.append( (WindowsError, (1, 'strErrorStr', 'filenameStr'), {'args' : (1, 'strErrorStr'), - 'strerror' : 'strErrorStr', 'winerror' : 1, - 'errno' : 22, 'filename' : 'filenameStr'}) + 'strerror' : 'strErrorStr', 'winerror' : None, + 'errno' : 1, 'filename' : 'filenameStr'}) ) except NameError: pass diff -r 39873557ff4f -r 9bb6b71f172d Lib/test/test_http_cookiejar.py --- a/Lib/test/test_http_cookiejar.py Wed Jul 13 23:39:53 2011 +0200 +++ b/Lib/test/test_http_cookiejar.py Thu Jul 14 01:01:27 2011 +0200 @@ -257,7 +257,7 @@ "filename should not exist") except IOError as exc: # exactly IOError, not LoadError - self.assertEqual(exc.__class__, IOError) + self.assertNotEqual(exc.__class__, LoadError) else: self.fail("expected IOError for invalid filename") # Invalid contents of cookies file (eg. bad magic string) diff -r 39873557ff4f -r 9bb6b71f172d Lib/test/test_io.py --- a/Lib/test/test_io.py Wed Jul 13 23:39:53 2011 +0200 +++ b/Lib/test/test_io.py Thu Jul 14 01:01:27 2011 +0200 @@ -2548,12 +2548,6 @@ def test_blockingioerror(self): # Various BlockingIOError issues - self.assertRaises(TypeError, self.BlockingIOError) - self.assertRaises(TypeError, self.BlockingIOError, 1) - self.assertRaises(TypeError, self.BlockingIOError, 1, 2, 3, 4) - self.assertRaises(TypeError, self.BlockingIOError, 1, "", None) - b = self.BlockingIOError(1, "") - self.assertEqual(b.characters_written, 0) class C(str): pass c = C("") diff -r 39873557ff4f -r 9bb6b71f172d Lib/test/test_mmap.py --- a/Lib/test/test_mmap.py Wed Jul 13 23:39:53 2011 +0200 +++ b/Lib/test/test_mmap.py Thu Jul 14 01:01:27 2011 +0200 @@ -563,8 +563,7 @@ f.close() def test_error(self): - self.assertTrue(issubclass(mmap.error, EnvironmentError)) - self.assertIn("mmap.error", str(mmap.error)) + self.assertIs(mmap.error, IOError) def test_io_methods(self): data = b"0123456789" diff -r 39873557ff4f -r 9bb6b71f172d Lib/test/test_pep3151.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Lib/test/test_pep3151.py Thu Jul 14 01:01:27 2011 +0200 @@ -0,0 +1,88 @@ +import os +import select +import socket +import sys +import unittest +from errno import * + +from test import support + +class SubIOError(IOError): + pass + + +class HierarchyTest(unittest.TestCase): + + def test_builtin_errors(self): + self.assertEqual(IOError.__name__, 'IOError') + self.assertIs(OSError, IOError) + self.assertIs(EnvironmentError, IOError) + + def test_socket_errors(self): + self.assertIs(socket.error, IOError) + self.assertIs(socket.gaierror.__base__, IOError) + self.assertIs(socket.herror.__base__, IOError) + self.assertIs(socket.timeout.__base__, IOError) + + def test_select_error(self): + self.assertIs(select.error, IOError) + + # mmap.error is tested in test_mmap + + def test_errno_mapping(self): + # The IOError constructor maps errnos to subclasses + e = IOError(EBADF, "Bad file descriptor") + self.assertIs(type(e), FileDescriptorError) + + def test_ioerror_subclass_mapping(self): + # When constructing an IOError subclass, errno mapping isn't done + e = SubIOError(EBADF, "Bad file descriptor") + self.assertIs(type(e), SubIOError) + + +class AttributesTest(unittest.TestCase): + + def test_windows_error(self): + if os.name == "nt": + self.assertIn('winerror', dir(IOError)) + else: + self.assertNotIn('winerror', dir(IOError)) + + def test_posix_error(self): + e = IOError(EEXIST, "File already exists", "foo.txt") + self.assertEqual(e.errno, EEXIST) + self.assertEqual(e.args[0], EEXIST) + self.assertEqual(e.strerror, "File already exists") + self.assertEqual(e.filename, "foo.txt") + if os.name == "nt": + self.assertEqual(e.winerror, None) + + @unittest.skipUnless(os.name == "nt", "Windows-specific test") + def test_errno_translation(self): + # ERROR_ALREADY_EXISTS (183) -> EEXIST + e = IOError(0, "File already exists", "foo.txt", 183) + self.assertEqual(e.winerror, 183) + self.assertEqual(e.errno, EEXIST) + self.assertEqual(e.args[0], EEXIST) + self.assertEqual(e.strerror, "File already exists") + self.assertEqual(e.filename, "foo.txt") + + def test_blockingioerror(self): + args = ("a", "b", "c", "d", "e") + for n in range(6): + e = BlockingIOError(*args[:n]) + with self.assertRaises(AttributeError): + e.characters_written + e = BlockingIOError("a", "b", 3) + self.assertEqual(e.characters_written, 3) + e.characters_written = 5 + self.assertEqual(e.characters_written, 5) + + # XXX VMSError not tested + + +def test_main(): + support.run_unittest(__name__) + +if __name__=="__main__": + test_main() diff -r 39873557ff4f -r 9bb6b71f172d Lib/urllib/request.py --- a/Lib/urllib/request.py Wed Jul 13 23:39:53 2011 +0200 +++ b/Lib/urllib/request.py Thu Jul 14 01:01:27 2011 +0200 @@ -1540,6 +1540,8 @@ return getattr(self, name)(url) else: return getattr(self, name)(url, data) + except HTTPError: + raise except socket.error as msg: raise IOError('socket error', msg).with_traceback(sys.exc_info()[2]) diff -r 39873557ff4f -r 9bb6b71f172d Modules/_io/_iomodule.c --- a/Modules/_io/_iomodule.c Wed Jul 13 23:39:53 2011 +0200 +++ b/Modules/_io/_iomodule.c Thu Jul 14 01:01:27 2011 +0200 @@ -91,89 +91,6 @@ /* - * BlockingIOError extends IOError - */ - -static int -blockingioerror_init(PyBlockingIOErrorObject *self, PyObject *args, - PyObject *kwds) -{ - PyObject *myerrno = NULL, *strerror = NULL; - PyObject *baseargs = NULL; - Py_ssize_t written = 0; - - assert(PyTuple_Check(args)); - - self->written = 0; - if (!PyArg_ParseTuple(args, "OO|n:BlockingIOError", - &myerrno, &strerror, &written)) - return -1; - - baseargs = PyTuple_Pack(2, myerrno, strerror); - if (baseargs == NULL) - return -1; - /* This will take care of initializing of myerrno and strerror members */ - if (((PyTypeObject *)PyExc_IOError)->tp_init( - (PyObject *)self, baseargs, kwds) == -1) { - Py_DECREF(baseargs); - return -1; - } - Py_DECREF(baseargs); - - self->written = written; - return 0; -} - -static PyMemberDef blockingioerror_members[] = { - {"characters_written", T_PYSSIZET, offsetof(PyBlockingIOErrorObject, written), 0}, - {NULL} /* Sentinel */ -}; - -static PyTypeObject _PyExc_BlockingIOError = { - PyVarObject_HEAD_INIT(NULL, 0) - "BlockingIOError", /*tp_name*/ - sizeof(PyBlockingIOErrorObject), /*tp_basicsize*/ - 0, /*tp_itemsize*/ - 0, /*tp_dealloc*/ - 0, /*tp_print*/ - 0, /*tp_getattr*/ - 0, /*tp_setattr*/ - 0, /*tp_compare */ - 0, /*tp_repr*/ - 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ - 0, /*tp_as_mapping*/ - 0, /*tp_hash */ - 0, /*tp_call*/ - 0, /*tp_str*/ - 0, /*tp_getattro*/ - 0, /*tp_setattro*/ - 0, /*tp_as_buffer*/ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ - PyDoc_STR("Exception raised when I/O would block " - "on a non-blocking I/O stream"), /* tp_doc */ - 0, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - blockingioerror_members, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - (initproc)blockingioerror_init, /* tp_init */ - 0, /* tp_alloc */ - 0, /* tp_new */ -}; -PyObject *PyExc_BlockingIOError = (PyObject *)&_PyExc_BlockingIOError; - - -/* * The main open() function */ PyDoc_STRVAR(open_doc, @@ -691,9 +608,11 @@ state->unsupported_operation) < 0) goto fail; - /* BlockingIOError */ - _PyExc_BlockingIOError.tp_base = (PyTypeObject *) PyExc_IOError; - ADD_TYPE(&_PyExc_BlockingIOError, "BlockingIOError"); + /* BlockingIOError, for compatibility */ + Py_INCREF(PyExc_BlockingIOError); + if (PyModule_AddObject(m, "BlockingIOError", + (PyObject *) PyExc_BlockingIOError) < 0) + goto fail; /* Concrete base types of the IO ABCs. (the ABCs themselves are declared through inheritance in io.py) diff -r 39873557ff4f -r 9bb6b71f172d Modules/_io/_iomodule.h --- a/Modules/_io/_iomodule.h Wed Jul 13 23:39:53 2011 +0200 +++ b/Modules/_io/_iomodule.h Thu Jul 14 01:01:27 2011 +0200 @@ -60,15 +60,6 @@ #define DEFAULT_BUFFER_SIZE (8 * 1024) /* bytes */ -typedef struct { - PyException_HEAD - PyObject *myerrno; - PyObject *strerror; - PyObject *filename; /* Not used, but part of the IOError object */ - Py_ssize_t written; -} PyBlockingIOErrorObject; -PyAPI_DATA(PyObject *) PyExc_BlockingIOError; - /* * Offset type for positioning. */ diff -r 39873557ff4f -r 9bb6b71f172d Modules/_io/bufferedio.c --- a/Modules/_io/bufferedio.c Wed Jul 13 23:39:53 2011 +0200 +++ b/Modules/_io/bufferedio.c Thu Jul 14 01:01:27 2011 +0200 @@ -609,14 +609,14 @@ _buffered_check_blocking_error(void) { PyObject *t, *v, *tb; - PyBlockingIOErrorObject *err; + PyIOErrorObject *err; PyErr_Fetch(&t, &v, &tb); if (v == NULL || !PyErr_GivenExceptionMatches(v, PyExc_BlockingIOError)) { PyErr_Restore(t, v, tb); return NULL; } - err = (PyBlockingIOErrorObject *) v; + err = (PyIOErrorObject *) v; /* TODO: sanity check (err->written >= 0) */ PyErr_Restore(t, v, tb); return &err->written; diff -r 39873557ff4f -r 9bb6b71f172d Modules/mmapmodule.c --- a/Modules/mmapmodule.c Wed Jul 13 23:39:53 2011 +0200 +++ b/Modules/mmapmodule.c Thu Jul 14 01:01:27 2011 +0200 @@ -78,8 +78,6 @@ # define MAP_ANONYMOUS MAP_ANON #endif -static PyObject *mmap_module_error; - typedef enum { ACCESS_DEFAULT, @@ -459,7 +457,7 @@ { struct stat buf; if (-1 == fstat(self->fd, &buf)) { - PyErr_SetFromErrno(mmap_module_error); + PyErr_SetFromErrno(PyExc_IOError); return NULL; } #ifdef HAVE_LARGEFILE_SUPPORT @@ -549,7 +547,7 @@ void *newmap; if (ftruncate(self->fd, self->offset + new_size) == -1) { - PyErr_SetFromErrno(mmap_module_error); + PyErr_SetFromErrno(PyExc_IOError); return NULL; } @@ -564,7 +562,7 @@ #endif if (newmap == (void *)-1) { - PyErr_SetFromErrno(mmap_module_error); + PyErr_SetFromErrno(PyExc_IOError); return NULL; } self->data = newmap; @@ -605,7 +603,7 @@ /* XXX semantics of return value? */ /* XXX flags for msync? */ if (-1 == msync(self->data + offset, size, MS_SYNC)) { - PyErr_SetFromErrno(mmap_module_error); + PyErr_SetFromErrno(PyExc_IOError); return NULL; } return PyLong_FromLong(0); @@ -1203,7 +1201,7 @@ fd = devzero = open("/dev/zero", O_RDWR); if (devzero == -1) { Py_DECREF(m_obj); - PyErr_SetFromErrno(mmap_module_error); + PyErr_SetFromErrno(PyExc_IOError); return NULL; } #endif @@ -1211,7 +1209,7 @@ m_obj->fd = dup(fd); if (m_obj->fd == -1) { Py_DECREF(m_obj); - PyErr_SetFromErrno(mmap_module_error); + PyErr_SetFromErrno(PyExc_IOError); return NULL; } } @@ -1227,7 +1225,7 @@ if (m_obj->data == (char *)-1) { m_obj->data = NULL; Py_DECREF(m_obj); - PyErr_SetFromErrno(mmap_module_error); + PyErr_SetFromErrno(PyExc_IOError); return NULL; } m_obj->access = (access_mode)access; @@ -1308,12 +1306,12 @@ if (fileno != -1 && fileno != 0) { /* Ensure that fileno is within the CRT's valid range */ if (_PyVerify_fd(fileno) == 0) { - PyErr_SetFromErrno(mmap_module_error); + PyErr_SetFromErrno(PyExc_IOError); return NULL; } fh = (HANDLE)_get_osfhandle(fileno); if (fh==(HANDLE)-1) { - PyErr_SetFromErrno(mmap_module_error); + PyErr_SetFromErrno(PyExc_IOError); return NULL; } /* Win9x appears to need us seeked to zero */ @@ -1467,11 +1465,7 @@ dict = PyModule_GetDict(module); if (!dict) return NULL; - mmap_module_error = PyErr_NewException("mmap.error", - PyExc_EnvironmentError , NULL); - if (mmap_module_error == NULL) - return NULL; - PyDict_SetItemString(dict, "error", mmap_module_error); + PyDict_SetItemString(dict, "error", PyExc_IOError); PyDict_SetItemString(dict, "mmap", (PyObject*) &mmap_object_type); #ifdef PROT_EXEC setint(dict, "PROT_EXEC", PROT_EXEC); diff -r 39873557ff4f -r 9bb6b71f172d Modules/selectmodule.c --- a/Modules/selectmodule.c Wed Jul 13 23:39:53 2011 +0200 +++ b/Modules/selectmodule.c Thu Jul 14 01:01:27 2011 +0200 @@ -54,8 +54,6 @@ # endif #endif -static PyObject *SelectError; - /* list of Python objects and their file descriptor */ typedef struct { PyObject *obj; /* owned reference */ @@ -281,11 +279,11 @@ #ifdef MS_WINDOWS if (n == SOCKET_ERROR) { - PyErr_SetExcFromWindowsErr(SelectError, WSAGetLastError()); + PyErr_SetExcFromWindowsErr(PyExc_IOError, WSAGetLastError()); } #else if (n < 0) { - PyErr_SetFromErrno(SelectError); + PyErr_SetFromErrno(PyExc_IOError); } #endif else { @@ -531,7 +529,7 @@ Py_END_ALLOW_THREADS if (poll_result < 0) { - PyErr_SetFromErrno(SelectError); + PyErr_SetFromErrno(PyExc_IOError); return NULL; } @@ -1785,9 +1783,8 @@ if (m == NULL) return NULL; - SelectError = PyErr_NewException("select.error", NULL, NULL); - Py_INCREF(SelectError); - PyModule_AddObject(m, "error", SelectError); + Py_INCREF(PyExc_IOError); + PyModule_AddObject(m, "error", PyExc_IOError); #ifdef PIPE_BUF #ifdef HAVE_BROKEN_PIPE_BUF diff -r 39873557ff4f -r 9bb6b71f172d Modules/socketmodule.c --- a/Modules/socketmodule.c Wed Jul 13 23:39:53 2011 +0200 +++ b/Modules/socketmodule.c Thu Jul 14 01:01:27 2011 +0200 @@ -452,7 +452,6 @@ /* Global variable holding the exception type for errors detected by this module (but not argument type or memory errors, etc.). */ -static PyObject *socket_error; static PyObject *socket_herror; static PyObject *socket_gaierror; static PyObject *socket_timeout; @@ -486,7 +485,7 @@ static PyObject* select_error(void) { - PyErr_SetString(socket_error, "unable to select on socket"); + PyErr_SetString(PyExc_IOError, "unable to select on socket"); return NULL; } @@ -513,7 +512,7 @@ recognizes the error codes used by both GetLastError() and WSAGetLastError */ if (err_no) - return PyErr_SetExcFromWindowsErr(socket_error, err_no); + return PyErr_SetExcFromWindowsErr(PyExc_IOError, err_no); #endif #if defined(PYOS_OS2) && !defined(PYCC_GCC) @@ -544,7 +543,7 @@ } v = Py_BuildValue("(is)", myerrorcode, outbuf); if (v != NULL) { - PyErr_SetObject(socket_error, v); + PyErr_SetObject(PyExc_IOError, v); Py_DECREF(v); } return NULL; @@ -552,7 +551,7 @@ } #endif - return PyErr_SetFromErrno(socket_error); + return PyErr_SetFromErrno(PyExc_IOError); } @@ -871,13 +870,13 @@ #endif default: freeaddrinfo(res); - PyErr_SetString(socket_error, + PyErr_SetString(PyExc_IOError, "unsupported address family"); return -1; } if (res->ai_next) { freeaddrinfo(res); - PyErr_SetString(socket_error, + PyErr_SetString(PyExc_IOError, "wildcard resolved to multiple address"); return -1; } @@ -890,7 +889,7 @@ if (name[0] == '<' && strcmp(name, "") == 0) { struct sockaddr_in *sin; if (af != AF_INET && af != AF_UNSPEC) { - PyErr_SetString(socket_error, + PyErr_SetString(PyExc_IOError, "address family mismatched"); return -1; } @@ -948,7 +947,7 @@ return 16; #endif default: - PyErr_SetString(socket_error, "unknown address family"); + PyErr_SetString(PyExc_IOError, "unknown address family"); return -1; } } @@ -997,7 +996,7 @@ bdaddr->b[5] = b5; return 6; } else { - PyErr_SetString(socket_error, "bad bluetooth address"); + PyErr_SetString(PyExc_IOError, "bad bluetooth address"); return -1; } } @@ -1247,7 +1246,7 @@ if (len > 0 && path[0] == 0) { /* Linux abstract namespace extension */ if (len > sizeof addr->sun_path) { - PyErr_SetString(socket_error, + PyErr_SetString(PyExc_IOError, "AF_UNIX path too long"); return 0; } @@ -1257,7 +1256,7 @@ { /* regular NULL-terminated string */ if (len >= sizeof addr->sun_path) { - PyErr_SetString(socket_error, + PyErr_SetString(PyExc_IOError, "AF_UNIX path too long"); return 0; } @@ -1387,7 +1386,7 @@ _BT_L2_MEMB(addr, family) = AF_BLUETOOTH; if (!PyArg_ParseTuple(args, "si", &straddr, &_BT_L2_MEMB(addr, psm))) { - PyErr_SetString(socket_error, "getsockaddrarg: " + PyErr_SetString(PyExc_IOError, "getsockaddrarg: " "wrong format"); return 0; } @@ -1406,7 +1405,7 @@ _BT_RC_MEMB(addr, family) = AF_BLUETOOTH; if (!PyArg_ParseTuple(args, "si", &straddr, &_BT_RC_MEMB(addr, channel))) { - PyErr_SetString(socket_error, "getsockaddrarg: " + PyErr_SetString(PyExc_IOError, "getsockaddrarg: " "wrong format"); return 0; } @@ -1424,7 +1423,7 @@ _BT_HCI_MEMB(addr, family) = AF_BLUETOOTH; if (straddr == NULL) { - PyErr_SetString(socket_error, "getsockaddrarg: " + PyErr_SetString(PyExc_IOError, "getsockaddrarg: " "wrong format"); return 0; } @@ -1433,7 +1432,7 @@ #else _BT_HCI_MEMB(addr, family) = AF_BLUETOOTH; if (!PyArg_ParseTuple(args, "i", &_BT_HCI_MEMB(addr, dev))) { - PyErr_SetString(socket_error, "getsockaddrarg: " + PyErr_SetString(PyExc_IOError, "getsockaddrarg: " "wrong format"); return 0; } @@ -1450,7 +1449,7 @@ addr = (struct sockaddr_sco *)addr_ret; _BT_SCO_MEMB(addr, family) = AF_BLUETOOTH; if (!PyBytes_Check(args)) { - PyErr_SetString(socket_error, "getsockaddrarg: " + PyErr_SetString(PyExc_IOError, "getsockaddrarg: " "wrong format"); return 0; } @@ -1463,7 +1462,7 @@ } #endif default: - PyErr_SetString(socket_error, "getsockaddrarg: unknown Bluetooth protocol"); + PyErr_SetString(PyExc_IOError, "getsockaddrarg: unknown Bluetooth protocol"); return 0; } } @@ -1578,7 +1577,7 @@ /* More cases here... */ default: - PyErr_SetString(socket_error, "getsockaddrarg: bad family"); + PyErr_SetString(PyExc_IOError, "getsockaddrarg: bad family"); return 0; } @@ -1644,7 +1643,7 @@ return 1; #endif default: - PyErr_SetString(socket_error, "getsockaddrlen: " + PyErr_SetString(PyExc_IOError, "getsockaddrlen: " "unknown BT protocol"); return 0; @@ -1671,7 +1670,7 @@ /* More cases here... */ default: - PyErr_SetString(socket_error, "getsockaddrlen: bad family"); + PyErr_SetString(PyExc_IOError, "getsockaddrlen: bad family"); return 0; } @@ -1900,7 +1899,7 @@ #else if (buflen <= 0 || buflen > 1024) { #endif - PyErr_SetString(socket_error, + PyErr_SetString(PyExc_IOError, "getsockopt buflen out of range"); return NULL; } @@ -3241,7 +3240,7 @@ if (h->h_addrtype != af) { /* Let's get real error message to return */ - PyErr_SetString(socket_error, + PyErr_SetString(PyExc_IOError, (char *)strerror(EAFNOSUPPORT)); return NULL; @@ -3326,7 +3325,7 @@ #endif default: /* can't happen */ - PyErr_SetString(socket_error, + PyErr_SetString(PyExc_IOError, "unsupported address family"); return NULL; } @@ -3480,7 +3479,7 @@ break; #endif default: - PyErr_SetString(socket_error, "unsupported address family"); + PyErr_SetString(PyExc_IOError, "unsupported address family"); goto finally; } Py_BEGIN_ALLOW_THREADS @@ -3536,7 +3535,7 @@ sp = getservbyname(name, proto); Py_END_ALLOW_THREADS if (sp == NULL) { - PyErr_SetString(socket_error, "service/proto not found"); + PyErr_SetString(PyExc_IOError, "service/proto not found"); return NULL; } return PyLong_FromLong((long) ntohs(sp->s_port)); @@ -3573,7 +3572,7 @@ sp = getservbyport(htons((short)port), proto); Py_END_ALLOW_THREADS if (sp == NULL) { - PyErr_SetString(socket_error, "port/proto not found"); + PyErr_SetString(PyExc_IOError, "port/proto not found"); return NULL; } return PyUnicode_FromString(sp->s_name); @@ -3602,7 +3601,7 @@ sp = getprotobyname(name); Py_END_ALLOW_THREADS if (sp == NULL) { - PyErr_SetString(socket_error, "protocol not found"); + PyErr_SetString(PyExc_IOError, "protocol not found"); return NULL; } return PyLong_FromLong((long) sp->p_proto); @@ -3857,7 +3856,7 @@ return PyBytes_FromStringAndSize((char *)(&buf), sizeof(buf)); - PyErr_SetString(socket_error, + PyErr_SetString(PyExc_IOError, "illegal IP address string passed to inet_aton"); return NULL; @@ -3878,7 +3877,7 @@ packed_addr = inet_addr(ip_addr); if (packed_addr == INADDR_NONE) { /* invalid address */ - PyErr_SetString(socket_error, + PyErr_SetString(PyExc_IOError, "illegal IP address string passed to inet_aton"); return NULL; } @@ -3910,7 +3909,7 @@ } if (addr_len != sizeof(packed_addr)) { - PyErr_SetString(socket_error, + PyErr_SetString(PyExc_IOError, "packed IP wrong length for inet_ntoa"); return NULL; } @@ -3945,7 +3944,7 @@ #if !defined(ENABLE_IPV6) && defined(AF_INET6) if(af == AF_INET6) { - PyErr_SetString(socket_error, + PyErr_SetString(PyExc_IOError, "can't use AF_INET6, IPv6 is disabled"); return NULL; } @@ -3953,10 +3952,10 @@ retval = inet_pton(af, ip, packed); if (retval < 0) { - PyErr_SetFromErrno(socket_error); + PyErr_SetFromErrno(PyExc_IOError); return NULL; } else if (retval == 0) { - PyErr_SetString(socket_error, + PyErr_SetString(PyExc_IOError, "illegal IP address string passed to inet_pton"); return NULL; } else if (af == AF_INET) { @@ -3968,7 +3967,7 @@ sizeof(struct in6_addr)); #endif } else { - PyErr_SetString(socket_error, "unknown address family"); + PyErr_SetString(PyExc_IOError, "unknown address family"); return NULL; } } @@ -4020,7 +4019,7 @@ retval = inet_ntop(af, packed, ip, sizeof(ip)); if (!retval) { - PyErr_SetFromErrno(socket_error); + PyErr_SetFromErrno(PyExc_IOError); return NULL; } else { return PyUnicode_FromString(retval); @@ -4089,7 +4088,7 @@ } else if (pobj == Py_None) { pptr = (char *)NULL; } else { - PyErr_SetString(socket_error, "Int or String expected"); + PyErr_SetString(PyExc_IOError, "Int or String expected"); goto err; } memset(&hints, 0, sizeof(hints)); @@ -4186,7 +4185,7 @@ goto fail; } if (res->ai_next) { - PyErr_SetString(socket_error, + PyErr_SetString(PyExc_IOError, "sockaddr resolved to multiple addresses"); goto fail; } @@ -4194,7 +4193,7 @@ case AF_INET: { if (PyTuple_GET_SIZE(sa) != 2) { - PyErr_SetString(socket_error, + PyErr_SetString(PyExc_IOError, "IPv4 sockaddr must be 2 tuple"); goto fail; } @@ -4293,7 +4292,7 @@ ni = if_nameindex(); if (ni == NULL) { - PyErr_SetFromErrno(socket_error); + PyErr_SetFromErrno(PyExc_IOError); return NULL; } @@ -4339,7 +4338,7 @@ Py_DECREF(oname); if (index == 0) { /* if_nametoindex() doesn't set errno */ - PyErr_SetString(socket_error, "no interface with this name"); + PyErr_SetString(PyExc_IOError, "no interface with this name"); return NULL; } @@ -4362,7 +4361,7 @@ return NULL; if (if_indextoname(index, name) == NULL) { - PyErr_SetFromErrno(socket_error); + PyErr_SetFromErrno(PyExc_IOError); return NULL; } @@ -4572,27 +4571,24 @@ if (m == NULL) return NULL; - socket_error = PyErr_NewException("socket.error", - PyExc_IOError, NULL); - if (socket_error == NULL) - return NULL; - PySocketModuleAPI.error = socket_error; - Py_INCREF(socket_error); - PyModule_AddObject(m, "error", socket_error); + Py_INCREF(PyExc_IOError); + PySocketModuleAPI.error = PyExc_IOError; + Py_INCREF(PyExc_IOError); + PyModule_AddObject(m, "error", PyExc_IOError); socket_herror = PyErr_NewException("socket.herror", - socket_error, NULL); + PyExc_IOError, NULL); if (socket_herror == NULL) return NULL; Py_INCREF(socket_herror); PyModule_AddObject(m, "herror", socket_herror); - socket_gaierror = PyErr_NewException("socket.gaierror", socket_error, + socket_gaierror = PyErr_NewException("socket.gaierror", PyExc_IOError, NULL); if (socket_gaierror == NULL) return NULL; Py_INCREF(socket_gaierror); PyModule_AddObject(m, "gaierror", socket_gaierror); socket_timeout = PyErr_NewException("socket.timeout", - socket_error, NULL); + PyExc_IOError, NULL); if (socket_timeout == NULL) return NULL; PySocketModuleAPI.timeout_error = socket_timeout; diff -r 39873557ff4f -r 9bb6b71f172d Objects/exceptions.c --- a/Objects/exceptions.c Wed Jul 13 23:39:53 2011 +0200 +++ b/Objects/exceptions.c Thu Jul 14 01:01:27 2011 +0200 @@ -10,6 +10,20 @@ #include "osdefs.h" +/* Compatibility aliases */ +PyObject *PyExc_EnvironmentError = NULL; +PyObject *PyExc_OSError = NULL; +#ifdef MS_WINDOWS +PyObject *PyExc_WindowsError = NULL; +#endif +#ifdef __VMS +PyObject *PyExc_VMSError = NULL; +#endif + +/* The dict map from errno codes to IOError subclasses */ +static PyObject *errnomap = NULL; + + /* NOTE: If the exception class hierarchy changes, don't forget to update * Lib/test/exception_hierarchy.txt */ @@ -433,11 +447,13 @@ PyDoc_STR(EXCDOC), (traverseproc)EXCSTORE ## _traverse, \ (inquiry)EXCSTORE ## _clear, 0, 0, 0, 0, 0, 0, 0, &_ ## EXCBASE, \ 0, 0, 0, offsetof(Py ## EXCSTORE ## Object, dict), \ - (initproc)EXCSTORE ## _init, 0, BaseException_new,\ + (initproc)EXCSTORE ## _init, 0, 0, \ }; \ PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME -#define ComplexExtendsException(EXCBASE, EXCNAME, EXCSTORE, EXCDEALLOC, EXCMETHODS, EXCMEMBERS, EXCSTR, EXCDOC) \ +#define ComplexExtendsException(EXCBASE, EXCNAME, EXCSTORE, EXCNEW, \ + EXCMETHODS, EXCMEMBERS, EXCGETSET, \ + EXCSTR, EXCDOC) \ static PyTypeObject _PyExc_ ## EXCNAME = { \ PyVarObject_HEAD_INIT(NULL, 0) \ # EXCNAME, \ @@ -447,9 +463,9 @@ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \ PyDoc_STR(EXCDOC), (traverseproc)EXCSTORE ## _traverse, \ (inquiry)EXCSTORE ## _clear, 0, 0, 0, 0, EXCMETHODS, \ - EXCMEMBERS, 0, &_ ## EXCBASE, \ + EXCMEMBERS, EXCGETSET, &_ ## EXCBASE, \ 0, 0, 0, offsetof(Py ## EXCSTORE ## Object, dict), \ - (initproc)EXCSTORE ## _init, 0, BaseException_new,\ + (initproc)EXCSTORE ## _init, 0, EXCNEW,\ }; \ PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME @@ -534,7 +550,7 @@ }; ComplexExtendsException(PyExc_BaseException, SystemExit, SystemExit, - SystemExit_dealloc, 0, SystemExit_members, 0, + 0, 0, SystemExit_members, 0, 0, "Request to exit from the interpreter."); /* @@ -552,9 +568,13 @@ /* - * EnvironmentError extends Exception + * IOError extends Exception */ +#ifdef MS_WINDOWS +#include "errmap.h" +#endif + /* Where a function has a single filename, such as open() or some * of the os module functions, PyErr_SetFromErrnoWithFilename() is * called, giving a third argument which is the filename. But, so @@ -566,110 +586,215 @@ * means we need our own __str__() which prints out the filename * when it was supplied. */ -static int -EnvironmentError_init(PyEnvironmentErrorObject *self, PyObject *args, - PyObject *kwds) + +static PyObject * +IOError_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { + PyIOErrorObject *self = NULL; + Py_ssize_t nargs; + PyObject *myerrno = NULL, *strerror = NULL, *filename = NULL; PyObject *subslice = NULL; +#ifdef MS_WINDOWS + PyObject *winerror = NULL; + long winerrcode = 0; +#endif - if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1) - return -1; + if (!_PyArg_NoKeywords(type->tp_name, kwds)) + return NULL; + Py_INCREF(args); + nargs = PyTuple_GET_SIZE(args); - if (PyTuple_GET_SIZE(args) <= 1 || PyTuple_GET_SIZE(args) > 3) { - return 0; +#ifdef MS_WINDOWS + if (nargs >= 2 && nargs <= 4) { + if (!PyArg_UnpackTuple(args, "IOError", 2, 4, + &myerrno, &strerror, &filename, &winerror)) + goto error; + if (winerror && PyLong_Check(winerror)) { + long errcode; + PyObject *newargs; + Py_ssize_t i; + + winerrcode = PyLong_AsLong(winerror); + if (winerrcode == -1 && PyErr_Occurred()) + goto error; + /* Set errno to the corresponding POSIX errno (overriding + first argument). Windows Socket error codes (> 10000) + have the same value as their POSIX counterparts. + */ + if (winerrcode < 10000) + errcode = winerror_to_errno(winerrcode); + else + errcode = winerrcode; + myerrno = PyLong_FromLong(errcode); + if (!myerrno) + goto error; + newargs = PyTuple_New(nargs); + if (!newargs) + goto error; + PyTuple_SET_ITEM(newargs, 0, myerrno); + for (i = 1; i < nargs; i++) { + PyObject *val = PyTuple_GET_ITEM(args, i); + Py_INCREF(val); + PyTuple_SET_ITEM(newargs, i, val); + } + Py_DECREF(args); + args = newargs; + } + } +#else + if (nargs >= 2 && nargs <= 3) { + if (!PyArg_UnpackTuple(args, "IOError", 2, 3, + &myerrno, &strerror, &filename)) + goto error; + } +#endif + if (myerrno && PyLong_Check(myerrno) && + errnomap && (PyObject *) type == PyExc_IOError) { + PyObject *newtype; + newtype = PyDict_GetItem(errnomap, myerrno); + if (newtype) { + assert(PyType_Check(newtype)); + type = (PyTypeObject *) newtype; + } + else if (PyErr_Occurred()) + goto error; } - if (!PyArg_UnpackTuple(args, "EnvironmentError", 2, 3, - &myerrno, &strerror, &filename)) { - return -1; - } - Py_CLEAR(self->myerrno); /* replacing */ - self->myerrno = myerrno; - Py_INCREF(self->myerrno); + self = (PyIOErrorObject *) type->tp_alloc(type, 0); + if (!self) + goto error; - Py_CLEAR(self->strerror); /* replacing */ - self->strerror = strerror; - Py_INCREF(self->strerror); + self->dict = NULL; + self->traceback = self->cause = self->context = NULL; + self->written = -1; /* self->filename will remain Py_None otherwise */ - if (filename != NULL) { - Py_CLEAR(self->filename); /* replacing */ - self->filename = filename; - Py_INCREF(self->filename); + if (filename && filename != Py_None) { + if ((PyObject *) type == PyExc_BlockingIOError && + PyNumber_Check(filename)) { + /* BlockingIOError's 3rd argument can be the number of + * characters written. + */ + self->written = PyNumber_AsSsize_t(filename, PyExc_ValueError); + if (self->written == -1 && PyErr_Occurred()) + goto error; + } + else { + Py_INCREF(filename); + self->filename = filename; - subslice = PyTuple_GetSlice(args, 0, 2); - if (!subslice) - return -1; + if (nargs >= 2 && nargs <= 3) { + /* filename is removed from the args tuple (for compatibility + purposes, see test_exceptions.py) */ + subslice = PyTuple_GetSlice(args, 0, 2); + if (!subslice) + goto error; - Py_DECREF(self->args); /* replacing args */ - self->args = subslice; + Py_DECREF(args); /* replacing args */ + args = subslice; + } + } } + + /* Steals the reference to args */ + self->args = args; + args = NULL; + + Py_XINCREF(myerrno); + self->myerrno = myerrno; + + Py_XINCREF(strerror); + self->strerror = strerror; + +#ifdef MS_WINDOWS + Py_XINCREF(winerror); + self->winerror = winerror; +#endif + + return (PyObject *) self; + +error: + Py_XDECREF(args); + Py_XDECREF(self); + return NULL; +} + +static int +IOError_init(PySyntaxErrorObject *self, PyObject *args, PyObject *kwds) +{ + /* Everything already done in IOError_new */ return 0; } static int -EnvironmentError_clear(PyEnvironmentErrorObject *self) +IOError_clear(PyIOErrorObject *self) { Py_CLEAR(self->myerrno); Py_CLEAR(self->strerror); Py_CLEAR(self->filename); +#ifdef MS_WINDOWS + Py_CLEAR(self->winerror); +#endif return BaseException_clear((PyBaseExceptionObject *)self); } static void -EnvironmentError_dealloc(PyEnvironmentErrorObject *self) +IOError_dealloc(PyIOErrorObject *self) { _PyObject_GC_UNTRACK(self); - EnvironmentError_clear(self); + IOError_clear(self); Py_TYPE(self)->tp_free((PyObject *)self); } static int -EnvironmentError_traverse(PyEnvironmentErrorObject *self, visitproc visit, +IOError_traverse(PyIOErrorObject *self, visitproc visit, void *arg) { Py_VISIT(self->myerrno); Py_VISIT(self->strerror); Py_VISIT(self->filename); +#ifdef MS_WINDOWS + Py_VISIT(self->winerror); +#endif return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg); } static PyObject * -EnvironmentError_str(PyEnvironmentErrorObject *self) +IOError_str(PyIOErrorObject *self) { +#ifdef MS_WINDOWS + /* If available, winerror has the priority over myerrno */ + if (self->winerror && self->filename) + return PyUnicode_FromFormat("[Error %S] %S: %R", + self->winerror ? self->winerror: Py_None, + self->strerror ? self->strerror: Py_None, + self->filename); + if (self->winerror && self->strerror) + return PyUnicode_FromFormat("[Error %S] %S", + self->winerror ? self->winerror: Py_None, + self->strerror ? self->strerror: Py_None); +#endif if (self->filename) return PyUnicode_FromFormat("[Errno %S] %S: %R", self->myerrno ? self->myerrno: Py_None, self->strerror ? self->strerror: Py_None, self->filename); - else if (self->myerrno && self->strerror) + if (self->myerrno && self->strerror) return PyUnicode_FromFormat("[Errno %S] %S", self->myerrno ? self->myerrno: Py_None, self->strerror ? self->strerror: Py_None); - else - return BaseException_str((PyBaseExceptionObject *)self); + return BaseException_str((PyBaseExceptionObject *)self); } -static PyMemberDef EnvironmentError_members[] = { - {"errno", T_OBJECT, offsetof(PyEnvironmentErrorObject, myerrno), 0, - PyDoc_STR("exception errno")}, - {"strerror", T_OBJECT, offsetof(PyEnvironmentErrorObject, strerror), 0, - PyDoc_STR("exception strerror")}, - {"filename", T_OBJECT, offsetof(PyEnvironmentErrorObject, filename), 0, - PyDoc_STR("exception filename")}, - {NULL} /* Sentinel */ -}; - - static PyObject * -EnvironmentError_reduce(PyEnvironmentErrorObject *self) +IOError_reduce(PyIOErrorObject *self) { PyObject *args = self->args; PyObject *res = NULL, *tmp; /* self->args is only the first two real arguments if there was a - * file name given to EnvironmentError. */ + * file name given to IOError. */ if (PyTuple_GET_SIZE(args) == 2 && self->filename) { args = PyTuple_New(3); if (!args) return NULL; @@ -695,144 +820,89 @@ return res; } +static PyObject * +IOError_written_get(PyIOErrorObject *self, void *context) +{ + if (self->written == -1) { + PyErr_SetString(PyExc_AttributeError, "characters_written"); + return NULL; + } + return PyLong_FromSsize_t(self->written); +} -static PyMethodDef EnvironmentError_methods[] = { - {"__reduce__", (PyCFunction)EnvironmentError_reduce, METH_NOARGS}, +static int +IOError_written_set(PyIOErrorObject *self, PyObject *arg, void *context) +{ + Py_ssize_t n; + n = PyNumber_AsSsize_t(arg, PyExc_ValueError); + if (n == -1 && PyErr_Occurred()) + return -1; + self->written = n; + return 0; +} + +static PyMemberDef IOError_members[] = { + {"errno", T_OBJECT, offsetof(PyIOErrorObject, myerrno), 0, + PyDoc_STR("POSIX exception code")}, + {"strerror", T_OBJECT, offsetof(PyIOErrorObject, strerror), 0, + PyDoc_STR("exception strerror")}, + {"filename", T_OBJECT, offsetof(PyIOErrorObject, filename), 0, + PyDoc_STR("exception filename")}, +#ifdef MS_WINDOWS + {"winerror", T_OBJECT, offsetof(PyIOErrorObject, winerror), 0, + PyDoc_STR("Win32 exception code")}, +#endif + {NULL} /* Sentinel */ +}; + +static PyMethodDef IOError_methods[] = { + {"__reduce__", (PyCFunction)IOError_reduce, METH_NOARGS}, {NULL} }; -ComplexExtendsException(PyExc_Exception, EnvironmentError, - EnvironmentError, EnvironmentError_dealloc, - EnvironmentError_methods, EnvironmentError_members, - EnvironmentError_str, +static PyGetSetDef IOError_getset[] = { + {"characters_written", (getter) IOError_written_get, + (setter) IOError_written_set, NULL}, + {NULL} +}; + + +ComplexExtendsException(PyExc_Exception, IOError, + IOError, IOError_new, + IOError_methods, IOError_members, IOError_getset, + IOError_str, "Base class for I/O related errors."); /* - * IOError extends EnvironmentError + * Various IOError subclasses */ -MiddlingExtendsException(PyExc_EnvironmentError, IOError, - EnvironmentError, "I/O operation failed."); - - -/* - * OSError extends EnvironmentError - */ -MiddlingExtendsException(PyExc_EnvironmentError, OSError, - EnvironmentError, "OS system call failed."); - - -/* - * WindowsError extends OSError - */ -#ifdef MS_WINDOWS -#include "errmap.h" - -static int -WindowsError_clear(PyWindowsErrorObject *self) -{ - Py_CLEAR(self->myerrno); - Py_CLEAR(self->strerror); - Py_CLEAR(self->filename); - Py_CLEAR(self->winerror); - return BaseException_clear((PyBaseExceptionObject *)self); -} - -static void -WindowsError_dealloc(PyWindowsErrorObject *self) -{ - _PyObject_GC_UNTRACK(self); - WindowsError_clear(self); - Py_TYPE(self)->tp_free((PyObject *)self); -} - -static int -WindowsError_traverse(PyWindowsErrorObject *self, visitproc visit, void *arg) -{ - Py_VISIT(self->myerrno); - Py_VISIT(self->strerror); - Py_VISIT(self->filename); - Py_VISIT(self->winerror); - return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg); -} - -static int -WindowsError_init(PyWindowsErrorObject *self, PyObject *args, PyObject *kwds) -{ - PyObject *o_errcode = NULL; - long errcode; - long posix_errno; - - if (EnvironmentError_init((PyEnvironmentErrorObject *)self, args, kwds) - == -1) - return -1; - - if (self->myerrno == NULL) - return 0; - - /* Set errno to the POSIX errno, and winerror to the Win32 - error code. */ - errcode = PyLong_AsLong(self->myerrno); - if (errcode == -1 && PyErr_Occurred()) - return -1; - posix_errno = winerror_to_errno(errcode); - - Py_CLEAR(self->winerror); - self->winerror = self->myerrno; - - o_errcode = PyLong_FromLong(posix_errno); - if (!o_errcode) - return -1; - - self->myerrno = o_errcode; - - return 0; -} - - -static PyObject * -WindowsError_str(PyWindowsErrorObject *self) -{ - if (self->filename) - return PyUnicode_FromFormat("[Error %S] %S: %R", - self->winerror ? self->winerror: Py_None, - self->strerror ? self->strerror: Py_None, - self->filename); - else if (self->winerror && self->strerror) - return PyUnicode_FromFormat("[Error %S] %S", - self->winerror ? self->winerror: Py_None, - self->strerror ? self->strerror: Py_None); - else - return EnvironmentError_str((PyEnvironmentErrorObject *)self); -} - -static PyMemberDef WindowsError_members[] = { - {"errno", T_OBJECT, offsetof(PyWindowsErrorObject, myerrno), 0, - PyDoc_STR("POSIX exception code")}, - {"strerror", T_OBJECT, offsetof(PyWindowsErrorObject, strerror), 0, - PyDoc_STR("exception strerror")}, - {"filename", T_OBJECT, offsetof(PyWindowsErrorObject, filename), 0, - PyDoc_STR("exception filename")}, - {"winerror", T_OBJECT, offsetof(PyWindowsErrorObject, winerror), 0, - PyDoc_STR("Win32 exception code")}, - {NULL} /* Sentinel */ -}; - -ComplexExtendsException(PyExc_OSError, WindowsError, WindowsError, - WindowsError_dealloc, 0, WindowsError_members, - WindowsError_str, "MS-Windows OS system call failed."); - -#endif /* MS_WINDOWS */ - - -/* - * VMSError extends OSError (I think) - */ -#ifdef __VMS -MiddlingExtendsException(PyExc_OSError, VMSError, EnvironmentError, - "OpenVMS OS system call failed."); -#endif - +MiddlingExtendsException(PyExc_IOError, BlockingIOError, IOError, + "I/O operation would block."); +MiddlingExtendsException(PyExc_IOError, ConnectionError, IOError, + "Connection error."); +MiddlingExtendsException(PyExc_ConnectionError, ConnectionAbortedError, IOError, + "Connection aborted."); +MiddlingExtendsException(PyExc_ConnectionError, ConnectionRefusedError, IOError, + "Connection refused."); +MiddlingExtendsException(PyExc_ConnectionError, ConnectionResetError, IOError, + "Connection reset."); +MiddlingExtendsException(PyExc_IOError, FileSystemError, IOError, + "Generic filesystem error."); +MiddlingExtendsException(PyExc_FileSystemError, FileExistsError, IOError, + "File already exists."); +MiddlingExtendsException(PyExc_FileSystemError, FileNotFoundError, IOError, + "File not found."); +MiddlingExtendsException(PyExc_FileSystemError, IsADirectoryError, IOError, + "Operation doesn't work on directories."); +MiddlingExtendsException(PyExc_FileSystemError, NotADirectoryError, IOError, + "Operation only works on directories."); +MiddlingExtendsException(PyExc_IOError, FileDescriptorError, IOError, + "Bad file descriptor."); +MiddlingExtendsException(PyExc_IOError, PermissionError, IOError, + "Not enough permissions."); +MiddlingExtendsException(PyExc_IOError, TimeoutError, IOError, + "Timeout expired."); /* * EOFError extends Exception @@ -1044,7 +1114,7 @@ }; ComplexExtendsException(PyExc_Exception, SyntaxError, SyntaxError, - SyntaxError_dealloc, 0, SyntaxError_members, + 0, 0, SyntaxError_members, 0, SyntaxError_str, "Invalid syntax."); @@ -1098,7 +1168,7 @@ } ComplexExtendsException(PyExc_LookupError, KeyError, BaseException, - 0, 0, 0, KeyError_str, "Mapping key not found."); + 0, 0, 0, 0, KeyError_str, "Mapping key not found."); /* @@ -1966,6 +2036,42 @@ if (PyDict_SetItemString(bdict, # TYPE, PyExc_ ## TYPE)) \ Py_FatalError("Module dictionary insertion problem."); +#define INIT_ALIAS(NAME, TYPE) Py_INCREF(PyExc_ ## TYPE); \ + PyExc_ ## NAME = PyExc_ ## TYPE; \ + if (PyDict_SetItemString(bdict, # NAME, PyExc_ ## NAME)) \ + Py_FatalError("Module dictionary insertion problem."); + +#define ADD_ERRNO(TYPE, CODE) { \ + PyObject *_code = PyLong_FromLong(CODE); \ + assert(_PyObject_RealIsSubclass(PyExc_ ## TYPE, PyExc_IOError)); \ + if (!_code || PyDict_SetItem(errnomap, _code, PyExc_ ## TYPE)) \ + Py_FatalError("errmap insertion problem."); \ + } + +#ifdef MS_WINDOWS +#include +#if defined(WSAEALREADY) && !defined(EALREADY) +#define EALREADY WSAEALREADY +#endif +#if defined(WSAECONNABORTED) && !defined(ECONNABORTED) +#define ECONNABORTED WSAECONNABORTED +#endif +#if defined(WSAECONNREFUSED) && !defined(ECONNREFUSED) +#define ECONNREFUSED WSAECONNREFUSED +#endif +#if defined(WSAECONNRESET) && !defined(ECONNRESET) +#define ECONNRESET WSAECONNRESET +#endif +#if defined(WSAEINPROGRESS) && !defined(EINPROGRESS) +#define EINPROGRESS WSAEINPROGRESS +#endif +#if defined(WSAETIMEDOUT) && !defined(ETIMEDOUT) +#define ETIMEDOUT WSAETIMEDOUT +#endif +#if defined(WSAEWOULDBLOCK) && !defined(EWOULDBLOCK) +#define EWOULDBLOCK WSAEWOULDBLOCK +#endif +#endif /* MS_WINDOWS */ void _PyExc_Init(void) @@ -1980,15 +2086,7 @@ PRE_INIT(SystemExit) PRE_INIT(KeyboardInterrupt) PRE_INIT(ImportError) - PRE_INIT(EnvironmentError) PRE_INIT(IOError) - PRE_INIT(OSError) -#ifdef MS_WINDOWS - PRE_INIT(WindowsError) -#endif -#ifdef __VMS - PRE_INIT(VMSError) -#endif PRE_INIT(EOFError) PRE_INIT(RuntimeError) PRE_INIT(NotImplementedError) @@ -2028,6 +2126,22 @@ PRE_INIT(BytesWarning) PRE_INIT(ResourceWarning) + /* IOError subclasses */ + PRE_INIT(BlockingIOError); + PRE_INIT(ConnectionError); + PRE_INIT(FileSystemError); + + PRE_INIT(ConnectionAbortedError); + PRE_INIT(ConnectionRefusedError); + PRE_INIT(ConnectionResetError); + PRE_INIT(FileDescriptorError); + PRE_INIT(FileExistsError); + PRE_INIT(FileNotFoundError); + PRE_INIT(IsADirectoryError); + PRE_INIT(NotADirectoryError); + PRE_INIT(PermissionError); + PRE_INIT(TimeoutError); + bltinmod = PyImport_ImportModule("builtins"); if (bltinmod == NULL) Py_FatalError("exceptions bootstrapping error."); @@ -2043,14 +2157,14 @@ POST_INIT(SystemExit) POST_INIT(KeyboardInterrupt) POST_INIT(ImportError) - POST_INIT(EnvironmentError) POST_INIT(IOError) - POST_INIT(OSError) + INIT_ALIAS(EnvironmentError, IOError) + INIT_ALIAS(OSError, IOError) #ifdef MS_WINDOWS - POST_INIT(WindowsError) + INIT_ALIAS(WindowsError, IOError) #endif #ifdef __VMS - POST_INIT(VMSError) + INIT_ALIAS(VMSError, IOError) #endif POST_INIT(EOFError) POST_INIT(RuntimeError) @@ -2091,6 +2205,41 @@ POST_INIT(BytesWarning) POST_INIT(ResourceWarning) + errnomap = PyDict_New(); + if (!errnomap) + Py_FatalError("Cannot allocate map from errnos to IOError subclasses"); + + /* IOError subclasses */ + POST_INIT(ConnectionError); + POST_INIT(FileSystemError); + + POST_INIT(BlockingIOError); + ADD_ERRNO(BlockingIOError, EAGAIN); + ADD_ERRNO(BlockingIOError, EALREADY); + ADD_ERRNO(BlockingIOError, EINPROGRESS); + ADD_ERRNO(BlockingIOError, EWOULDBLOCK); + POST_INIT(ConnectionAbortedError); + ADD_ERRNO(ConnectionAbortedError, ECONNABORTED); + POST_INIT(ConnectionRefusedError); + ADD_ERRNO(ConnectionRefusedError, ECONNREFUSED); + POST_INIT(ConnectionResetError); + ADD_ERRNO(ConnectionResetError, ECONNRESET); + POST_INIT(FileDescriptorError); + ADD_ERRNO(FileDescriptorError, EBADF); + POST_INIT(FileExistsError); + ADD_ERRNO(FileExistsError, EEXIST); + POST_INIT(FileNotFoundError); + ADD_ERRNO(FileNotFoundError, ENOENT); + POST_INIT(IsADirectoryError); + ADD_ERRNO(IsADirectoryError, EISDIR); + POST_INIT(NotADirectoryError); + ADD_ERRNO(NotADirectoryError, ENOTDIR); + POST_INIT(PermissionError); + ADD_ERRNO(PermissionError, EACCES); + ADD_ERRNO(PermissionError, EPERM); + POST_INIT(TimeoutError); + ADD_ERRNO(TimeoutError, ETIMEDOUT); + preallocate_memerrors(); PyExc_RecursionErrorInst = BaseException_new(&_PyExc_RuntimeError, NULL, NULL); @@ -2124,4 +2273,5 @@ { Py_CLEAR(PyExc_RecursionErrorInst); free_preallocated_memerrors(); + Py_CLEAR(errnomap); } diff -r 39873557ff4f -r 9bb6b71f172d Python/errors.c --- a/Python/errors.c Wed Jul 13 23:39:53 2011 +0200 +++ b/Python/errors.c Thu Jul 14 01:01:27 2011 +0200 @@ -496,10 +496,11 @@ return NULL; } - if (filenameObject != NULL) - v = Py_BuildValue("(iOO)", err, message, filenameObject); - else - v = Py_BuildValue("(iO)", err, message); + if (filenameObject == NULL) + filenameObject = Py_None; + /* This is the constructor signature for passing a Windows error code. + The POSIX translation will be figured out by the constructor. */ + v = Py_BuildValue("(iOOi)", 0, message, filenameObject, err); Py_DECREF(message); if (v != NULL) { diff -r 39873557ff4f -r 9bb6b71f172d TODO-3151.txt --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/TODO-3151.txt Thu Jul 14 01:01:27 2011 +0200 @@ -0,0 +1,19 @@ + +Step 1 +------ + +Add deprecations: + +- rename all PyExc_WindowsError to PyExc_IOError +- rename all PyExc_OSError to PyExc_IOError +- rename all PyExc_EnvironmentError to PyExc_IOError +- rename all WindowsError to IOError +- rename all OSError to IOError +- rename all EnvironmentError to IOError +- LOAD_OLD_GLOBAL + + +Step 2 +------ + +Done.