Coverage Report

Created: 2026-12-01 06:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Modules/_io/_iomodule.c
Line
Count
Source
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
#include "Python.h"
11
#include "pycore_abstract.h"      // _PyNumber_Index()
12
#include "pycore_interp.h"        // _PyInterpreterState_GetConfig()
13
#include "pycore_long.h"          // _PyLong_IsNegative()
14
#include "pycore_pyerrors.h"      // _PyErr_ChainExceptions1()
15
#include "pycore_pystate.h"       // _PyInterpreterState_GET()
16
17
#include "_iomodule.h"
18
19
#ifdef HAVE_SYS_TYPES_H
20
#include <sys/types.h>
21
#endif /* HAVE_SYS_TYPES_H */
22
23
#ifdef HAVE_SYS_STAT_H
24
#include <sys/stat.h>
25
#endif /* HAVE_SYS_STAT_H */
26
27
#ifdef MS_WINDOWS
28
#include <windows.h>
29
#endif
30
31
PyDoc_STRVAR(module_doc,
32
"The io module provides the Python interfaces to stream handling. The\n"
33
"builtin open function is defined in this module.\n"
34
"\n"
35
"At the top of the I/O hierarchy is the abstract base class IOBase. It\n"
36
"defines the basic interface to a stream. Note, however, that there is no\n"
37
"separation between reading and writing to streams; implementations are\n"
38
"allowed to raise an OSError if they do not support a given operation.\n"
39
"\n"
40
"Extending IOBase is RawIOBase which deals simply with the reading and\n"
41
"writing of raw bytes to a stream. FileIO subclasses RawIOBase to provide\n"
42
"an interface to OS files.\n"
43
"\n"
44
"BufferedIOBase deals with buffering on a raw byte stream (RawIOBase). Its\n"
45
"subclasses, BufferedWriter, BufferedReader, and BufferedRWPair buffer\n"
46
"streams that are readable, writable, and both respectively.\n"
47
"BufferedRandom provides a buffered interface to random access\n"
48
"streams. BytesIO is a simple stream of in-memory bytes.\n"
49
"\n"
50
"Another IOBase subclass, TextIOBase, deals with the encoding and decoding\n"
51
"of streams into text. TextIOWrapper, which extends it, is a buffered text\n"
52
"interface to a buffered raw stream (`BufferedIOBase`). Finally, StringIO\n"
53
"is an in-memory stream for text.\n"
54
"\n"
55
"Argument names are not part of the specification, and only the arguments\n"
56
"of open() are intended to be used as keyword arguments.\n"
57
"\n"
58
"data:\n"
59
"\n"
60
"DEFAULT_BUFFER_SIZE\n"
61
"\n"
62
"   An int containing the default buffer size used by the module's buffered\n"
63
"   I/O classes.\n"
64
    );
65
66
67
/*
68
 * The main open() function
69
 */
