• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2     An implementation of the new I/O lib as defined by PEP 3116 - "New I/O"
3 
4     Classes defined here: UnsupportedOperation, BlockingIOError.
5     Functions defined here: open().
6 
7     Mostly written by Amaury Forgeot d'Arc
8 */
9 
10 #define PY_SSIZE_T_CLEAN
11 #include "Python.h"
12 #include "structmember.h"
13 #include "_iomodule.h"
14 
15 #ifdef HAVE_SYS_TYPES_H
16 #include <sys/types.h>
17 #endif /* HAVE_SYS_TYPES_H */
18 
19 #ifdef HAVE_SYS_STAT_H
20 #include <sys/stat.h>
21 #endif /* HAVE_SYS_STAT_H */
22 
23 #ifdef MS_WINDOWS
24 #include <consoleapi.h>
25 #endif
26 
27 /* Various interned strings */
28 
29 PyObject *_PyIO_str_close;
30 PyObject *_PyIO_str_closed;
31 PyObject *_PyIO_str_decode;
32 PyObject *_PyIO_str_encode;
33 PyObject *_PyIO_str_fileno;
34 PyObject *_PyIO_str_flush;
35 PyObject *_PyIO_str_getstate;
36 PyObject *_PyIO_str_isatty;
37 PyObject *_PyIO_str_newlines;
38 PyObject *_PyIO_str_nl;
39 PyObject *_PyIO_str_read;
40 PyObject *_PyIO_str_read1;
41 PyObject *_PyIO_str_readable;
42 PyObject *_PyIO_str_readall;
43 PyObject *_PyIO_str_readinto;
44 PyObject *_PyIO_str_readline;
45 PyObject *_PyIO_str_reset;
46 PyObject *_PyIO_str_seek;
47 PyObject *_PyIO_str_seekable;
48 PyObject *_PyIO_str_setstate;
49 PyObject *_PyIO_str_tell;
50 PyObject *_PyIO_str_truncate;
51 PyObject *_PyIO_str_writable;
52 PyObject *_PyIO_str_write;
53 
54 PyObject *_PyIO_empty_str;
55 PyObject *_PyIO_empty_bytes;
56 PyObject *_PyIO_zero;
57 
58 PyDoc_STRVAR(module_doc,
59 "The io module provides the Python interfaces to stream handling. The\n"
60 "builtin open function is defined in this module.\n"
61 "\n"
62 "At the top of the I/O hierarchy is the abstract base class IOBase. It\n"
63 "defines the basic interface to a stream. Note, however, that there is no\n"
64 "separation between reading and writing to streams; implementations are\n"
65 "allowed to raise an IOError if they do not support a given operation.\n"
66 "\n"
67 "Extending IOBase is RawIOBase which deals simply with the reading and\n"
68 "writing of raw bytes to a stream. FileIO subclasses RawIOBase to provide\n"
69 "an interface to OS files.\n"
70 "\n"
71 "BufferedIOBase deals with buffering on a raw byte stream (RawIOBase). Its\n"
72 "subclasses, BufferedWriter, BufferedReader, and BufferedRWPair buffer\n"
73 "streams that are readable, writable, and both respectively.\n"
74 "BufferedRandom provides a buffered interface to random access\n"
75 "streams. BytesIO is a simple stream of in-memory bytes.\n"
76 "\n"
77 "Another IOBase subclass, TextIOBase, deals with the encoding and decoding\n"
78 "of streams into text. TextIOWrapper, which extends it, is a buffered text\n"
79 "interface to a buffered raw stream (`BufferedIOBase`). Finally, StringIO\n"
80 "is an in-memory stream for text.\n"
81 "\n"
82 "Argument names are not part of the specification, and only the arguments\n"
83 "of open() are intended to be used as keyword arguments.\n"
84 "\n"
85 "data:\n"
86 "\n"
87 "DEFAULT_BUFFER_SIZE\n"
88 "\n"
89 "   An int containing the default buffer size used by the module's buffered\n"
90 "   I/O classes. open() uses the file's blksize (as obtained by os.stat) if\n"
91 "   possible.\n"
92     );
93 
94 
95 /*
96  * The main open() function
97  */
98 /*[clinic input]
99 module _io
100 
101 _io.open
102     file: object
103     mode: str = "r"
104     buffering: int = -1
105     encoding: str(accept={str, NoneType}) = NULL
106     errors: str(accept={str, NoneType}) = NULL
107     newline: str(accept={str, NoneType}) = NULL
108     closefd: int(c_default="1") = True
109     opener: object = None
110 
111 Open file and return a stream.  Raise IOError upon failure.
112 
113 file is either a text or byte string giving the name (and the path
114 if the file isn't in the current working directory) of the file to
115 be opened or an integer file descriptor of the file to be
116 wrapped. (If a file descriptor is given, it is closed when the
117 returned I/O object is closed, unless closefd is set to False.)
118 
119 mode is an optional string that specifies the mode in which the file
120 is opened. It defaults to 'r' which means open for reading in text
121 mode.  Other common values are 'w' for writing (truncating the file if
122 it already exists), 'x' for creating and writing to a new file, and
123 'a' for appending (which on some Unix systems, means that all writes
124 append to the end of the file regardless of the current seek position).
125 In text mode, if encoding is not specified the encoding used is platform
126 dependent: locale.getpreferredencoding(False) is called to get the
127 current locale encoding. (For reading and writing raw bytes use binary
128 mode and leave encoding unspecified.) The available modes are:
129 
130 ========= ===============================================================
131 Character Meaning
132 --------- ---------------------------------------------------------------
133 'r'       open for reading (default)
134 'w'       open for writing, truncating the file first
135 'x'       create a new file and open it for writing
136 'a'       open for writing, appending to the end of the file if it exists
137 'b'       binary mode
138 't'       text mode (default)
139 '+'       open a disk file for updating (reading and writing)
140 'U'       universal newline mode (deprecated)
141 ========= ===============================================================
142 
143 The default mode is 'rt' (open for reading text). For binary random
144 access, the mode 'w+b' opens and truncates the file to 0 bytes, while
145 'r+b' opens the file without truncation. The 'x' mode implies 'w' and
146 raises an `FileExistsError` if the file already exists.
147 
148 Python distinguishes between files opened in binary and text modes,
149 even when the underlying operating system doesn't. Files opened in
150 binary mode (appending 'b' to the mode argument) return contents as
151 bytes objects without any decoding. In text mode (the default, or when
152 't' is appended to the mode argument), the contents of the file are
153 returned as strings, the bytes having been first decoded using a
154 platform-dependent encoding or using the specified encoding if given.
155 
156 'U' mode is deprecated and will raise an exception in future versions
157 of Python.  It has no effect in Python 3.  Use newline to control
158 universal newlines mode.
159 
160 buffering is an optional integer used to set the buffering policy.
161 Pass 0 to switch buffering off (only allowed in binary mode), 1 to select
162 line buffering (only usable in text mode), and an integer > 1 to indicate
163 the size of a fixed-size chunk buffer.  When no buffering argument is
164 given, the default buffering policy works as follows:
165 
166 * Binary files are buffered in fixed-size chunks; the size of the buffer
167   is chosen using a heuristic trying to determine the underlying device's
168   "block size" and falling back on `io.DEFAULT_BUFFER_SIZE`.
169   On many systems, the buffer will typically be 4096 or 8192 bytes long.
170 
171 * "Interactive" text files (files for which isatty() returns True)
172   use line buffering.  Other text files use the policy described above
173   for binary files.
174 
175 encoding is the name of the encoding used to decode or encode the
176 file. This should only be used in text mode. The default encoding is
177 platform dependent, but any encoding supported by Python can be
178 passed.  See the codecs module for the list of supported encodings.
179 
180 errors is an optional string that specifies how encoding errors are to
181 be handled---this argument should not be used in binary mode. Pass
182 'strict' to raise a ValueError exception if there is an encoding error
183 (the default of None has the same effect), or pass 'ignore' to ignore
184 errors. (Note that ignoring encoding errors can lead to data loss.)
185 See the documentation for codecs.register or run 'help(codecs.Codec)'
186 for a list of the permitted encoding error strings.
187 
188 newline controls how universal newlines works (it only applies to text
189 mode). It can be None, '', '\n', '\r', and '\r\n'.  It works as
190 follows:
191 
192 * On input, if newline is None, universal newlines mode is
193   enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
194   these are translated into '\n' before being returned to the
195   caller. If it is '', universal newline mode is enabled, but line
196   endings are returned to the caller untranslated. If it has any of
197   the other legal values, input lines are only terminated by the given
198   string, and the line ending is returned to the caller untranslated.
199 
200 * On output, if newline is None, any '\n' characters written are
201   translated to the system default line separator, os.linesep. If
202   newline is '' or '\n', no translation takes place. If newline is any
203   of the other legal values, any '\n' characters written are translated
204   to the given string.
205 
206 If closefd is False, the underlying file descriptor will be kept open
207 when the file is closed. This does not work when a file name is given
208 and must be True in that case.
209 
210 A custom opener can be used by passing a callable as *opener*. The
211 underlying file descriptor for the file object is then obtained by
212 calling *opener* with (*file*, *flags*). *opener* must return an open
213 file descriptor (passing os.open as *opener* results in functionality
214 similar to passing None).
215 
216 open() returns a file object whose type depends on the mode, and
217 through which the standard file operations such as reading and writing
218 are performed. When open() is used to open a file in a text mode ('w',
219 'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open
220 a file in a binary mode, the returned class varies: in read binary
221 mode, it returns a BufferedReader; in write binary and append binary
222 modes, it returns a BufferedWriter, and in read/write mode, it returns
223 a BufferedRandom.
224 
225 It is also possible to use a string or bytearray as a file for both
226 reading and writing. For strings StringIO can be used like a file
227 opened in a text mode, and for bytes a BytesIO can be used like a file
228 opened in a binary mode.
229 [clinic start generated code]*/
230 
231 static PyObject *
_io_open_impl(PyObject * module,PyObject * file,const char * mode,int buffering,const char * encoding,const char * errors,const char * newline,int closefd,PyObject * opener)232 _io_open_impl(PyObject *module, PyObject *file, const char *mode,
233               int buffering, const char *encoding, const char *errors,
234               const char *newline, int closefd, PyObject *opener)
235 /*[clinic end generated code: output=aefafc4ce2b46dc0 input=f4e1ca75223987bc]*/
236 {
237     unsigned i;
238 
239     int creating = 0, reading = 0, writing = 0, appending = 0, updating = 0;
240     int text = 0, binary = 0, universal = 0;
241 
242     char rawmode[6], *m;
243     int line_buffering, is_number;
244     long isatty;
245 
246     PyObject *raw, *modeobj = NULL, *buffer, *wrapper, *result = NULL, *path_or_fd = NULL;
247 
248     _Py_IDENTIFIER(_blksize);
249     _Py_IDENTIFIER(isatty);
250     _Py_IDENTIFIER(mode);
251     _Py_IDENTIFIER(close);
252 
253     is_number = PyNumber_Check(file);
254 
255     if (is_number) {
256         path_or_fd = file;
257         Py_INCREF(path_or_fd);
258     } else {
259         path_or_fd = PyOS_FSPath(file);
260         if (path_or_fd == NULL) {
261             return NULL;
262         }
263     }
264 
265     if (!is_number &&
266         !PyUnicode_Check(path_or_fd) &&
267         !PyBytes_Check(path_or_fd)) {
268         PyErr_Format(PyExc_TypeError, "invalid file: %R", file);
269         goto error;
270     }
271 
272     /* Decode mode */
273     for (i = 0; i < strlen(mode); i++) {
274         char c = mode[i];
275 
276         switch (c) {
277         case 'x':
278             creating = 1;
279             break;
280         case 'r':
281             reading = 1;
282             break;
283         case 'w':
284             writing = 1;
285             break;
286         case 'a':
287             appending = 1;
288             break;
289         case '+':
290             updating = 1;
291             break;
292         case 't':
293             text = 1;
294             break;
295         case 'b':
296             binary = 1;
297             break;
298         case 'U':
299             universal = 1;
300             reading = 1;
301             break;
302         default:
303             goto invalid_mode;
304         }
305 
306         /* c must not be duplicated */
307         if (strchr(mode+i+1, c)) {
308           invalid_mode:
309             PyErr_Format(PyExc_ValueError, "invalid mode: '%s'", mode);
310             goto error;
311         }
312 
313     }
314 
315     m = rawmode;
316     if (creating)  *(m++) = 'x';
317     if (reading)   *(m++) = 'r';
318     if (writing)   *(m++) = 'w';
319     if (appending) *(m++) = 'a';
320     if (updating)  *(m++) = '+';
321     *m = '\0';
322 
323     /* Parameters validation */
324     if (universal) {
325         if (creating || writing || appending || updating) {
326             PyErr_SetString(PyExc_ValueError,
327                             "mode U cannot be combined with x', 'w', 'a', or '+'");
328             goto error;
329         }
330         if (PyErr_WarnEx(PyExc_DeprecationWarning,
331                          "'U' mode is deprecated", 1) < 0)
332             goto error;
333         reading = 1;
334     }
335 
336     if (text && binary) {
337         PyErr_SetString(PyExc_ValueError,
338                         "can't have text and binary mode at once");
339         goto error;
340     }
341 
342     if (creating + reading + writing + appending > 1) {
343         PyErr_SetString(PyExc_ValueError,
344                         "must have exactly one of create/read/write/append mode");
345         goto error;
346     }
347 
348     if (binary && encoding != NULL) {
349         PyErr_SetString(PyExc_ValueError,
350                         "binary mode doesn't take an encoding argument");
351         goto error;
352     }
353 
354     if (binary && errors != NULL) {
355         PyErr_SetString(PyExc_ValueError,
356                         "binary mode doesn't take an errors argument");
357         goto error;
358     }
359 
360     if (binary && newline != NULL) {
361         PyErr_SetString(PyExc_ValueError,
362                         "binary mode doesn't take a newline argument");
363         goto error;
364     }
365 
366     /* Create the Raw file stream */
367     {
368         PyObject *RawIO_class = (PyObject *)&PyFileIO_Type;
369 #ifdef MS_WINDOWS
370         if (!Py_LegacyWindowsStdioFlag && _PyIO_get_console_type(path_or_fd) != '\0') {
371             RawIO_class = (PyObject *)&PyWindowsConsoleIO_Type;
372             encoding = "utf-8";
373         }
374 #endif
375         raw = PyObject_CallFunction(RawIO_class,
376                                     "OsiO", path_or_fd, rawmode, closefd, opener);
377     }
378 
379     if (raw == NULL)
380         goto error;
381     result = raw;
382 
383     Py_DECREF(path_or_fd);
384     path_or_fd = NULL;
385 
386     modeobj = PyUnicode_FromString(mode);
387     if (modeobj == NULL)
388         goto error;
389 
390     /* buffering */
391     {
392         PyObject *res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
393         if (res == NULL)
394             goto error;
395         isatty = PyLong_AsLong(res);
396         Py_DECREF(res);
397         if (isatty == -1 && PyErr_Occurred())
398             goto error;
399     }
400 
401     if (buffering == 1 || (buffering < 0 && isatty)) {
402         buffering = -1;
403         line_buffering = 1;
404     }
405     else
406         line_buffering = 0;
407 
408     if (buffering < 0) {
409         PyObject *blksize_obj;
410         blksize_obj = _PyObject_GetAttrId(raw, &PyId__blksize);
411         if (blksize_obj == NULL)
412             goto error;
413         buffering = PyLong_AsLong(blksize_obj);
414         Py_DECREF(blksize_obj);
415         if (buffering == -1 && PyErr_Occurred())
416             goto error;
417     }
418     if (buffering < 0) {
419         PyErr_SetString(PyExc_ValueError,
420                         "invalid buffering size");
421         goto error;
422     }
423 
424     /* if not buffering, returns the raw file object */
425     if (buffering == 0) {
426         if (!binary) {
427             PyErr_SetString(PyExc_ValueError,
428                             "can't have unbuffered text I/O");
429             goto error;
430         }
431 
432         Py_DECREF(modeobj);
433         return result;
434     }
435 
436     /* wraps into a buffered file */
437     {
438         PyObject *Buffered_class;
439 
440         if (updating)
441             Buffered_class = (PyObject *)&PyBufferedRandom_Type;
442         else if (creating || writing || appending)
443             Buffered_class = (PyObject *)&PyBufferedWriter_Type;
444         else if (reading)
445             Buffered_class = (PyObject *)&PyBufferedReader_Type;
446         else {
447             PyErr_Format(PyExc_ValueError,
448                          "unknown mode: '%s'", mode);
449             goto error;
450         }
451 
452         buffer = PyObject_CallFunction(Buffered_class, "Oi", raw, buffering);
453     }
454     if (buffer == NULL)
455         goto error;
456     result = buffer;
457     Py_DECREF(raw);
458 
459 
460     /* if binary, returns the buffered file */
461     if (binary) {
462         Py_DECREF(modeobj);
463         return result;
464     }
465 
466     /* wraps into a TextIOWrapper */
467     wrapper = PyObject_CallFunction((PyObject *)&PyTextIOWrapper_Type,
468                                     "Osssi",
469                                     buffer,
470                                     encoding, errors, newline,
471                                     line_buffering);
472     if (wrapper == NULL)
473         goto error;
474     result = wrapper;
475     Py_DECREF(buffer);
476 
477     if (_PyObject_SetAttrId(wrapper, &PyId_mode, modeobj) < 0)
478         goto error;
479     Py_DECREF(modeobj);
480     return result;
481 
482   error:
483     if (result != NULL) {
484         PyObject *exc, *val, *tb, *close_result;
485         PyErr_Fetch(&exc, &val, &tb);
486         close_result = _PyObject_CallMethodId(result, &PyId_close, NULL);
487         _PyErr_ChainExceptions(exc, val, tb);
488         Py_XDECREF(close_result);
489         Py_DECREF(result);
490     }
491     Py_XDECREF(path_or_fd);
492     Py_XDECREF(modeobj);
493     return NULL;
494 }
495 
496 /*
497  * Private helpers for the io module.
498  */
499 
500 Py_off_t
PyNumber_AsOff_t(PyObject * item,PyObject * err)501 PyNumber_AsOff_t(PyObject *item, PyObject *err)
502 {
503     Py_off_t result;
504     PyObject *runerr;
505     PyObject *value = PyNumber_Index(item);
506     if (value == NULL)
507         return -1;
508 
509     /* We're done if PyLong_AsSsize_t() returns without error. */
510     result = PyLong_AsOff_t(value);
511     if (result != -1 || !(runerr = PyErr_Occurred()))
512         goto finish;
513 
514     /* Error handling code -- only manage OverflowError differently */
515     if (!PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError))
516         goto finish;
517 
518     PyErr_Clear();
519     /* If no error-handling desired then the default clipping
520        is sufficient.
521      */
522     if (!err) {
523         assert(PyLong_Check(value));
524         /* Whether or not it is less than or equal to
525            zero is determined by the sign of ob_size
526         */
527         if (_PyLong_Sign(value) < 0)
528             result = PY_OFF_T_MIN;
529         else
530             result = PY_OFF_T_MAX;
531     }
532     else {
533         /* Otherwise replace the error with caller's error object. */
534         PyErr_Format(err,
535                      "cannot fit '%.200s' into an offset-sized integer",
536                      item->ob_type->tp_name);
537     }
538 
539  finish:
540     Py_DECREF(value);
541     return result;
542 }
543 
544 
545 /* Basically the "n" format code with the ability to turn None into -1. */
546 int
_PyIO_ConvertSsize_t(PyObject * obj,void * result)547 _PyIO_ConvertSsize_t(PyObject *obj, void *result) {
548     Py_ssize_t limit;
549     if (obj == Py_None) {
550         limit = -1;
551     }
552     else if (PyNumber_Check(obj)) {
553         limit = PyNumber_AsSsize_t(obj, PyExc_OverflowError);
554         if (limit == -1 && PyErr_Occurred())
555             return 0;
556     }
557     else {
558         PyErr_Format(PyExc_TypeError,
559                      "integer argument expected, got '%.200s'",
560                      Py_TYPE(obj)->tp_name);
561         return 0;
562     }
563     *((Py_ssize_t *)result) = limit;
564     return 1;
565 }
566 
567 
568 _PyIO_State *
_PyIO_get_module_state(void)569 _PyIO_get_module_state(void)
570 {
571     PyObject *mod = PyState_FindModule(&_PyIO_Module);
572     _PyIO_State *state;
573     if (mod == NULL || (state = IO_MOD_STATE(mod)) == NULL) {
574         PyErr_SetString(PyExc_RuntimeError,
575                         "could not find io module state "
576                         "(interpreter shutdown?)");
577         return NULL;
578     }
579     return state;
580 }
581 
582 PyObject *
_PyIO_get_locale_module(_PyIO_State * state)583 _PyIO_get_locale_module(_PyIO_State *state)
584 {
585     PyObject *mod;
586     if (state->locale_module != NULL) {
587         assert(PyWeakref_CheckRef(state->locale_module));
588         mod = PyWeakref_GET_OBJECT(state->locale_module);
589         if (mod != Py_None) {
590             Py_INCREF(mod);
591             return mod;
592         }
593         Py_CLEAR(state->locale_module);
594     }
595     mod = PyImport_ImportModule("_bootlocale");
596     if (mod == NULL)
597         return NULL;
598     state->locale_module = PyWeakref_NewRef(mod, NULL);
599     if (state->locale_module == NULL) {
600         Py_DECREF(mod);
601         return NULL;
602     }
603     return mod;
604 }
605 
606 
607 static int
iomodule_traverse(PyObject * mod,visitproc visit,void * arg)608 iomodule_traverse(PyObject *mod, visitproc visit, void *arg) {
609     _PyIO_State *state = IO_MOD_STATE(mod);
610     if (!state->initialized)
611         return 0;
612     if (state->locale_module != NULL) {
613         Py_VISIT(state->locale_module);
614     }
615     Py_VISIT(state->unsupported_operation);
616     return 0;
617 }
618 
619 
620 static int
iomodule_clear(PyObject * mod)621 iomodule_clear(PyObject *mod) {
622     _PyIO_State *state = IO_MOD_STATE(mod);
623     if (!state->initialized)
624         return 0;
625     if (state->locale_module != NULL)
626         Py_CLEAR(state->locale_module);
627     Py_CLEAR(state->unsupported_operation);
628     return 0;
629 }
630 
631 static void
iomodule_free(PyObject * mod)632 iomodule_free(PyObject *mod) {
633     iomodule_clear(mod);
634 }
635 
636 
637 /*
638  * Module definition
639  */
640 
641 #include "clinic/_iomodule.c.h"
642 
643 static PyMethodDef module_methods[] = {
644     _IO_OPEN_METHODDEF
645     {NULL, NULL}
646 };
647 
648 struct PyModuleDef _PyIO_Module = {
649     PyModuleDef_HEAD_INIT,
650     "io",
651     module_doc,
652     sizeof(_PyIO_State),
653     module_methods,
654     NULL,
655     iomodule_traverse,
656     iomodule_clear,
657     (freefunc)iomodule_free,
658 };
659 
660 PyMODINIT_FUNC
PyInit__io(void)661 PyInit__io(void)
662 {
663     PyObject *m = PyModule_Create(&_PyIO_Module);
664     _PyIO_State *state = NULL;
665     if (m == NULL)
666         return NULL;
667     state = IO_MOD_STATE(m);
668     state->initialized = 0;
669 
670 #define ADD_TYPE(type, name) \
671     if (PyType_Ready(type) < 0) \
672         goto fail; \
673     Py_INCREF(type); \
674     if (PyModule_AddObject(m, name, (PyObject *)type) < 0) {  \
675         Py_DECREF(type); \
676         goto fail; \
677     }
678 
679     /* DEFAULT_BUFFER_SIZE */
680     if (PyModule_AddIntMacro(m, DEFAULT_BUFFER_SIZE) < 0)
681         goto fail;
682 
683     /* UnsupportedOperation inherits from ValueError and IOError */
684     state->unsupported_operation = PyObject_CallFunction(
685         (PyObject *)&PyType_Type, "s(OO){}",
686         "UnsupportedOperation", PyExc_OSError, PyExc_ValueError);
687     if (state->unsupported_operation == NULL)
688         goto fail;
689     Py_INCREF(state->unsupported_operation);
690     if (PyModule_AddObject(m, "UnsupportedOperation",
691                            state->unsupported_operation) < 0)
692         goto fail;
693 
694     /* BlockingIOError, for compatibility */
695     Py_INCREF(PyExc_BlockingIOError);
696     if (PyModule_AddObject(m, "BlockingIOError",
697                            (PyObject *) PyExc_BlockingIOError) < 0)
698         goto fail;
699 
700     /* Concrete base types of the IO ABCs.
701        (the ABCs themselves are declared through inheritance in io.py)
702     */
703     ADD_TYPE(&PyIOBase_Type, "_IOBase");
704     ADD_TYPE(&PyRawIOBase_Type, "_RawIOBase");
705     ADD_TYPE(&PyBufferedIOBase_Type, "_BufferedIOBase");
706     ADD_TYPE(&PyTextIOBase_Type, "_TextIOBase");
707 
708     /* Implementation of concrete IO objects. */
709     /* FileIO */
710     PyFileIO_Type.tp_base = &PyRawIOBase_Type;
711     ADD_TYPE(&PyFileIO_Type, "FileIO");
712 
713     /* BytesIO */
714     PyBytesIO_Type.tp_base = &PyBufferedIOBase_Type;
715     ADD_TYPE(&PyBytesIO_Type, "BytesIO");
716     if (PyType_Ready(&_PyBytesIOBuffer_Type) < 0)
717         goto fail;
718 
719     /* StringIO */
720     PyStringIO_Type.tp_base = &PyTextIOBase_Type;
721     ADD_TYPE(&PyStringIO_Type, "StringIO");
722 
723 #ifdef MS_WINDOWS
724     /* WindowsConsoleIO */
725     PyWindowsConsoleIO_Type.tp_base = &PyRawIOBase_Type;
726     ADD_TYPE(&PyWindowsConsoleIO_Type, "_WindowsConsoleIO");
727 #endif
728 
729     /* BufferedReader */
730     PyBufferedReader_Type.tp_base = &PyBufferedIOBase_Type;
731     ADD_TYPE(&PyBufferedReader_Type, "BufferedReader");
732 
733     /* BufferedWriter */
734     PyBufferedWriter_Type.tp_base = &PyBufferedIOBase_Type;
735     ADD_TYPE(&PyBufferedWriter_Type, "BufferedWriter");
736 
737     /* BufferedRWPair */
738     PyBufferedRWPair_Type.tp_base = &PyBufferedIOBase_Type;
739     ADD_TYPE(&PyBufferedRWPair_Type, "BufferedRWPair");
740 
741     /* BufferedRandom */
742     PyBufferedRandom_Type.tp_base = &PyBufferedIOBase_Type;
743     ADD_TYPE(&PyBufferedRandom_Type, "BufferedRandom");
744 
745     /* TextIOWrapper */
746     PyTextIOWrapper_Type.tp_base = &PyTextIOBase_Type;
747     ADD_TYPE(&PyTextIOWrapper_Type, "TextIOWrapper");
748 
749     /* IncrementalNewlineDecoder */
750     ADD_TYPE(&PyIncrementalNewlineDecoder_Type, "IncrementalNewlineDecoder");
751 
752     /* Interned strings */
753 #define ADD_INTERNED(name) \
754     if (!_PyIO_str_ ## name && \
755         !(_PyIO_str_ ## name = PyUnicode_InternFromString(# name))) \
756         goto fail;
757 
758     ADD_INTERNED(close)
759     ADD_INTERNED(closed)
760     ADD_INTERNED(decode)
761     ADD_INTERNED(encode)
762     ADD_INTERNED(fileno)
763     ADD_INTERNED(flush)
764     ADD_INTERNED(getstate)
765     ADD_INTERNED(isatty)
766     ADD_INTERNED(newlines)
767     ADD_INTERNED(read)
768     ADD_INTERNED(read1)
769     ADD_INTERNED(readable)
770     ADD_INTERNED(readall)
771     ADD_INTERNED(readinto)
772     ADD_INTERNED(readline)
773     ADD_INTERNED(reset)
774     ADD_INTERNED(seek)
775     ADD_INTERNED(seekable)
776     ADD_INTERNED(setstate)
777     ADD_INTERNED(tell)
778     ADD_INTERNED(truncate)
779     ADD_INTERNED(write)
780     ADD_INTERNED(writable)
781 
782     if (!_PyIO_str_nl &&
783         !(_PyIO_str_nl = PyUnicode_InternFromString("\n")))
784         goto fail;
785 
786     if (!_PyIO_empty_str &&
787         !(_PyIO_empty_str = PyUnicode_FromStringAndSize(NULL, 0)))
788         goto fail;
789     if (!_PyIO_empty_bytes &&
790         !(_PyIO_empty_bytes = PyBytes_FromStringAndSize(NULL, 0)))
791         goto fail;
792     if (!_PyIO_zero &&
793         !(_PyIO_zero = PyLong_FromLong(0L)))
794         goto fail;
795 
796     state->initialized = 1;
797 
798     return m;
799 
800   fail:
801     Py_XDECREF(state->unsupported_operation);
802     Py_DECREF(m);
803     return NULL;
804 }
805