Coverage Report

Created: 2025-07-11 06:24

/src/cpython/Modules/_io/fileio.c
Line
Count
Source (jump to first uncovered line)
1
/* Author: Daniel Stutzbach */
2
3
#include "Python.h"
4
#include "pycore_fileutils.h"     // _Py_BEGIN_SUPPRESS_IPH
5
#include "pycore_object.h"        // _PyObject_GC_UNTRACK()
6
#include "pycore_pyerrors.h"      // _PyErr_ChainExceptions1()
7
#include "pycore_weakref.h"       // FT_CLEAR_WEAKREFS()
8
9
#include <stdbool.h>              // bool
10
#ifdef HAVE_UNISTD_H
11
#  include <unistd.h>             // lseek()
12
#endif
13
#ifdef HAVE_SYS_TYPES_H
14
#  include <sys/types.h>
15
#endif
16
#ifdef HAVE_IO_H
17
#  include <io.h>
18
#endif
19
#ifdef HAVE_FCNTL_H
20
#  include <fcntl.h>              // open()
21
#endif
22
23
#include "_iomodule.h"
24
25
/*
26
 * Known likely problems:
27
 *
28
 * - Files larger then 2**32-1
29
 * - Files with unicode filenames
30
 * - Passing numbers greater than 2**32-1 when an integer is expected
31
 * - Making it work on Windows and other oddball platforms
32
 *
33
 * To Do:
34
 *
35
 * - autoconfify header file inclusion
36
 */
37
38
#ifdef MS_WINDOWS
39
   // can simulate truncate with Win32 API functions; see file_truncate
40
#  define HAVE_FTRUNCATE
41
#  ifndef WIN32_LEAN_AND_MEAN
42
#    define WIN32_LEAN_AND_MEAN
43
#  endif
44
#  include <windows.h>
45
#endif
46
47
#if BUFSIZ < (8*1024)
48
#  define SMALLCHUNK (8*1024)
49
#elif (BUFSIZ >= (2 << 25))
50
#  error "unreasonable BUFSIZ > 64 MiB defined"
51
#else
52
3
#  define SMALLCHUNK BUFSIZ
53
#endif
54
55
/* Size at which a buffer is considered "large" and behavior should change to
56
   avoid excessive memory allocation */
57
947
#define LARGE_BUFFER_CUTOFF_SIZE 65536
58
59
/*[clinic input]
60
module _io
61
class _io.FileIO "fileio *" "clinic_state()->PyFileIO_Type"
62
[clinic start generated code]*/
63
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=ac25ec278f4d6703]*/
64
65
typedef struct {
66
    PyObject_HEAD
67
    int fd;
68
    unsigned int created : 1;
69
    unsigned int readable : 1;
70
    unsigned int writable : 1;
71
    unsigned int appending : 1;
72
    signed int seekable : 2; /* -1 means unknown */
73
    unsigned int closefd : 1;
74
    char finalizing;
75
    /* Stat result which was grabbed at file open, useful for optimizing common
76
       File I/O patterns to be more efficient. This is only guidance / an
77
       estimate, as it is subject to Time-Of-Check to Time-Of-Use (TOCTOU)
78
       issues / bugs. Both the underlying file descriptor and file may be
79
       modified outside of the fileio object / Python (ex. gh-90102, GH-121941,
80
       gh-109523). */
81
    struct _Py_stat_struct *stat_atopen;
82
    PyObject *weakreflist;
83
    PyObject *dict;
84
} fileio;
85
86
#define PyFileIO_Check(state, op) (PyObject_TypeCheck((op), state->PyFileIO_Type))
87
21.8k
#define PyFileIO_CAST(op) ((fileio *)(op))
88
89
/* Forward declarations */
90
static PyObject* portable_lseek(fileio *self, PyObject *posobj, int whence, bool suppress_pipe_error);
91
92
int
93
_PyFileIO_closed(PyObject *self)
94
958
{
95
958
    return (PyFileIO_CAST(self)->fd < 0);
96
958
}
97
98
/* Because this can call arbitrary code, it shouldn't be called when
99
   the refcount is 0 (that is, not directly from tp_dealloc unless
100
   the refcount has been temporarily re-incremented). */