70
/*[clinic input]
71
module _io
72
73
_io.open
74
    file: object
75
    mode: str = "r"
76
    buffering: int = -1
77
    encoding: str(accept={str, NoneType}) = None
78
    errors: str(accept={str, NoneType}) = None
79
    newline: str(accept={str, NoneType}) = None
80
    closefd: bool = True
81
    opener: object = None
82
83
Open file and return a stream.  Raise OSError upon failure.
84
85
file is either a text or byte string giving the name (and the path
86
if the file isn't in the current working directory) of the file to
87
be opened or an integer file descriptor of the file to be
88
wrapped.  (If a file descriptor is given, it is closed when the
89
returned I/O object is closed, unless closefd is set to False.)
90
91
mode is an optional string that specifies the mode in which the file
92
is opened.  It defaults to 'r' which means open for reading in text
93
mode.  Other common values are 'w' for writing (truncating the file if
94
it already exists), 'x' for creating and writing to a new file, and
95
'a' for appending (which on some Unix systems, means that all writes
96
append to the end of the file regardless of the current seek position).
97
The available modes are:
98
99
========= ==========================================================
100
Character Meaning
101
--------- ----------------------------------------------------------
102
'r'       open for reading (default)
103
'w'       open for writing, truncating the file first
104
'x'       create a new file and open it for writing
105
'a'       open for writing, appending to the end of the file if it
106
          exists
107
'b'       binary mode
108
't'       text mode (default)
109
'+'       open a disk file for updating (reading and writing)
110
========= ==========================================================
111
112
The default mode is 'rt' (open for reading text).  For binary random
113
access, the mode 'w+b' opens and truncates the file to 0 bytes, while
114
'r+b' opens the file without truncation.  The 'x' mode implies 'w' and
115
raises an `FileExistsError` if the file already exists.
116
117
Python distinguishes between files opened in binary and text modes,
118
even when the underlying operating system doesn't.  Files opened in
119
binary mode (appending 'b' to the mode argument) return contents as
120
bytes objects without any decoding.  In text mode (the default, or when
121
't' is appended to the mode argument), the contents of the file are
122
decoded using the encoding described below and returned as strings.
123
124
buffering is an optional integer used to set the buffering policy.
125
Pass 0 to switch buffering off (only allowed in binary mode), 1 to
126
select line buffering (only usable in text mode), and an integer > 1 to
127
indicate the size of a fixed-size chunk buffer.   When no buffering
128
argument is given, the default buffering policy works as follows:
129
130
* Binary files are buffered in fixed-size chunks; the size of the buffer
131
  is max(min(blocksize, 8 MiB), DEFAULT_BUFFER_SIZE) when the device
132
  block size is available.
133
  On most systems, the buffer will typically be 128 kilobytes long.
134
135
* "Interactive" text files (files for which isatty() returns True)
136
  use line buffering.  Other text files use the policy described above
137
  for binary files.
138
139
encoding is the name of the encoding used to decode or encode the file.
140
This should only be used in text mode.  The default encoding is UTF-8;
141
if UTF-8 Mode is disabled, the encoding returned by
142
locale.getencoding() is used instead.  See the codecs module for the
143
list of supported encodings.
144
145
errors is an optional string that specifies how encoding errors are to
146
be handled---this argument should not be used in binary mode.  Pass
147
'strict' to raise a ValueError exception if there is an encoding error
148
(the default of None has the same effect), or pass 'ignore' to ignore
149
errors.  (Note that ignoring encoding errors can lead to data loss.)
150
See the documentation for codecs.register or run 'help(codecs.Codec)'
151
for a list of the permitted encoding error strings.
152
153
newline controls how universal newlines works (it only applies to text
154
mode).  It can be None, '', '\n', '\r', and '\r\n'.  It works as
155
follows:
156
157
* On input, if newline is None, universal newlines mode is enabled.
158
  Lines in the input can end in '\n', '\r', or '\r\n', and these are
159
  translated into '\n' before being returned to the caller.  If it is
160
  '', universal newline mode is enabled, but line endings are returned
161
  to the caller untranslated.  If it has any of the other legal values,
162
  input lines are only terminated by the given string, and the line
163
  ending is returned to the caller untranslated.
164
165
* On output, if newline is None, any '\n' characters written are
166
  translated to the system default line separator, os.linesep.  If
167
  newline is '' or '\n', no translation takes place.  If newline is any
168
  of the other legal values, any '\n' characters written are translated
169
  to the given string.
170
171
If closefd is False, the underlying file descriptor will be kept open
172
when the file is closed.  This does not work when a file name is given
173
and must be True in that case.
174
175
A custom opener can be used by passing a callable as *opener*.  The
176
underlying file descriptor for the file object is then obtained by
177
calling *opener* with (*file*, *flags*).  *opener* must return an open
178
file descriptor (passing os.open as *opener* results in functionality
179
similar to passing None).
180
181
open() returns a file object whose type depends on the mode, and
182
through which the standard file operations such as reading and writing
183
are performed.  When open() is used to open a file in a text mode ('w',
184
'r', 'wt', 'rt', etc.), it returns a TextIOWrapper.  When used to open
185
a file in a binary mode, the returned class varies: in read binary
186
mode, it returns a BufferedReader; in write binary and append binary
187
modes, it returns a BufferedWriter, and in read/write mode, it returns
188
a BufferedRandom.
189
190
It is also possible to use a string or bytearray as a file for both
191
reading and writing.  For strings StringIO can be used like a file
192
opened in a text mode, and for bytes a BytesIO can be used like a file
193
opened in a binary mode.
194
[clinic start generated code]*/
195
196
static PyObject *
197
_io_open_impl(PyObject *module, PyObject *file, const char *mode,
198
              int buffering, const char *encoding, const char *errors,
199
              const char *newline, int closefd, PyObject *opener)
