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 <windows.h>
25 #endif
26 
27 /* Various interned strings */
28 
29 PyObject *_PyIO_str_close = NULL;
30 PyObject *_PyIO_str_closed = NULL;
31 PyObject *_PyIO_str_decode = NULL;
32 PyObject *_PyIO_str_encode = NULL;
33 PyObject *_PyIO_str_fileno = NULL;
34 PyObject *_PyIO_str_flush = NULL;
35 PyObject *_PyIO_str_getstate = NULL;
36 PyObject *_PyIO_str_isatty = NULL;
37 PyObject *_PyIO_str_newlines = NULL;
38 PyObject *_PyIO_str_nl = NULL;
39 PyObject *_PyIO_str_peek = NULL;
40 PyObject *_PyIO_str_read = NULL;
41 PyObject *_PyIO_str_read1 = NULL;
42 PyObject *_PyIO_str_readable = NULL;
43 PyObject *_PyIO_str_readall = NULL;
44 PyObject *_PyIO_str_readinto = NULL;
45 PyObject *_PyIO_str_readline = NULL;
46 PyObject *_PyIO_str_reset = NULL;
47 PyObject *_PyIO_str_seek = NULL;
48 PyObject *_PyIO_str_seekable = NULL;
49 PyObject *_PyIO_str_setstate = NULL;
50 PyObject *_PyIO_str_tell = NULL;
51 PyObject *_PyIO_str_truncate = NULL;
52 PyObject *_PyIO_str_writable = NULL;
53 PyObject *_PyIO_str_write = NULL;
54 
55 PyObject *_PyIO_empty_str = NULL;
56 PyObject *_PyIO_empty_bytes = NULL;
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 OSError 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: bool(accept={int}) = True
109     opener: object = None
110 
111 Open file and return a stream.  Raise OSError 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=03da2940c8a65871]*/
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 _PyIO_State *
_PyIO_get_module_state(void)546 _PyIO_get_module_state(void)
547 {
548     PyObject *mod = PyState_FindModule(&_PyIO_Module);
549     _PyIO_State *state;
550     if (mod == NULL || (state = IO_MOD_STATE(mod)) == NULL) {
551         PyErr_SetString(PyExc_RuntimeError,
552                         "could not find io module state "
553                         "(interpreter shutdown?)");
554         return NULL;
555     }
556     return state;
557 }
558 
559 PyObject *
_PyIO_get_locale_module(_PyIO_State * state)560 _PyIO_get_locale_module(_PyIO_State *state)
561 {
562     PyObject *mod;
563     if (state->locale_module != NULL) {
564         assert(PyWeakref_CheckRef(state->locale_module));
565         mod = PyWeakref_GET_OBJECT(state->locale_module);
566         if (mod != Py_None) {
567             Py_INCREF(mod);
568             return mod;
569         }
570         Py_CLEAR(state->locale_module);
571     }
572     mod = PyImport_ImportModule("_bootlocale");
573     if (mod == NULL)
574         return NULL;
575     state->locale_module = PyWeakref_NewRef(mod, NULL);
576     if (state->locale_module == NULL) {
577         Py_DECREF(mod);
578         return NULL;
579     }
580     return mod;
581 }
582 
583 
584 static int
iomodule_traverse(PyObject * mod,visitproc visit,void * arg)585 iomodule_traverse(PyObject *mod, visitproc visit, void *arg) {
586     _PyIO_State *state = IO_MOD_STATE(mod);
587     if (!state->initialized)
588         return 0;
589     if (state->locale_module != NULL) {
590         Py_VISIT(state->locale_module);
591     }
592     Py_VISIT(state->unsupported_operation);
593     return 0;
594 }
595 
596 
597 static int
iomodule_clear(PyObject * mod)598 iomodule_clear(PyObject *mod) {
599     _PyIO_State *state = IO_MOD_STATE(mod);
600     if (!state->initialized)
601         return 0;
602     if (state->locale_module != NULL)
603         Py_CLEAR(state->locale_module);
604     Py_CLEAR(state->unsupported_operation);
605     return 0;
606 }
607 
608 static void
iomodule_free(PyObject * mod)609 iomodule_free(PyObject *mod) {
610     iomodule_clear(mod);
611 }
612 
613 
614 /*
615  * Module definition
616  */
617 
618 #include "clinic/_iomodule.c.h"
619 
620 static PyMethodDef module_methods[] = {
621     _IO_OPEN_METHODDEF
622     {NULL, NULL}
623 };
624 
625 struct PyModuleDef _PyIO_Module = {
626     PyModuleDef_HEAD_INIT,
627     "io",
628     module_doc,
629     sizeof(_PyIO_State),
630     module_methods,
631     NULL,
632     iomodule_traverse,
633     iomodule_clear,
634     (freefunc)iomodule_free,
635 };
636 
637 PyMODINIT_FUNC
PyInit__io(void)638 PyInit__io(void)
639 {
640     PyObject *m = PyModule_Create(&_PyIO_Module);
641     _PyIO_State *state = NULL;
642     if (m == NULL)
643         return NULL;
644     state = IO_MOD_STATE(m);
645     state->initialized = 0;
646 
647 #define ADD_TYPE(type, name) \
648     if (PyType_Ready(type) < 0) \
649         goto fail; \
650     Py_INCREF(type); \
651     if (PyModule_AddObject(m, name, (PyObject *)type) < 0) {  \
652         Py_DECREF(type); \
653         goto fail; \
654     }
655 
656     /* DEFAULT_BUFFER_SIZE */
657     if (PyModule_AddIntMacro(m, DEFAULT_BUFFER_SIZE) < 0)
658         goto fail;
659 
660     /* UnsupportedOperation inherits from ValueError and OSError */
661     state->unsupported_operation = PyObject_CallFunction(
662         (PyObject *)&PyType_Type, "s(OO){}",
663         "UnsupportedOperation", PyExc_OSError, PyExc_ValueError);
664     if (state->unsupported_operation == NULL)
665         goto fail;
666     Py_INCREF(state->unsupported_operation);
667     if (PyModule_AddObject(m, "UnsupportedOperation",
668                            state->unsupported_operation) < 0)
669         goto fail;
670 
671     /* BlockingIOError, for compatibility */
672     Py_INCREF(PyExc_BlockingIOError);
673     if (PyModule_AddObject(m, "BlockingIOError",
674                            (PyObject *) PyExc_BlockingIOError) < 0)
675         goto fail;
676 
677     /* Concrete base types of the IO ABCs.
678        (the ABCs themselves are declared through inheritance in io.py)
679     */
680     ADD_TYPE(&PyIOBase_Type, "_IOBase");
681     ADD_TYPE(&PyRawIOBase_Type, "_RawIOBase");
682     ADD_TYPE(&PyBufferedIOBase_Type, "_BufferedIOBase");
683     ADD_TYPE(&PyTextIOBase_Type, "_TextIOBase");
684 
685     /* Implementation of concrete IO objects. */
686     /* FileIO */
687     PyFileIO_Type.tp_base = &PyRawIOBase_Type;
688     ADD_TYPE(&PyFileIO_Type, "FileIO");
689 
690     /* BytesIO */
691     PyBytesIO_Type.tp_base = &PyBufferedIOBase_Type;
692     ADD_TYPE(&PyBytesIO_Type, "BytesIO");
693     if (PyType_Ready(&_PyBytesIOBuffer_Type) < 0)
694         goto fail;
695 
696     /* StringIO */
697     PyStringIO_Type.tp_base = &PyTextIOBase_Type;
698     ADD_TYPE(&PyStringIO_Type, "StringIO");
699 
700 #ifdef MS_WINDOWS
701     /* WindowsConsoleIO */
702     PyWindowsConsoleIO_Type.tp_base = &PyRawIOBase_Type;
703     ADD_TYPE(&PyWindowsConsoleIO_Type, "_WindowsConsoleIO");
704 #endif
705 
706     /* BufferedReader */
707     PyBufferedReader_Type.tp_base = &PyBufferedIOBase_Type;
708     ADD_TYPE(&PyBufferedReader_Type, "BufferedReader");
709 
710     /* BufferedWriter */
711     PyBufferedWriter_Type.tp_base = &PyBufferedIOBase_Type;
712     ADD_TYPE(&PyBufferedWriter_Type, "BufferedWriter");
713 
714     /* BufferedRWPair */
715     PyBufferedRWPair_Type.tp_base = &PyBufferedIOBase_Type;
716     ADD_TYPE(&PyBufferedRWPair_Type, "BufferedRWPair");
717 
718     /* BufferedRandom */
719     PyBufferedRandom_Type.tp_base = &PyBufferedIOBase_Type;
720     ADD_TYPE(&PyBufferedRandom_Type, "BufferedRandom");
721 
722     /* TextIOWrapper */
723     PyTextIOWrapper_Type.tp_base = &PyTextIOBase_Type;
724     ADD_TYPE(&PyTextIOWrapper_Type, "TextIOWrapper");
725 
726     /* IncrementalNewlineDecoder */
727     ADD_TYPE(&PyIncrementalNewlineDecoder_Type, "IncrementalNewlineDecoder");
728 
729     /* Interned strings */
730 #define ADD_INTERNED(name) \
731     if (!_PyIO_str_ ## name && \
732         !(_PyIO_str_ ## name = PyUnicode_InternFromString(# name))) \
733         goto fail;
734 
735     ADD_INTERNED(close)
736     ADD_INTERNED(closed)
737     ADD_INTERNED(decode)
738     ADD_INTERNED(encode)
739     ADD_INTERNED(fileno)
740     ADD_INTERNED(flush)
741     ADD_INTERNED(getstate)
742     ADD_INTERNED(isatty)
743     ADD_INTERNED(newlines)
744     ADD_INTERNED(peek)
745     ADD_INTERNED(read)
746     ADD_INTERNED(read1)
747     ADD_INTERNED(readable)
748     ADD_INTERNED(readall)
749     ADD_INTERNED(readinto)
750     ADD_INTERNED(readline)
751     ADD_INTERNED(reset)
752     ADD_INTERNED(seek)
753     ADD_INTERNED(seekable)
754     ADD_INTERNED(setstate)
755     ADD_INTERNED(tell)
756     ADD_INTERNED(truncate)
757     ADD_INTERNED(write)
758     ADD_INTERNED(writable)
759 
760     if (!_PyIO_str_nl &&
761         !(_PyIO_str_nl = PyUnicode_InternFromString("\n")))
762         goto fail;
763 
764     if (!_PyIO_empty_str &&
765         !(_PyIO_empty_str = PyUnicode_FromStringAndSize(NULL, 0)))
766         goto fail;
767     if (!_PyIO_empty_bytes &&
768         !(_PyIO_empty_bytes = PyBytes_FromStringAndSize(NULL, 0)))
769         goto fail;
770 
771     state->initialized = 1;
772 
773     return m;
774 
775   fail:
776     Py_XDECREF(state->unsupported_operation);
777     Py_DECREF(m);
778     return NULL;
779 }
780