101
static PyObject *
102
fileio_dealloc_warn(PyObject *op, PyObject *source)
103
0
{
104
0
    fileio *self = PyFileIO_CAST(op);
105
0
    if (self->fd >= 0 && self->closefd) {
106
0
        PyObject *exc = PyErr_GetRaisedException();
107
0
        if (PyErr_ResourceWarning(source, 1, "unclosed file %R", source)) {
108
            /* Spurious errors can appear at shutdown */
109
0
            if (PyErr_ExceptionMatches(PyExc_Warning)) {
110
0
                PyErr_FormatUnraisable("Exception ignored "
111
0
                                       "while finalizing file %R", self);
112
0
            }
113
0
        }
114
0
        PyErr_SetRaisedException(exc);
115
0
    }
116
0
    Py_RETURN_NONE;
117
0
}
118
119
/* Returns 0 on success, -1 with exception set on failure. */
120
static int
121
internal_close(fileio *self)
122
1.17k
{
123
1.17k
    int err = 0;
124
1.17k
    int save_errno = 0;
125
1.17k
    if (self->fd >= 0) {
126
1.17k
        int fd = self->fd;
127
1.17k
        self->fd = -1;
128
        /* fd is accessible and someone else may have closed it */
129
1.17k
        Py_BEGIN_ALLOW_THREADS
130
1.17k
        _Py_BEGIN_SUPPRESS_IPH
131
1.17k
        err = close(fd);
132
1.17k
        if (err < 0)
133
0
            save_errno = errno;
134
1.17k
        _Py_END_SUPPRESS_IPH
135
1.17k
        Py_END_ALLOW_THREADS
136
1.17k
    }
137
1.17k
    PyMem_Free(self->stat_atopen);
138
1.17k
    self->stat_atopen = NULL;
139
1.17k
    if (err < 0) {
140
0
        errno = save_errno;
141
0
        PyErr_SetFromErrno(PyExc_OSError);
142
0
        return -1;
143
0
    }
144
1.17k
    return 0;
145
1.17k
}
146
147
/*[clinic input]
148
_io.FileIO.close
149
150
    cls: defining_class
151
    /
152
153
Close the file.
154
155
A closed file cannot be used for further I/O operations.  close() may be
156
called more than once without error.
157
[clinic start generated code]*/
158
159
static PyObject *
160
_io_FileIO_close_impl(fileio *self, PyTypeObject *cls)
161
/*[clinic end generated code: output=c30cbe9d1f23ca58 input=70da49e63db7c64d]*/
162
1.17k
{
163
1.17k
    PyObject *res;
164
1.17k
    int rc;
165
1.17k
    _PyIO_State *state = get_io_state_by_cls(cls);
166
1.17k
    res = PyObject_CallMethodOneArg((PyObject*)state->PyRawIOBase_Type,
167
1.17k
                                     &_Py_ID(close), (PyObject *)self);
168
1.17k
    if (!self->closefd) {
169
0
        self->fd = -1;
170
0
        return res;
171
0
    }
172
173
1.17k
    PyObject *exc = NULL;
174
1.17k
    if (res == NULL) {
175
0
        exc = PyErr_GetRaisedException();
176
0
    }
177
1.17k
    if (self->finalizing) {
178
0
        PyObject *r = fileio_dealloc_warn((PyObject*)self, (PyObject *) self);
179
0
        if (r) {
180
0
            Py_DECREF(r);
181
0
        }
182
0
        else {
183
0
            PyErr_Clear();
184
0
        }
185
0
    }
186
1.17k
    rc = internal_close(self);
187
1.17k
    if (res == NULL) {
188
0
        _PyErr_ChainExceptions1(exc);
189
0
    }
190
1.17k
    if (rc < 0) {
191
0
        Py_CLEAR(res);
192
0
    }
193
1.17k
    return res;
194
1.17k
}
195
196
static PyObject *
197
fileio_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
198
1.22k
{
199
1.22k
    assert(type != NULL && type->tp_alloc != NULL);
200
201
1.22k
    fileio *self = (fileio *) type->tp_alloc(type, 0);
202
1.22k
    if (self == NULL) {
203
0
        return NULL;
204
0
    }
205
206
1.22k
    self->fd = -1;
207
1.22k
    self->created = 0;
208
1.22k
    self->readable = 0;
209
1.22k
    self->writable = 0;
210
1.22k
    self->appending = 0;
211
1.22k
    self->seekable = -1;
212
1.22k
    self->stat_atopen = NULL;
213
1.22k
    self->closefd = 1;
214
1.22k
    self->weakreflist = NULL;
215
1.22k
    return (PyObject *) self;
216
1.22k
}
217
218
#ifdef O_CLOEXEC
219
extern int _Py_open_cloexec_works;
220
#endif
221
222
/*[clinic input]
223
_io.FileIO.__init__
224
    file as nameobj: object
225
    mode: str = "r"
226
    closefd: bool = True
227
    opener: object = None
228
229
Open a file.
230
231
The mode can be 'r' (default), 'w', 'x' or 'a' for reading,
232
writing, exclusive creation or appending.  The file will be created if it
233
doesn't exist when opened for writing or appending; it will be truncated
234
when opened for writing.  A FileExistsError will be raised if it already
235
exists when opened for creating. Opening a file for creating implies
236
writing so this mode behaves in a similar way to 'w'.Add a '+' to the mode
237
to allow simultaneous reading and writing. A custom opener can be used by
238
passing a callable as *opener*. The underlying file descriptor for the file
239
object is then obtained by calling opener with (*name*, *flags*).
240
*opener* must return an open file descriptor (passing os.open as *opener*
241
results in functionality similar to passing None).
242
[clinic start generated code]*/
243
244
static int
245
_io_FileIO___init___impl(fileio *self, PyObject *nameobj, const char *mode,
246
                         int closefd, PyObject *opener)