200
/*[clinic end generated code: output=aefafc4ce2b46dc0 input=5a005681afa02242]*/
201
22.3k
{
202
22.3k
    size_t i;
203
204
22.3k
    int creating = 0, reading = 0, writing = 0, appending = 0, updating = 0;
205
22.3k
    int text = 0, binary = 0;
206
207
22.3k
    char rawmode[6], *m;
208
22.3k
    int line_buffering, is_number, isatty = 0;
209
210
22.3k
    PyObject *raw, *modeobj = NULL, *buffer, *wrapper, *result = NULL, *path_or_fd = NULL;
211
212
22.3k
    is_number = PyNumber_Check(file);
213
214
22.3k
    if (is_number) {
215
247
        path_or_fd = Py_NewRef(file);
216
22.0k
    } else {
217
22.0k
        path_or_fd = PyOS_FSPath(file);
218
22.0k
        if (path_or_fd == NULL) {
219
0
            return NULL;
220
0
        }
221
22.0k
    }
222
223
22.3k
    if (!is_number &&
224
22.3k
        !PyUnicode_Check(path_or_fd) &&
225
0
        !PyBytes_Check(path_or_fd)) {
226
0
        PyErr_Format(PyExc_TypeError, "invalid file: %R", file);
227
0
        goto error;
228
0
    }
229
230
    /* Decode mode */
231
66.9k
    for (i = 0; i < strlen(mode); i++) {
232
44.6k
        char c = mode[i];
233
234
44.6k
        switch (c) {
235
0
        case 'x':
236
0
            creating = 1;
237
0
            break;
238
2.14k
        case 'r':
239
2.14k
            reading = 1;
240
2.14k
            break;
241
20.1k
        case 'w':
242
20.1k
            writing = 1;
243
20.1k
            break;
244
0
        case 'a':
245
0
            appending = 1;
246
0
            break;
247
0
        case '+':
248
0
            updating = 1;
249
0
            break;
250
0
        case 't':
251
0
            text = 1;
252
0
            break;
253
22.3k
        case 'b':
254
22.3k
            binary = 1;
255
22.3k
            break;
256
0
        default:
257
0
            goto invalid_mode;
258
44.6k
        }
259
260
        /* c must not be duplicated */
261
44.6k
        if (strchr(mode+i+1, c)) {
262
0
          invalid_mode:
263
0
            PyErr_Format(PyExc_ValueError, "invalid mode: '%s'", mode);
264
0
            goto error;
265
0
        }
266
267
44.6k
    }
268
269
22.3k
    m = rawmode;
270
22.3k
    if (creating)  *(m++) = 'x';
271
22.3k
    if (reading)   *(m++) = 'r';
272
22.3k
    if (writing)   *(m++) = 'w';
273
22.3k
    if (appending) *(m++) = 'a';
274
22.3k
    if (updating)  *(m++) = '+';
275
22.3k
    *m = '\0';
276
277
    /* Parameters validation */
278
22.3k
    if (text && binary) {
279
0
        PyErr_SetString(PyExc_ValueError,
280
0
                        "can't have text and binary mode at once");
281
0
        goto error;
282
0
    }
283
284
22.3k
    if (creating + reading + writing + appending > 1) {
285
0
        PyErr_SetString(PyExc_ValueError,
286
0
                        "must have exactly one of create/read/write/append mode");
287
0
        goto error;
288
0
    }
289
290
22.3k
    if (binary && encoding != NULL) {
291
0
        PyErr_SetString(PyExc_ValueError,
292
0
                        "binary mode doesn't take an encoding argument");
293
0
        goto error;
294
0
    }
295
296
22.3k
    if (binary && errors != NULL) {
297
0
        PyErr_SetString(PyExc_ValueError,
298
0
                        "binary mode doesn't take an errors argument");
299
0
        goto error;
300
0
    }
301
302
22.3k
    if (binary && newline != NULL) {
303
0
        PyErr_SetString(PyExc_ValueError,
304
0
                        "binary mode doesn't take a newline argument");
305
0
        goto error;
306
0
    }
307
308
22.3k
    if (binary && buffering == 1) {
309
0
        if (PyErr_WarnEx(PyExc_RuntimeWarning,
310
0
                         "line buffering (buffering=1) isn't supported in "
311
0
                         "binary mode, the default buffer size will be used",
312
0
                         1) < 0) {
313
0
           goto error;
314
0
        }
315
0
    }
316
317
    /* Create the Raw file stream */
318
22.3k
    _PyIO_State *state = get_io_state(module);
319
22.3k
    {
320
22.3k
        PyObject *RawIO_class = (PyObject *)state->PyFileIO_Type;
321
#ifdef HAVE_WINDOWS_CONSOLE_IO
322
        const PyConfig *config = _Py_GetConfig();
323
        if (!config->legacy_windows_stdio && _PyIO_get_console_type(path_or_fd) != '\0') {
324
            RawIO_class = (PyObject *)state->PyWindowsConsoleIO_Type;
325
            encoding = "utf-8";
326
        }
327
#endif
328
22.3k
        raw = PyObject_CallFunction(RawIO_class, "OsOO",
329
22.3k
                                    path_or_fd, rawmode,
330
22.3k
                                    closefd ? Py_True : Py_False,
331
22.3k
                                    opener);
332
22.3k
    }
333
334
22.3k
    if (raw == NULL)
335
11
        goto error;
336
22.3k
    result = raw;
337
338
22.3k
    Py_SETREF(path_or_fd, NULL);
339
340
22.3k
    modeobj = PyUnicode_FromString(mode);
341
22.3k
    if (modeobj == NULL)
342
0
        goto error;
343
344
    /* buffering */
345
22.3k
    if (buffering < 0) {
346
22.3k
        PyObject *res = PyObject_CallMethodNoArgs(raw, &_Py_ID(_isatty_open_only));
347
22.3k
        if (res == NULL)
348
0
            goto error;
349
22.3k
        isatty = PyObject_IsTrue(res);
350
22.3k
        Py_DECREF(res);
351
22.3k
        if (isatty < 0)
352
0
            goto error;
353
22.3k
    }
354
355
22.3k
    if (buffering == 1 || isatty) {
356
0
        buffering = -1;
357
0
        line_buffering = 1;
358
0
    }
359
22.3k
    else
360
22.3k
        line_buffering = 0;
361
362
22.3k
    if (buffering < 0) {
363
22.3k
        PyObject *blksize_obj;
364
22.3k
        blksize_obj = PyObject_GetAttr(raw, &_Py_ID(_blksize));
365
22.3k
        if (blksize_obj == NULL)
366
0
            goto error;
367
22.3k
        buffering = PyLong_AsLong(blksize_obj);
368
22.3k
        Py_DECREF(blksize_obj);
369
22.3k
        if (buffering == -1 && PyErr_Occurred())
370
0
            goto error;
371
22.3k
        buffering = Py_MAX(Py_MIN(buffering, 8192 * 1024), DEFAULT_BUFFER_SIZE);
372
22.3k
    }
373
22.3k
    if (buffering < 0) {
374
0
        PyErr_SetString(PyExc_ValueError,
375
0
                        "invalid buffering size");
376
0
        goto error;
377
0
    }
378
379
    /* if not buffering, returns the raw file object */
380
22.3k
    if (buffering == 0) {
381
0
        if (!binary) {
382
0
            PyErr_SetString(PyExc_ValueError,
383
0
                            "can't have unbuffered text I/O");
384
0
            goto error;
385
0
        }
386
387
0
        Py_DECREF(modeobj);
388
0
        return result;
389
0
    }
390
391
    /* wraps into a buffered file */
392
22.3k
    {
393
22.3k
        PyObject *Buffered_class;
394
395
22.3k
        if (updating) {
396
0
            Buffered_class = (PyObject *)state->PyBufferedRandom_Type;
397
0
        }
398
22.3k
        else if (creating || writing || appending) {
399
20.1k
            Buffered_class = (PyObject *)state->PyBufferedWriter_Type;
400
20.1k
        }
401
2.13k
        else if (reading) {
402
2.13k
            Buffered_class = (PyObject *)state->PyBufferedReader_Type;
403
2.13k
        }
404
0
        else {
405
0
            PyErr_Format(PyExc_ValueError,
406
0
                         "unknown mode: '%s'", mode);
407
0
            goto error;
408
0
        }
409
410
22.3k
        buffer = PyObject_CallFunction(Buffered_class, "Oi", raw, buffering);
411
22.3k
    }
412
22.3k
    if (buffer == NULL)
413
0
        goto error;
414
22.3k
    result = buffer;
415
22.3k
    Py_DECREF(raw);
416
417
418
    /* if binary, returns the buffered file */
419
22.3k
    if (binary) {
420
22.2k
        Py_DECREF(modeobj);
421
22.2k
        return result;
422
22.2k
    }
423
424
    /* wraps into a TextIOWrapper */
425
9
    wrapper = PyObject_CallFunction((PyObject *)state->PyTextIOWrapper_Type,
426
9
                                    "OsssO",
427
9
                                    buffer,
428
9
                                    encoding, errors, newline,
429
9
                                    line_buffering ? Py_True : Py_False);
430
9
    if (wrapper == NULL)
431
0
        goto error;
432
9
    result = wrapper;
433
9
    Py_DECREF(buffer);
434
435
9
    if (PyObject_SetAttr(wrapper, &_Py_ID(mode), modeobj) < 0)
436
0
        goto error;
437
9
    Py_DECREF(modeobj);
438
9
    return result;
439
440
11
  error:
441
11
    if (result != NULL) {
442
0
        PyObject *exc = PyErr_GetRaisedException();
443
0
        PyObject *close_result = PyObject_CallMethodNoArgs(result, &_Py_ID(close));
444
0
        _PyErr_ChainExceptions1(exc);
445
0
        Py_XDECREF(close_result);
446
0
        Py_DECREF(result);
447
0
    }
448
11
    Py_XDECREF(path_or_fd);
449
11
    Py_XDECREF(modeobj);
450
11
    return NULL;
451
9
}
452
453
454
/*[clinic input]
455
_io.text_encoding
456
    encoding: object
457
    stacklevel: int = 2
458
    /
459
460
A helper function to choose the text encoding.
461
462
When encoding is not None, this function returns it.
463
Otherwise, this function returns the default text encoding
464
(i.e. "locale" or "utf-8" depends on UTF-8 mode).
465
466
This function emits an EncodingWarning if encoding is None and
467
sys.flags.warn_default_encoding is true.
468
469
This can be used in APIs with an encoding=None parameter.
470
However, please consider using encoding="utf-8" for new APIs.
471
[clinic start generated code]*/
472
473
static PyObject *
474
_io_text_encoding_impl(PyObject *module, PyObject *encoding, int stacklevel)
475
/*[clinic end generated code: output=91b2cfea6934cc0c input=4999aa8b3d90f3d4]*/
476
26
{
477
26
    if (encoding == NULL || encoding == Py_None) {
478
0
        PyInterpreterState *interp = _PyInterpreterState_GET();
479
0
        if (_PyInterpreterState_GetConfig(interp)->warn_default_encoding) {
480
0
            if (PyErr_WarnEx(PyExc_EncodingWarning,
481
0
                             "'encoding' argument not specified", stacklevel)) {
482
0
                return NULL;
483
0
            }
484
0
        }
485
0
        const PyPreConfig *preconfig = &_PyRuntime.preconfig;
486
0
        if (preconfig->utf8_mode) {
487
0
            _Py_DECLARE_STR(utf_8, "utf-8");
488
0
            encoding = &_Py_STR(utf_8);
489
0
        }
490
0
        else {
491
0
            encoding = &_Py_ID(locale);
492
0
        }
493
0
    }
494
26
    return Py_NewRef(encoding);
495
26
}
496
497
498
/*[clinic input]
499
_io.open_code
500
501
    path : unicode
502
503
Opens the provided file with the intent to import the contents.
504
505
This may perform extra validation beyond open(), but is otherwise
506
interchangeable with calling open(path, 'rb').
507
508
[clinic start generated code]*/
509
510
static PyObject *
511
_io_open_code_impl(PyObject *module, PyObject *path)
512
/*[clinic end generated code: output=2fe4ecbd6f3d6844 input=2803c35aeb63c719]*/
513
2.07k
{
514
2.07k
    return PyFile_OpenCodeObject(path);
515
2.07k
}
516
517
/*
518
 * Private helpers for the io module.
519
 */
