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