247
/*[clinic end generated code: output=23413f68e6484bbd input=588aac967e0ba74b]*/
248
1.22k
{
249
#ifdef MS_WINDOWS
250
    wchar_t *widename = NULL;
251
#else
252
1.22k
    const char *name = NULL;
253
1.22k
#endif
254
1.22k
    PyObject *stringobj = NULL;
255
1.22k
    const char *s;
256
1.22k
    int ret = 0;
257
1.22k
    int rwa = 0, plus = 0;
258
1.22k
    int flags = 0;
259
1.22k
    int fd = -1;
260
1.22k
    int fd_is_own = 0;
261
1.22k
#ifdef O_CLOEXEC
262
1.22k
    int *atomic_flag_works = &_Py_open_cloexec_works;
263
#elif !defined(MS_WINDOWS)
264
    int *atomic_flag_works = NULL;
265
#endif
266
1.22k
    int fstat_result;
267
1.22k
    int async_err = 0;
268
269
#ifdef Py_DEBUG
270
    _PyIO_State *state = find_io_state_by_def(Py_TYPE(self));
271
    assert(PyFileIO_Check(state, self));
272
#endif
273
1.22k
    if (self->fd >= 0) {
274
0
        if (self->closefd) {
275
            /* Have to close the existing file first. */
276
0
            if (internal_close(self) < 0) {
277
0
                return -1;
278
0
            }
279
0
        }
280
0
        else
281
0
            self->fd = -1;
282
0
    }
283
284
1.22k
    if (PyBool_Check(nameobj)) {
285
0
        if (PyErr_WarnEx(PyExc_RuntimeWarning,
286
0
                "bool is used as a file descriptor", 1))
287
0
        {
288
0
            return -1;
289
0
        }
290
0
    }
291
1.22k
    fd = PyLong_AsInt(nameobj);
292
1.22k
    if (fd < 0) {
293
952
        if (!PyErr_Occurred()) {
294
0
            PyErr_SetString(PyExc_ValueError,
295
0
                            "negative file descriptor");
296
0
            return -1;
297
0
        }
298
952
        PyErr_Clear();
299
952
    }
300
301
1.22k
    if (fd < 0) {
302
#ifdef MS_WINDOWS
303
        if (!PyUnicode_FSDecoder(nameobj, &stringobj)) {
304
            return -1;
305
        }
306
        widename = PyUnicode_AsWideCharString(stringobj, NULL);
307
        if (widename == NULL)
308
            return -1;
309
#else
310
952
        if (!PyUnicode_FSConverter(nameobj, &stringobj)) {
311
0
            return -1;
312
0
        }
313
952
        name = PyBytes_AS_STRING(stringobj);
314
952
#endif
315
952
    }
316
317
1.22k
    s = mode;
318
2.66k
    while (*s) {
319
1.44k
        switch (*s++) {
320
0
        case 'x':
321
0
            if (rwa) {
322
0
            bad_mode:
323
0
                PyErr_SetString(PyExc_ValueError,
324
0
                                "Must have exactly one of create/read/write/append "
325
0
                                "mode and at most one plus");
326
0
                goto error;
327
0
            }
328
0
            rwa = 1;
329
0
            self->created = 1;
330
0
            self->writable = 1;
331
0
            flags |= O_EXCL | O_CREAT;
332
0
            break;
333
968
        case 'r':
334
968
            if (rwa)
335
0
                goto bad_mode;
336
968
            rwa = 1;
337
968
            self->readable = 1;
338
968
            break;
339
255
        case 'w':
340
255
            if (rwa)
341
0
                goto bad_mode;
342
255
            rwa = 1;
343
255
            self->writable = 1;
344
255
            flags |= O_CREAT | O_TRUNC;
345
255
            break;
346
0
        case 'a':
347
0
            if (rwa)
348
0
                goto bad_mode;
349
0
            rwa = 1;
350
0
            self->writable = 1;
351
0
            self->appending = 1;
352
0
            flags |= O_APPEND | O_CREAT;
353
0
            break;
354
223
        case 'b':
355
223
            break;
356
0
        case '+':
357
0
            if (plus)
358
0
                goto bad_mode;
359
0
            self->readable = self->writable = 1;
360
0
            plus = 1;
361
0
            break;
362
0
        default:
363
0
            PyErr_Format(PyExc_ValueError,
364
0
                         "invalid mode: %.200s", mode);
365
0
            goto error;
366
1.44k
        }
367
1.44k
    }
368
369
1.22k
    if (!rwa)
370
0
        goto bad_mode;
371
372
1.22k
    if (self->readable && self->writable)
373
0
        flags |= O_RDWR;
374
1.22k
    else if (self->readable)
375
968
        flags |= O_RDONLY;
376
255
    else
377
255
        flags |= O_WRONLY;
378
379
#ifdef O_BINARY
380
    flags |= O_BINARY;
381
#endif
382
383
#ifdef MS_WINDOWS
384
    flags |= O_NOINHERIT;
385
#elif defined(O_CLOEXEC)
386
    flags |= O_CLOEXEC;
387
1.22k
#endif
388
389
1.22k
    if (PySys_Audit("open", "Osi", nameobj, mode, flags) < 0) {
390
0
        goto error;
391
0
    }
392
393
1.22k
    if (fd >= 0) {
394
271
        self->fd = fd;
395
271
        self->closefd = closefd;
396
271
    }
397
952
    else {
398
952
        self->closefd = 1;
399
952
        if (!closefd) {
400
0
            PyErr_SetString(PyExc_ValueError,
401
0
                "Cannot use closefd=False with file name");
402
0
            goto error;
403
0
        }
404
405
952
        errno = 0;
406
952
        if (opener == Py_None) {
407
952
            do {
408
952
                Py_BEGIN_ALLOW_THREADS
409
#ifdef MS_WINDOWS
410
                self->fd = _wopen(widename, flags, 0666);
411
#else
412
952
                self->fd = open(name, flags, 0666);
413
952
#endif
414
952
                Py_END_ALLOW_THREADS
415
952
            } while (self->fd < 0 && errno == EINTR &&
416
952
                     !(async_err = PyErr_CheckSignals()));
417
418
952
            if (async_err)
419
0
                goto error;
420
421
952
            if (self->fd < 0) {
422
0
                PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, nameobj);
423
0
                goto error;
424
0
            }
425
952
        }
426
0
        else {
427
0
            PyObject *fdobj;
428
429
0
#ifndef MS_WINDOWS
430
            /* the opener may clear the atomic flag */
431
0
            atomic_flag_works = NULL;
432
0
#endif
433
434
0
            fdobj = PyObject_CallFunction(opener, "Oi", nameobj, flags);
435
0
            if (fdobj == NULL)
436
0
                goto error;
437
0
            if (!PyLong_Check(fdobj)) {
438
0
                Py_DECREF(fdobj);
439
0
                PyErr_SetString(PyExc_TypeError,
440
0
                        "expected integer from opener");
441
0
                goto error;
442
0
            }
443
444
0
            self->fd = PyLong_AsInt(fdobj);
445
0
            Py_DECREF(fdobj);
446
0
            if (self->fd < 0) {
447
0
                if (!PyErr_Occurred()) {
448
                    /* The opener returned a negative but didn't set an
449
                       exception.  See issue #27066 */
450
0
                    PyErr_Format(PyExc_ValueError,
451
0
                                 "opener returned %d", self->fd);
452
0
                }
453
0
                goto error;
454
0
            }
455
0
        }
456
952
        fd_is_own = 1;
457
458
952
#ifndef MS_WINDOWS
459
952
        if (_Py_set_inheritable(self->fd, 0, atomic_flag_works) < 0)
460
0
            goto error;
461
952
#endif
462
952
    }
463
464
1.22k
    PyMem_Free(self->stat_atopen);
465
1.22k
    self->stat_atopen = PyMem_New(struct _Py_stat_struct, 1);
466
1.22k
    if (self->stat_atopen == NULL) {
467
0
        PyErr_NoMemory();
468
0
        goto error;
469
0
    }
470
1.22k
    Py_BEGIN_ALLOW_THREADS
471
1.22k
    fstat_result = _Py_fstat_noraise(self->fd, self->stat_atopen);
472
1.22k
    Py_END_ALLOW_THREADS
473
1.22k
    if (fstat_result < 0) {
474
        /* Tolerate fstat() errors other than EBADF.  See Issue #25717, where
475
        an anonymous file on a Virtual Box shared folder filesystem would
476
        raise ENOENT. */
477
#ifdef MS_WINDOWS
478
        if (GetLastError() == ERROR_INVALID_HANDLE) {
479
            PyErr_SetFromWindowsErr(0);
480
#else
481
0
        if (errno == EBADF) {
482
0
            PyErr_SetFromErrno(PyExc_OSError);
483
0
#endif
484
0
            goto error;
485
0
        }
486
487
0
        PyMem_Free(self->stat_atopen);
488
0
        self->stat_atopen = NULL;
489
0
    }
490
1.22k
    else {
491
1.22k
#if defined(S_ISDIR) && defined(EISDIR)
492
        /* On Unix, open will succeed for directories.
493
           In Python, there should be no file objects referring to
494
           directories, so we need a check.  */
495
1.22k
        if (S_ISDIR(self->stat_atopen->st_mode)) {
496
0
            errno = EISDIR;
497
0
            PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, nameobj);
498
0
            goto error;
499
0
        }
500
1.22k
#endif /* defined(S_ISDIR) */
501
1.22k
    }
502
503
#if defined(MS_WINDOWS) || defined(__CYGWIN__)
504
    /* don't translate newlines (\r\n <=> \n) */