520
521
Py_off_t
522
PyNumber_AsOff_t(PyObject *item, PyObject *err)
523
1.45M
{
524
1.45M
    Py_off_t result;
525
1.45M
    PyObject *runerr;
526
1.45M
    PyObject *value = _PyNumber_Index(item);
527
1.45M
    if (value == NULL)
528
0
        return -1;
529
530
    /* We're done if PyLong_AsSsize_t() returns without error. */
531
1.45M
    result = PyLong_AsOff_t(value);
532
1.45M
    if (result != -1 || !(runerr = PyErr_Occurred()))
533
1.45M
        goto finish;
534
535
    /* Error handling code -- only manage OverflowError differently */
536
0
    if (!PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError))
537
0
        goto finish;
538
539
0
    PyErr_Clear();
540
    /* If no error-handling desired then the default clipping
541
       is sufficient.
542
     */
543
0
    if (!err) {
544
0
        assert(PyLong_Check(value));
545
0
        if (_PyLong_IsNegative((PyLongObject *)value))
546
0
            result = PY_OFF_T_MIN;
547
0
        else
548
0
            result = PY_OFF_T_MAX;
549
0
    }
550
0
    else {
551
        /* Otherwise replace the error with caller's error object. */
552
0
        PyErr_Format(err,
553
0
                     "cannot fit '%.200s' into an offset-sized integer",
554
0
                     Py_TYPE(item)->tp_name);
555
0
    }
556
557
1.45M
 finish:
558
1.45M
    Py_DECREF(value);
559
1.45M
    return result;
560
0
}
561
562
static int
563
2.03k
iomodule_traverse(PyObject *mod, visitproc visit, void *arg) {
564
2.03k
    _PyIO_State *state = get_io_state(mod);
565
2.03k
    Py_VISIT(state->unsupported_operation);
566
567
2.03k
    Py_VISIT(state->PyIOBase_Type);
568
2.03k
    Py_VISIT(state->PyIncrementalNewlineDecoder_Type);
569
2.03k
    Py_VISIT(state->PyRawIOBase_Type);
570
2.03k
    Py_VISIT(state->PyBufferedIOBase_Type);
571
2.03k
    Py_VISIT(state->PyBufferedRWPair_Type);
572
2.03k
    Py_VISIT(state->PyBufferedRandom_Type);
573
2.03k
    Py_VISIT(state->PyBufferedReader_Type);
574
2.03k
    Py_VISIT(state->PyBufferedWriter_Type);
575
2.03k
    Py_VISIT(state->PyBytesIOBuffer_Type);
576
2.03k
    Py_VISIT(state->PyBytesIO_Type);
577
2.03k
    Py_VISIT(state->PyFileIO_Type);
578
2.03k
    Py_VISIT(state->PyStringIO_Type);
579
2.03k
    Py_VISIT(state->PyTextIOBase_Type);
580
2.03k
    Py_VISIT(state->PyTextIOWrapper_Type);
581
#ifdef HAVE_WINDOWS_CONSOLE_IO
582
    Py_VISIT(state->PyWindowsConsoleIO_Type);
583
#endif
584
2.03k
    return 0;
585
2.03k
}
586
587
588
static int
589
0
iomodule_clear(PyObject *mod) {
590
0
    _PyIO_State *state = get_io_state(mod);
591
0
    Py_CLEAR(state->unsupported_operation);
592
593
0
    Py_CLEAR(state->PyIOBase_Type);
594
0
    Py_CLEAR(state->PyIncrementalNewlineDecoder_Type);
595
0
    Py_CLEAR(state->PyRawIOBase_Type);
596
0
    Py_CLEAR(state->PyBufferedIOBase_Type);
597
0
    Py_CLEAR(state->PyBufferedRWPair_Type);
598
0
    Py_CLEAR(state->PyBufferedRandom_Type);
599
0
    Py_CLEAR(state->PyBufferedReader_Type);
600
0
    Py_CLEAR(state->PyBufferedWriter_Type);
601
0
    Py_CLEAR(state->PyBytesIOBuffer_Type);
602
0
    Py_CLEAR(state->PyBytesIO_Type);
603
0
    Py_CLEAR(state->PyFileIO_Type);
604
0
    Py_CLEAR(state->PyStringIO_Type);
605
0
    Py_CLEAR(state->PyTextIOBase_Type);
606
0
    Py_CLEAR(state->PyTextIOWrapper_Type);
607
#ifdef HAVE_WINDOWS_CONSOLE_IO
608
    Py_CLEAR(state->PyWindowsConsoleIO_Type);
609
#endif
610
0
    return 0;
611
0
}
612
613
static void
614
iomodule_free(void *mod)
615
0
{
616
0
    (void)iomodule_clear((PyObject *)mod);
617
0
}
618
619
620
/*
621
 * Module definition
622
 */