505
    _setmode(self->fd, O_BINARY);
506
#endif
507
508
1.22k
    if (PyObject_SetAttr((PyObject *)self, &_Py_ID(name), nameobj) < 0)
509
0
        goto error;
510
511
1.22k
    if (self->appending) {
512
        /* For consistent behaviour, we explicitly seek to the
513
           end of file (otherwise, it might be done only on the
514
           first write()). */
515
0
        PyObject *pos = portable_lseek(self, NULL, 2, true);
516
0
        if (pos == NULL)
517
0
            goto error;
518
0
        Py_DECREF(pos);
519
0
    }
520
521
1.22k
    goto done;
522
523
1.22k
 error:
524
0
    ret = -1;
525
0
    if (!fd_is_own)
526
0
        self->fd = -1;
527
0
    if (self->fd >= 0) {
528
0
        PyObject *exc = PyErr_GetRaisedException();
529
0
        internal_close(self);
530
0
        _PyErr_ChainExceptions1(exc);
531
0
    }
532
0
    PyMem_Free(self->stat_atopen);
533
0
    self->stat_atopen = NULL;
534
535
1.22k
 done:
536
#ifdef MS_WINDOWS
537
    PyMem_Free(widename);
538
#endif
539
1.22k
    Py_CLEAR(stringobj);
540
1.22k
    return ret;