623
624
#define clinic_state() (get_io_state(module))
625
#include "clinic/_iomodule.c.h"
626
#undef clinic_state
627
628
static PyMethodDef module_methods[] = {
629
    _IO_OPEN_METHODDEF
630
    _IO_TEXT_ENCODING_METHODDEF
631
    _IO_OPEN_CODE_METHODDEF
632
    {NULL, NULL}
633
};
634
635
518
#define ADD_TYPE(module, type, spec, base)                               \
636
518
do {                                                                     \
637
518
    type = (PyTypeObject *)PyType_FromModuleAndSpec(module, spec,        \
638
518
                                                    (PyObject *)base);   \
639
518
    if (type == NULL) {                                                  \
640
0
        return -1;                                                       \
641
0
    }                                                                    \
642
518
    if (PyModule_AddType(module, type) < 0) {                            \
643
0
        return -1;                                                       \
644
0
    }                                                                    \
645
518
} while (0)
646
647
static int
648
iomodule_exec(PyObject *m)
649
37
{
650
37
    _PyIO_State *state = get_io_state(m);
651
652
    /* DEFAULT_BUFFER_SIZE */
653
37
    if (PyModule_AddIntMacro(m, DEFAULT_BUFFER_SIZE) < 0)
654
0
        return -1;
655
656
    /* UnsupportedOperation inherits from ValueError and OSError */
657
37
    state->unsupported_operation = PyObject_CallFunction(
658
37
        (PyObject *)&PyType_Type, "s(OO){}",
659
37
        "UnsupportedOperation", PyExc_OSError, PyExc_ValueError);
660
37
    if (state->unsupported_operation == NULL)
661
0
        return -1;
662
37
    if (PyObject_SetAttrString(state->unsupported_operation,
663
37
                               "__module__", &_Py_ID(io)) < 0)
664
0
    {
665
0
        return -1;
666
0
    }
667
37
    if (PyModule_AddObjectRef(m, "UnsupportedOperation",
668
37
                              state->unsupported_operation) < 0)
669
0
    {
670
0
        return -1;
671
0
    }
672
673
    /* BlockingIOError, for compatibility */
674
37
    if (PyModule_AddObjectRef(m, "BlockingIOError",
675
37
                              (PyObject *) PyExc_BlockingIOError) < 0) {
676
0
        return -1;
677
0
    }
678
679
    // Base classes
680
37
    ADD_TYPE(m, state->PyIncrementalNewlineDecoder_Type, &_Py_nldecoder_spec, NULL);
681
37
    ADD_TYPE(m, state->PyBytesIOBuffer_Type, &_Py_bytesiobuf_spec, NULL);
682
37
    ADD_TYPE(m, state->PyIOBase_Type, &_Py_iobase_spec, NULL);
683
684
    // PyIOBase_Type subclasses
685
37
    ADD_TYPE(m, state->PyTextIOBase_Type, &_Py_textiobase_spec,
686
37
             state->PyIOBase_Type);
687
37
    ADD_TYPE(m, state->PyBufferedIOBase_Type, &_Py_bufferediobase_spec,
688
37
             state->PyIOBase_Type);
689
37
    ADD_TYPE(m, state->PyRawIOBase_Type, &_Py_rawiobase_spec,
690
37
             state->PyIOBase_Type);
691
692
    // PyBufferedIOBase_Type(PyIOBase_Type) subclasses
693
37
    ADD_TYPE(m, state->PyBytesIO_Type, &_Py_bytesio_spec, state->PyBufferedIOBase_Type);
694
37
    ADD_TYPE(m, state->PyBufferedWriter_Type, &_Py_bufferedwriter_spec,
695
37
             state->PyBufferedIOBase_Type);
696
37
    ADD_TYPE(m, state->PyBufferedReader_Type, &_Py_bufferedreader_spec,
697
37
             state->PyBufferedIOBase_Type);
698
37
    ADD_TYPE(m, state->PyBufferedRWPair_Type, &_Py_bufferedrwpair_spec,
699
37
             state->PyBufferedIOBase_Type);
700
37
    ADD_TYPE(m, state->PyBufferedRandom_Type, &_Py_bufferedrandom_spec,
701
37
             state->PyBufferedIOBase_Type);
702
703
    // PyRawIOBase_Type(PyIOBase_Type) subclasses
704
37
    ADD_TYPE(m, state->PyFileIO_Type, &_Py_fileio_spec, state->PyRawIOBase_Type);
705
706
#ifdef HAVE_WINDOWS_CONSOLE_IO
707
    ADD_TYPE(m, state->PyWindowsConsoleIO_Type, &_Py_winconsoleio_spec,
708
             state->PyRawIOBase_Type);
709
#endif
710
711
    // PyTextIOBase_Type(PyIOBase_Type) subclasses
712
37
    ADD_TYPE(m, state->PyStringIO_Type, &_Py_stringio_spec, state->PyTextIOBase_Type);
713
37
    ADD_TYPE(m, state->PyTextIOWrapper_Type, &_Py_textiowrapper_spec,
714
37
             state->PyTextIOBase_Type);
715
716
37
#undef ADD_TYPE
717
37
    return 0;
718
37
}
719
720
static struct PyModuleDef_Slot iomodule_slots[] = {
721
    _Py_ABI_SLOT,
722
    {Py_mod_exec, iomodule_exec},
723
    {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
724
    {Py_mod_gil, Py_MOD_GIL_NOT_USED},
725
    {0, NULL},
726
};
727
728
struct PyModuleDef _PyIO_Module = {
729
    .m_base = PyModuleDef_HEAD_INIT,
730
    .m_name = "io",
731
    .m_doc = module_doc,
732
    .m_size = sizeof(_PyIO_State),
733
    .m_methods = module_methods,
734
    .m_traverse = iomodule_traverse,
735
    .m_clear = iomodule_clear,
736
    .m_free = iomodule_free,
737
    .m_slots = iomodule_slots,
738
};
739
740
PyMODINIT_FUNC
741
PyInit__io(void)
742
37
{
743
37
    return PyModuleDef_Init(&_PyIO_Module);
744
37
}