541
0
}
542
543
static int
544
fileio_traverse(PyObject *op, visitproc visit, void *arg)
545
12.3k
{
546
12.3k
    fileio *self = PyFileIO_CAST(op);
547
12.3k
    Py_VISIT(Py_TYPE(self));
548
12.3k
    Py_VISIT(self->dict);
549
12.3k
    return 0;
550
12.3k
}
551
552
static int
553
fileio_clear(PyObject *op)
554
1.17k
{
555
1.17k
    fileio *self = PyFileIO_CAST(op);
556
1.17k
    Py_CLEAR(self->dict);
557
1.17k
    return 0;
558
1.17k
}
559
560
static void
561
fileio_dealloc(PyObject *op)
562
1.17k
{
563
1.17k
    fileio *self = PyFileIO_CAST(op);
564
1.17k
    self->finalizing = 1;
565
1.17k
    if (_PyIOBase_finalize(op) < 0) {
566
0
        return;
567
0
    }
568
569
1.17k
    _PyObject_GC_UNTRACK(self);
570
1.17k
    if (self->stat_atopen != NULL) {
571
0
        PyMem_Free(self->stat_atopen);
572
0
        self->stat_atopen = NULL;
573
0
    }
574
1.17k
    FT_CLEAR_WEAKREFS(op, self->weakreflist);
575
1.17k
    (void)fileio_clear(op);
576
577
1.17k
    PyTypeObject *tp = Py_TYPE(op);
578
1.17k
    tp->tp_free(op);
579
1.17k
    Py_DECREF(tp);
580
1.17k
}
581
582
static PyObject *
583
err_closed(void)
584
0
{
585
0
    PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
586
0
    return NULL;
587
0
}
588
589
static PyObject *
590
err_mode(_PyIO_State *state, const char *action)
591
0
{
592
0
    return PyErr_Format(state->unsupported_operation,
593
0
                        "File not open for %s", action);
594
0
}
595
596
/*[clinic input]
597
_io.FileIO.fileno
598
599
Return the underlying file descriptor (an integer).
600
[clinic start generated code]*/
601
602
static PyObject *
603
_io_FileIO_fileno_impl(fileio *self)
604
/*[clinic end generated code: output=a9626ce5398ece90 input=0b9b2de67335ada3]*/
605
0
{
606
0
    if (self->fd < 0)
607
0
        return err_closed();
608
0
    return PyLong_FromLong((long) self->fd);
609
0
}
610
611
/*[clinic input]
612
_io.FileIO.readable
613
614
True if file was opened in a read mode.
615
[clinic start generated code]*/
616
617
static PyObject *
618
_io_FileIO_readable_impl(fileio *self)
619
/*[clinic end generated code: output=640744a6150fe9ba input=a3fdfed6eea721c5]*/
620
984
{
621
984
    if (self->fd < 0)
622
0
        return err_closed();
623
984
    return PyBool_FromLong((long) self->readable);
624
984
}
625
626
/*[clinic input]
627
_io.FileIO.writable
628
629
True if file was opened in a write mode.
630
[clinic start generated code]*/
631
632
static PyObject *
633
_io_FileIO_writable_impl(fileio *self)
634
/*[clinic end generated code: output=96cefc5446e89977 input=c204a808ca2e1748]*/
635
64
{
636
64
    if (self->fd < 0)
637
0
        return err_closed();
638
64
    return PyBool_FromLong((long) self->writable);
639
64
}
640
641
/*[clinic input]
642
_io.FileIO.seekable
643
644
True if file supports random-access.
645
[clinic start generated code]*/
646
647
static PyObject *
648
_io_FileIO_seekable_impl(fileio *self)
649
/*[clinic end generated code: output=47909ca0a42e9287 input=c8e5554d2fd63c7f]*/
650
54
{
651
54
    if (self->fd < 0)
652
0
        return err_closed();
653
54
    if (self->seekable < 0) {
654
        /* portable_lseek() sets the seekable attribute */
655
0
        PyObject *pos = portable_lseek(self, NULL, SEEK_CUR, false);
656
0
        assert(self->seekable >= 0);
657
0
        if (pos == NULL) {
658
0
            PyErr_Clear();
659
0
        }
660
0
        else {
661
0
            Py_DECREF(pos);
662
0
        }
663
0
    }
664
54
    return PyBool_FromLong((long) self->seekable);
665
54
}
666
667
/*[clinic input]
668
_io.FileIO.readinto
669
    cls: defining_class
670
    buffer: Py_buffer(accept={rwbuffer})
671
    /
672
673
Same as RawIOBase.readinto().
674
[clinic start generated code]*/
675
676
static PyObject *
677
_io_FileIO_readinto_impl(fileio *self, PyTypeObject *cls, Py_buffer *buffer)
678
/*[clinic end generated code: output=97f0f3d69534db34 input=fd20323e18ce1ec8]*/
679
4
{
680
4
    Py_ssize_t n;
681
4
    int err;
682
683
4
    if (self->fd < 0)
684
0
        return err_closed();
685
4
    if (!self->readable) {
686
0
        _PyIO_State *state = get_io_state_by_cls(cls);
687
0
        return err_mode(state, "reading");
688
0
    }
689
690
4
    n = _Py_read(self->fd, buffer->buf, buffer->len);
691
    /* copy errno because PyBuffer_Release() can indirectly modify it */
692
4
    err = errno;
693
694
4
    if (n == -1) {
695
0
        if (err == EAGAIN) {
696
0
            PyErr_Clear();
697
0
            Py_RETURN_NONE;
698
0
        }
699
0
        return NULL;
700
0
    }
701
702
4
    return PyLong_FromSsize_t(n);
703
4
}
704
705
static size_t
706
new_buffersize(fileio *self, size_t currentsize)
707
0
{
708
0
    size_t addend;
709
710
    /* Expand the buffer by an amount proportional to the current size,
711
       giving us amortized linear-time behavior.  For bigger sizes, use a
712
       less-than-double growth factor to avoid excessive allocation. */
713
0
    assert(currentsize <= PY_SSIZE_T_MAX);
714
0
    if (currentsize > LARGE_BUFFER_CUTOFF_SIZE)
715
0
        addend = currentsize >> 3;
716
0
    else
717
0
        addend = 256 + currentsize;
718
0
    if (addend < SMALLCHUNK)
719
        /* Avoid tiny read() calls. */
720
0
        addend = SMALLCHUNK;
721
0
    return addend + currentsize;
722
0
}
723
724
/*[clinic input]
725
_io.FileIO.readall
726
727
Read all data from the file, returned as bytes.
728
729
Reads until either there is an error or read() returns size 0 (indicates EOF).
730
If the file is already at EOF, returns an empty bytes object.
731
732
In non-blocking mode, returns as much data as could be read before EAGAIN. If no
733
data is available (EAGAIN is returned before bytes are read) returns None.
734
[clinic start generated code]*/
735
736
static PyObject *
737
_io_FileIO_readall_impl(fileio *self)
738
/*[clinic end generated code: output=faa0292b213b4022 input=1e19849857f5d0a1]*/
739
950
{
740
950
    Py_off_t pos, end;
741
950
    PyObject *result;
742
950
    Py_ssize_t bytes_read = 0;
743
950
    Py_ssize_t n;
744
950
    size_t bufsize;
745
746
950
    if (self->fd < 0) {
747
0
        return err_closed();
748
0
    }
749
750
950
    if (self->stat_atopen != NULL && self->stat_atopen->st_size < _PY_READ_MAX) {
751
950
        end = (Py_off_t)self->stat_atopen->st_size;
752
950
    }
753
0
    else {
754
0
        end = -1;
755
0
    }
756
950
    if (end <= 0) {
757
        /* Use a default size and resize as needed. */
758
3
        bufsize = SMALLCHUNK;
759
3
    }
760
947
    else {
761
        /* This is probably a real file. */
762
947
        if (end > _PY_READ_MAX - 1) {
763
0
            bufsize = _PY_READ_MAX;
764
0
        }
765
947
        else {
766
            /* In order to detect end of file, need a read() of at
767
               least 1 byte which returns size 0. Oversize the buffer
768
               by 1 byte so the I/O can be completed with two read()
769
               calls (one for all data, one for EOF) without needing
770
               to resize the buffer. */
771
947
            bufsize = (size_t)end + 1;
772
947
        }
773
774
        /* While a lot of code does open().read() to get the whole contents
775
           of a file it is possible a caller seeks/reads a ways into the file
776
           then calls readall() to get the rest, which would result in allocating
777
           more than required. Guard against that for larger files where we expect
778
           the I/O time to dominate anyways while keeping small files fast. */
779
947
        if (bufsize > LARGE_BUFFER_CUTOFF_SIZE) {
780
54
            Py_BEGIN_ALLOW_THREADS
781
54
            _Py_BEGIN_SUPPRESS_IPH
782
#ifdef MS_WINDOWS
783
            pos = _lseeki64(self->fd, 0L, SEEK_CUR);
784
#else
785
54
            pos = lseek(self->fd, 0L, SEEK_CUR);
786
54
#endif
787
54
            _Py_END_SUPPRESS_IPH
788
54
            Py_END_ALLOW_THREADS
789
790
54
            if (end >= pos && pos >= 0 && (end - pos) < (_PY_READ_MAX - 1)) {
791
54
                bufsize = (size_t)(end - pos) + 1;
792
54
            }
793
54
        }
794
947
    }
795
796
797
950
    result = PyBytes_FromStringAndSize(NULL, bufsize);
798
950
    if (result == NULL)
799
0
        return NULL;
800
801
1.89k
    while (1) {
802
1.89k
        if (bytes_read >= (Py_ssize_t)bufsize) {
803
0
            bufsize = new_buffersize(self, bytes_read);
804
0
            if (bufsize > PY_SSIZE_T_MAX || bufsize <= 0) {
805
0
                PyErr_SetString(PyExc_OverflowError,
806
0
                                "unbounded read returned more bytes "
807
0
                                "than a Python bytes object can hold");
808
0
                Py_DECREF(result);
809
0
                return NULL;
810
0
            }
811
812
0
            if (PyBytes_GET_SIZE(result) < (Py_ssize_t)bufsize) {
813
0
                if (_PyBytes_Resize(&result, bufsize) < 0)
814
0
                    return NULL;
815
0
            }
816
0
        }
817
818
1.89k
        n = _Py_read(self->fd,
819
1.89k
                     PyBytes_AS_STRING(result) + bytes_read,
820
1.89k
                     bufsize - bytes_read);
821
822
1.89k
        if (n == 0)
823
950
            break;
824
947
        if (n == -1) {
825
0
            if (errno == EAGAIN) {
826
0
                PyErr_Clear();
827
0
                if (bytes_read > 0)
828
0
                    break;
829
0
                Py_DECREF(result);
830
0
                Py_RETURN_NONE;
831
0
            }
832
0
            Py_DECREF(result);
833
0
            return NULL;
834
0
        }
835
947
        bytes_read += n;
836
947
    }
837
838
950
    if (PyBytes_GET_SIZE(result) > bytes_read) {
839
950
        if (_PyBytes_Resize(&result, bytes_read) < 0)
840
0
            return NULL;
841
950
    }
842
950
    return result;
843
950
}
844
845
/*[clinic input]
846
_io.FileIO.read
847
    cls: defining_class
848
    size: Py_ssize_t(accept={int, NoneType}) = -1
849
    /
850
851
Read at most size bytes, returned as bytes.
852
853
If size is less than 0, read all bytes in the file making multiple read calls.
854
See ``FileIO.readall``.
855
856
Attempts to make only one system call, retrying only per PEP 475 (EINTR). This
857
means less data may be returned than requested.
858
859
In non-blocking mode, returns None if no data is available. Return an empty
860
bytes object at EOF.
861
[clinic start generated code]*/
862
863
static PyObject *
864
_io_FileIO_read_impl(fileio *self, PyTypeObject *cls, Py_ssize_t size)
865
/*[clinic end generated code: output=bbd749c7c224143e input=cf21fddef7d38ab6]*/
866
0
{
867
0
    char *ptr;
868
0
    Py_ssize_t n;
869
0
    PyObject *bytes;
870
871
0
    if (self->fd < 0)
872
0
        return err_closed();
873
0
    if (!self->readable) {
874
0
        _PyIO_State *state = get_io_state_by_cls(cls);
875
0
        return err_mode(state, "reading");
876
0
    }
877
878
0
    if (size < 0)
879
0
        return _io_FileIO_readall_impl(self);
880
881
0
    if (size > _PY_READ_MAX) {
882
0
        size = _PY_READ_MAX;
883
0
    }
884
885
0
    bytes = PyBytes_FromStringAndSize(NULL, size);
886
0
    if (bytes == NULL)
887
0
        return NULL;
888
0
    ptr = PyBytes_AS_STRING(bytes);
889
890
0
    n = _Py_read(self->fd, ptr, size);
891
0
    if (n == -1) {
892
        /* copy errno because Py_DECREF() can indirectly modify it */
893
0
        int err = errno;
894
0
        Py_DECREF(bytes);
895
0
        if (err == EAGAIN) {
896
0
            PyErr_Clear();
897
0
            Py_RETURN_NONE;
898
0
        }
899
0
        return NULL;
900
0
    }
901
902
0
    if (n != size) {
903
0
        if (_PyBytes_Resize(&bytes, n) < 0) {
904
0
            Py_CLEAR(bytes);
905
0
            return NULL;
906
0
        }
907
0
    }
908
909
0
    return (PyObject *) bytes;
910
0
}
911
912
/*[clinic input]
913
_io.FileIO.write
914
    cls: defining_class
915
    b: Py_buffer
916
    /
917
918
Write buffer b to file, return number of bytes written.
919
920
Only makes one system call, so not all of the data may be written.
921
The number of bytes actually written is returned.  In non-blocking mode,
922
returns None if the write would block.
923
[clinic start generated code]*/
924
925
static PyObject *
926
_io_FileIO_write_impl(fileio *self, PyTypeObject *cls, Py_buffer *b)
927
/*[clinic end generated code: output=927e25be80f3b77b input=2776314f043088f5]*/
928
223
{
929
223
    Py_ssize_t n;
930
223
    int err;
931
932
223
    if (self->fd < 0)
933
0
        return err_closed();
934
223
    if (!self->writable) {
935
0
        _PyIO_State *state = get_io_state_by_cls(cls);
936
0
        return err_mode(state, "writing");
937
0
    }
938
939
223
    n = _Py_write(self->fd, b->buf, b->len);
940
    /* copy errno because PyBuffer_Release() can indirectly modify it */
941
223
    err = errno;
942
943
223
    if (n < 0) {
944
0
        if (err == EAGAIN) {
945
0
            PyErr_Clear();
946
0
            Py_RETURN_NONE;
947
0
        }
948
0
        return NULL;
949
0
    }
950
951
223
    return PyLong_FromSsize_t(n);
952
223
}
953
954
/* XXX Windows support below is likely incomplete */
955
956
/* Cribbed from posix_lseek() */
957
static PyObject *
958
portable_lseek(fileio *self, PyObject *posobj, int whence, bool suppress_pipe_error)
959
1.04k
{
960
1.04k
    Py_off_t pos, res;
961
1.04k
    int fd = self->fd;
962
963
1.04k
#ifdef SEEK_SET
964
    /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
965
1.04k
    switch (whence) {
966
#if SEEK_SET != 0
967
    case 0: whence = SEEK_SET; break;
968
#endif
969
#if SEEK_CUR != 1
970
    case 1: whence = SEEK_CUR; break;
971
#endif
972
#if SEEK_END != 2
973
    case 2: whence = SEEK_END; break;
974
#endif
975
1.04k
    }
976
1.04k
#endif /* SEEK_SET */
977
978
1.04k
    if (posobj == NULL) {
979
1.03k
        pos = 0;
980
1.03k
    }
981
6
    else {
982
#if defined(HAVE_LARGEFILE_SUPPORT)
983
        pos = PyLong_AsLongLong(posobj);
984
#else
985
6
        pos = PyLong_AsLong(posobj);
986
6
#endif
987
6
        if (PyErr_Occurred())
988
0
            return NULL;
989
6
    }
990
991
1.04k
    Py_BEGIN_ALLOW_THREADS
992
1.04k
    _Py_BEGIN_SUPPRESS_IPH
993
#ifdef MS_WINDOWS
994
    res = _lseeki64(fd, pos, whence);
995
#else
996
1.04k
    res = lseek(fd, pos, whence);
997
1.04k
#endif
998
1.04k
    _Py_END_SUPPRESS_IPH
999
1.04k
    Py_END_ALLOW_THREADS
1000
1001
1.04k
    if (self->seekable < 0) {
1002
1.00k
        self->seekable = (res >= 0);
1003
1.00k
    }
1004
1005
1.04k
    if (res < 0) {
1006
0
        if (suppress_pipe_error && errno == ESPIPE) {
1007
0
            res = 0;
1008
0
        } else {
1009
0
            return PyErr_SetFromErrno(PyExc_OSError);
1010
0
        }
1011
0
    }
1012
1013
#if defined(HAVE_LARGEFILE_SUPPORT)
1014
    return PyLong_FromLongLong(res);
1015
#else
1016
1.04k
    return PyLong_FromLong(res);
1017
1.04k
#endif
1018
1.04k
}
1019
1020
/*[clinic input]
1021
_io.FileIO.seek
1022
    pos: object
1023
    whence: int = 0
1024
    /
1025
1026
Move to new file position and return the file position.
1027
1028
Argument offset is a byte count.  Optional argument whence defaults to
1029
SEEK_SET or 0 (offset from start of file, offset should be >= 0); other values
1030
are SEEK_CUR or 1 (move relative to current position, positive or negative),
1031
and SEEK_END or 2 (move relative to end of file, usually negative, although
1032
many platforms allow seeking beyond the end of a file).
1033
1034
Note that not all file objects are seekable.
1035
[clinic start generated code]*/
1036
1037
static PyObject *
1038
_io_FileIO_seek_impl(fileio *self, PyObject *pos, int whence)
1039
/*[clinic end generated code: output=c976acdf054e6655 input=0439194b0774d454]*/
1040
6
{
1041
6
    if (self->fd < 0)
1042
0
        return err_closed();
1043
1044
6
    return portable_lseek(self, pos, whence, false);
1045
6
}
1046
1047
/*[clinic input]
1048
_io.FileIO.tell
1049
1050
Current file position.
1051
1052
Can raise OSError for non seekable files.
1053
[clinic start generated code]*/
1054
1055
static PyObject *
1056
_io_FileIO_tell_impl(fileio *self)
1057
/*[clinic end generated code: output=ffe2147058809d0b input=807e24ead4cec2f9]*/
1058
1.03k
{
1059
1.03k
    if (self->fd < 0)
1060
0
        return err_closed();
1061
1062
1.03k
    return portable_lseek(self, NULL, 1, false);
1063
1.03k
}
1064
1065
#ifdef HAVE_FTRUNCATE
1066
/*[clinic input]
1067
_io.FileIO.truncate
1068
    cls: defining_class
1069
    size as posobj: object = None
1070
    /
1071
1072
Truncate the file to at most size bytes and return the truncated size.
1073
1074
Size defaults to the current file position, as returned by tell().
1075
The current file position is changed to the value of size.
1076
[clinic start generated code]*/
1077
1078
static PyObject *
1079
_io_FileIO_truncate_impl(fileio *self, PyTypeObject *cls, PyObject *posobj)
1080
/*[clinic end generated code: output=d936732a49e8d5a2 input=c367fb45d6bb2c18]*/
1081
0
{
1082
0
    Py_off_t pos;
1083
0
    int ret;
1084
0
    int fd;
1085
1086
0
    fd = self->fd;
1087
0
    if (fd < 0)
1088
0
        return err_closed();
1089
0
    if (!self->writable) {
1090
0
        _PyIO_State *state = get_io_state_by_cls(cls);
1091
0
        return err_mode(state, "writing");
1092
0
    }
1093
1094
0
    if (posobj == Py_None) {
1095
        /* Get the current position. */
1096
0
        posobj = portable_lseek(self, NULL, 1, false);
1097
0
        if (posobj == NULL)
1098
0
            return NULL;
1099
0
    }
1100
0
    else {
1101
0
        Py_INCREF(posobj);
1102
0
    }
1103
1104
#if defined(HAVE_LARGEFILE_SUPPORT)
1105
    pos = PyLong_AsLongLong(posobj);
1106
#else
1107
0
    pos = PyLong_AsLong(posobj);
1108
0
#endif
1109
0
    if (PyErr_Occurred()){
1110
0
        Py_DECREF(posobj);
1111
0
        return NULL;
1112
0
    }
1113
1114
0
    Py_BEGIN_ALLOW_THREADS
1115
0
    _Py_BEGIN_SUPPRESS_IPH
1116
0
    errno = 0;
1117
#ifdef MS_WINDOWS
1118
    ret = _chsize_s(fd, pos);
1119
#else
1120
0
    ret = ftruncate(fd, pos);
1121
0
#endif
1122
0
    _Py_END_SUPPRESS_IPH
1123
0
    Py_END_ALLOW_THREADS
1124
1125
0
    if (ret != 0) {
1126
0
        PyErr_SetFromErrno(PyExc_OSError);
1127
0
        Py_DECREF(posobj);
1128
0
        return NULL;
1129
0
    }
1130
1131
    /* Since the file was truncated, its size at open is no longer accurate
1132
       as an estimate. Clear out the stat result, and rely on dynamic resize
1133
       code if a readall is requested. */
1134
0
    if (self->stat_atopen != NULL) {
1135
0
        PyMem_Free(self->stat_atopen);
1136
0
        self->stat_atopen = NULL;
1137
0
    }
1138
1139
0
    return posobj;
1140
0
}
1141
#endif /* HAVE_FTRUNCATE */
1142
1143
static const char *
1144
mode_string(fileio *self)
1145
0
{
1146
0
    if (self->created) {
1147
0
        if (self->readable)
1148
0
            return "xb+";
1149
0
        else
1150
0
            return "xb";
1151
0
    }
1152
0
    if (self->appending) {
1153
0
        if (self->readable)
1154
0
            return "ab+";
1155
0
        else
1156
0
            return "ab";
1157
0
    }
1158
0
    else if (self->readable) {
1159
0
        if (self->writable)
1160
0
            return "rb+";
1161
0
        else
1162
0
            return "rb";
1163
0
    }
1164
0
    else
1165
0
        return "wb";
1166
0
}
1167
1168
static PyObject *
1169
fileio_repr(PyObject *op)
1170
0
{
1171
0
    fileio *self = PyFileIO_CAST(op);
1172
0
    const char *type_name = Py_TYPE(self)->tp_name;
1173
1174
0
    if (self->fd < 0) {
1175
0
        return PyUnicode_FromFormat("<%.100s [closed]>", type_name);
1176
0
    }
1177
1178
0
    PyObject *nameobj;
1179
0
    if (PyObject_GetOptionalAttr((PyObject *) self, &_Py_ID(name), &nameobj) < 0) {
1180
0
        return NULL;
1181
0
    }
1182
0
    PyObject *res;
1183
0
    if (nameobj == NULL) {
1184
0
        res = PyUnicode_FromFormat(
1185
0
            "<%.100s fd=%d mode='%s' closefd=%s>",
1186
0
            type_name, self->fd, mode_string(self), self->closefd ? "True" : "False");
1187
0
    }
1188
0
    else {
1189
0
        int status = Py_ReprEnter((PyObject *)self);
1190
0
        res = NULL;
1191
0
        if (status == 0) {
1192
0
            res = PyUnicode_FromFormat(
1193
0
                "<%.100s name=%R mode='%s' closefd=%s>",
1194
0
                type_name, nameobj, mode_string(self), self->closefd ? "True" : "False");
1195
0
            Py_ReprLeave((PyObject *)self);
1196
0
        }
1197
0
        else if (status > 0) {
1198
0
            PyErr_Format(PyExc_RuntimeError,
1199
0
                         "reentrant call inside %.100s.__repr__", type_name);
1200
0
        }
1201
0
        Py_DECREF(nameobj);
1202
0
    }
1203
0
    return res;
1204
0
}
1205
1206
/*[clinic input]
1207
_io.FileIO.isatty
1208
1209
True if the file is connected to a TTY device.
1210
[clinic start generated code]*/
1211
1212
static PyObject *
1213
_io_FileIO_isatty_impl(fileio *self)
1214
/*[clinic end generated code: output=932c39924e9a8070 input=cd94ca1f5e95e843]*/
1215
64
{
1216
64
    long res;
1217
1218
64
    if (self->fd < 0)
1219
0
        return err_closed();
1220
64
    Py_BEGIN_ALLOW_THREADS
1221
64
    _Py_BEGIN_SUPPRESS_IPH
1222
64
    res = isatty(self->fd);
1223
64
    _Py_END_SUPPRESS_IPH
1224
64
    Py_END_ALLOW_THREADS
1225
64
    return PyBool_FromLong(res);
1226
64
}
1227
1228
/* Checks whether the file is a TTY using an open-only optimization.
1229
1230
   TTYs are always character devices. If the interpreter knows a file is
1231
   not a character device when it would call ``isatty``, can skip that
1232
   call. Inside ``open()``  there is a fresh stat result that contains that
1233
   information. Use the stat result to skip a system call. Outside of that
1234
   context TOCTOU issues (the fd could be arbitrarily modified by
1235
   surrounding code). */
1236
static PyObject *
1237
_io_FileIO_isatty_open_only(PyObject *op, PyObject *Py_UNUSED(dummy))
1238
1.00k
{
1239
1.00k
    fileio *self = PyFileIO_CAST(op);
1240
1.00k
    if (self->stat_atopen != NULL && !S_ISCHR(self->stat_atopen->st_mode)) {
1241
984
        Py_RETURN_FALSE;
1242
984
    }
1243
16
    return _io_FileIO_isatty_impl(self);
1244
1.00k
}
1245
1246
#include "clinic/fileio.c.h"
1247
1248
static PyMethodDef fileio_methods[] = {
1249
    _IO_FILEIO_READ_METHODDEF
1250
    _IO_FILEIO_READALL_METHODDEF
1251
    _IO_FILEIO_READINTO_METHODDEF
1252
    _IO_FILEIO_WRITE_METHODDEF
1253
    _IO_FILEIO_SEEK_METHODDEF
1254
    _IO_FILEIO_TELL_METHODDEF
1255
    _IO_FILEIO_TRUNCATE_METHODDEF
1256
    _IO_FILEIO_CLOSE_METHODDEF
1257
    _IO_FILEIO_SEEKABLE_METHODDEF
1258
    _IO_FILEIO_READABLE_METHODDEF
1259
    _IO_FILEIO_WRITABLE_METHODDEF
1260
    _IO_FILEIO_FILENO_METHODDEF
1261
    _IO_FILEIO_ISATTY_METHODDEF
1262
    {"_isatty_open_only", _io_FileIO_isatty_open_only, METH_NOARGS},
1263
    {"_dealloc_warn", fileio_dealloc_warn, METH_O, NULL},
1264
    {"__getstate__", _PyIOBase_cannot_pickle, METH_NOARGS},
1265
    {NULL,           NULL}             /* sentinel */
1266
};
1267
1268
/* 'closed' and 'mode' are attributes for backwards compatibility reasons. */
1269
1270
static PyObject *
1271
fileio_get_closed(PyObject *op, void *closure)
1272
4.25k
{
1273
4.25k
    fileio *self = PyFileIO_CAST(op);
1274
4.25k
    return PyBool_FromLong((long)(self->fd < 0));
1275
4.25k
}
1276
1277
static PyObject *
1278
fileio_get_closefd(PyObject *op, void *closure)
1279
0
{
1280
0
    fileio *self = PyFileIO_CAST(op);
1281
0
    return PyBool_FromLong((long)(self->closefd));
1282
0
}
1283
1284
static PyObject *
1285
fileio_get_mode(PyObject *op, void *closure)
1286
0
{
1287
0
    fileio *self = PyFileIO_CAST(op);
1288
0
    return PyUnicode_FromString(mode_string(self));
1289
0
}
1290
1291
static PyObject *
1292
fileio_get_blksize(PyObject *op, void *closure)
1293
1.00k
{
1294
1.00k
#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
1295
1.00k
    fileio *self = PyFileIO_CAST(op);
1296
1.00k
    if (self->stat_atopen != NULL && self->stat_atopen->st_blksize > 1) {
1297
1.00k
        return PyLong_FromLong(self->stat_atopen->st_blksize);
1298
1.00k
    }
1299
0
#endif /* HAVE_STRUCT_STAT_ST_BLKSIZE */
1300
0
    return PyLong_FromLong(DEFAULT_BUFFER_SIZE);
1301
1.00k
}
1302
1303
static PyGetSetDef fileio_getsetlist[] = {
1304
    {"closed", fileio_get_closed, NULL, "True if the file is closed"},
1305
    {"closefd", fileio_get_closefd, NULL,
1306
        "True if the file descriptor will be closed by close()."},
1307
    {"mode", fileio_get_mode, NULL, "String giving the file mode"},
1308
    {"_blksize", fileio_get_blksize, NULL, "Stat st_blksize if available"},
1309
    {NULL},
1310
};
1311
1312
static PyMemberDef fileio_members[] = {
1313
    {"_finalizing", Py_T_BOOL, offsetof(fileio, finalizing), 0},
1314
    {"__weaklistoffset__", Py_T_PYSSIZET, offsetof(fileio, weakreflist), Py_READONLY},
1315
    {"__dictoffset__", Py_T_PYSSIZET, offsetof(fileio, dict), Py_READONLY},
1316
    {NULL}
1317
};
1318
1319
static PyType_Slot fileio_slots[] = {
1320
    {Py_tp_dealloc, fileio_dealloc},
1321
    {Py_tp_repr, fileio_repr},
1322
    {Py_tp_doc, (void *)_io_FileIO___init____doc__},
1323
    {Py_tp_traverse, fileio_traverse},
1324
    {Py_tp_clear, fileio_clear},
1325
    {Py_tp_methods, fileio_methods},
1326
    {Py_tp_members, fileio_members},
1327
    {Py_tp_getset, fileio_getsetlist},
1328
    {Py_tp_init, _io_FileIO___init__},
1329
    {Py_tp_new, fileio_new},
1330
    {0, NULL},
1331
};
1332
1333
PyType_Spec fileio_spec = {
1334
    .name = "_io.FileIO",
1335
    .basicsize = sizeof(fileio),
1336
    .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
1337
              Py_TPFLAGS_IMMUTABLETYPE),
1338
    .slots = fileio_slots,
1339
};