Coverage Report

Created: 2026-12-01 06:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Modules/_io/bytesio.c
Line
Count
Source
1
#include "Python.h"
2
#include "pycore_bytesobject.h"       // _PyBytes_ResizeKeepOnError()
3
#include "pycore_critical_section.h"  // Py_BEGIN_CRITICAL_SECTION()
4
#include "pycore_list.h"              // _PyList_AppendTakeRef()
5
#include "pycore_object.h"
6
#include "pycore_pyatomic_ft_wrappers.h"
7
#include "pycore_sysmodule.h"         // _PySys_GetSizeOf()
8
9
#include <stddef.h>                   // offsetof()
10
#include "_iomodule.h"
11
12
/*[clinic input]
13
module _io
14
class _io.BytesIO "bytesio *" "clinic_state()->PyBytesIO_Type"
15
[clinic start generated code]*/
16
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=48ede2f330f847c3]*/
17
18
typedef struct {
19
    PyObject_HEAD
20
    PyObject *buf;
21
    Py_ssize_t pos;
22
    Py_ssize_t string_size;
23
    Py_ssize_t exports;
24
#ifdef Py_GIL_DISABLED
25
    int buf_shared;
26
#endif
27
} bytesio;
28
29
67.3k
#define bytesio_CAST(op)    ((bytesio *)(op))
30
31
typedef struct {
32
    PyObject_HEAD
33
    bytesio *source;
34
} bytesiobuf;
35
36
0
#define bytesiobuf_CAST(op) ((bytesiobuf *)(op))
37
38
/* The bytesio object can be in three states:
39
  * Py_REFCNT(buf) == 1, the hash of buf is not cached, exports == 0.
40
  * Py_REFCNT(buf) > 1 or the hash of buf is cached.  exports == 0,
41
    first modification or export causes the internal buffer copying.
42
  * exports > 0.  Any modifications are forbidden.  Every exported buffer
43
    keeps a reference to buf, so it outlives closing of the bytesio object.
44
*/
45
46
static int
47
check_closed(bytesio *self)
48
19.4M
{
49
19.4M
    if (self->buf == NULL) {
50
0
        PyErr_SetString(PyExc_ValueError, "I/O operation on closed file.");
51
0
        return 1;
52
0
    }
53
19.4M
    return 0;
54
19.4M
}
55
56
static int
57
check_exports(bytesio *self)
58
15.9k
{
59
15.9k
    if (FT_ATOMIC_LOAD_SSIZE_RELAXED(self->exports) > 0) {
60
0
        PyErr_SetString(PyExc_BufferError,
61
0
                        "Existing exports of data: object cannot be re-sized");
62
0
        return 1;
63
0
    }
64
15.9k
    return 0;
65
15.9k
}
66
67
#define CHECK_CLOSED(self)                                  \
68
19.3M
    if (check_closed(self)) {                               \
69
0
        return NULL;                                        \
70
0
    }
71
72
#define CHECK_EXPORTS(self) \
73
0
    if (check_exports(self)) { \
74
0
        return NULL; \
75
0
    }
76
77
/* If the hash value is cached, the internal bytes object was already used in
78
   Python somehow (ex: as a dictionary key).  Modifying it in place would leave
79
   the hash of the old contents, even if nothing else references it anymore. */
80
#define HASHED_BUF(self) \
81
11.2k
    (_PyBytes_GET_CACHED_HASH((PyBytesObject *)(self)->buf) != -1)
82
83
#ifdef Py_GIL_DISABLED
84
#define SHARED_BUF(self) \
85
    ((self)->buf_shared || !_PyObject_IsUniquelyReferenced((self)->buf) \
86
     || HASHED_BUF(self))
87
#else
88
#define SHARED_BUF(self) \
89
14.0k
    (!_PyObject_IsUniquelyReferenced((self)->buf) || HASHED_BUF(self))
90
#endif
91
92
static inline void
93
set_shared_buf(bytesio *self)
94
31.4k
{
95
#ifdef Py_GIL_DISABLED
96
    self->buf_shared = 1;
97
#endif
98
31.4k
}
99
100
static inline void
101
clear_shared_buf(bytesio *self)
102
65.3k
{
103
#ifdef Py_GIL_DISABLED
104
    self->buf_shared = 0;
105
#endif
106
65.3k
}
107
108
static int
109
resize_unshared_buffer_lock_held(bytesio *self, Py_ssize_t size)
110
7.69k
{
111
7.69k
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(self);
112
113
#ifdef Py_GIL_DISABLED
114
    /* If the internal bytes object escaped via a zero-copy getvalue(), read(),
115
       or peek(), resizing it would mutate an object visible to Python code.
116
       Callers must detach first. */
117
    assert(!self->buf_shared);
118
#endif
119
7.69k
    int ret = _PyBytes_ResizeKeepOnError(&self->buf, size);
120
7.69k
    if (ret == 0) {
121
7.69k
        clear_shared_buf(self);
122
7.69k
    }
123
7.69k
    return ret;
124
7.69k
}
125
126
127
/* Internal routine to get a line from the buffer of a BytesIO
128
   object. Returns the length between the current position to the
129
   next newline character. */
130
static Py_ssize_t
131
scan_eol_lock_held(bytesio *self, Py_ssize_t len)
132
136k
{
133
136k
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(self);
134
135
136k
    const char *start, *n;
136
136k
    Py_ssize_t maxlen;
137
138
136k
    assert(self->buf != NULL);
139
136k
    assert(self->pos >= 0);
140
141
136k
    if (self->pos >= self->string_size)
142
9.34k
        return 0;
143
144
    /* Move to the end of the line, up to the end of the string, s. */
145
127k
    maxlen = self->string_size - self->pos;
146
127k
    if (len < 0 || len > maxlen)
147
103k
        len = maxlen;
148
149
127k
    if (len) {
150
127k
        start = PyBytes_AS_STRING(self->buf) + self->pos;
151
127k
        n = memchr(start, '\n', len);
152
127k
        if (n)
153
            /* Get the length from the current position to the end of
154
               the line. */
155
117k
            len = n - start + 1;
156
127k
    }
157
127k
    assert(len >= 0);
158
127k
    assert(self->pos < PY_SSIZE_T_MAX - len);
159
160
127k
    return len;
161
136k
}
162
163
/* Internal routine for detaching the shared buffer of BytesIO objects.
164
   The caller should ensure that the 'size' argument is non-negative and
165
   not lesser than self->string_size.  Returns 0 on success, -1 otherwise. */
166
static int
167
unshare_buffer_lock_held(bytesio *self, size_t size)
168
2.85k
{
169
2.85k
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(self);
170
171
2.85k
    PyObject *new_buf;
172
2.85k
    assert(SHARED_BUF(self));
173
2.85k
    assert(FT_ATOMIC_LOAD_SSIZE_RELAXED(self->exports) == 0);
174
2.85k
    assert(size >= (size_t)self->string_size);
175
2.85k
    new_buf = PyBytes_FromStringAndSize(NULL, size);
176
2.85k
    if (new_buf == NULL)
177
0
        return -1;
178
2.85k
    memcpy(PyBytes_AS_STRING(new_buf), PyBytes_AS_STRING(self->buf),
179
2.85k
           self->string_size);
180
2.85k
    Py_SETREF(self->buf, new_buf);
181
2.85k
    clear_shared_buf(self);
182
2.85k
    return 0;
183
2.85k
}
184
185
/* Internal routine for changing the size of the buffer of BytesIO objects.
186
   The caller should ensure that the 'size' argument is non-negative.  Returns
187
   0 on success, -1 otherwise. */
188
static int
189
resize_buffer_lock_held(bytesio *self, size_t size)
190
9.93k
{
191
9.93k
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(self);
192
193
9.93k
    assert(self->buf != NULL);
194
9.93k
    assert(FT_ATOMIC_LOAD_SSIZE_RELAXED(self->exports) == 0);
195
196
    /* Here, unsigned types are used to avoid dealing with signed integer
197
       overflow, which is undefined in C. */
198
9.93k
    size_t alloc = PyBytes_GET_SIZE(self->buf);
199
200
    /* For simplicity, stay in the range of the signed type. Anyway, Python
201
       doesn't allow strings to be longer than this. */
202
9.93k
    if (size > PY_SSIZE_T_MAX)
203
0
        goto overflow;
204
205
9.93k
    if (size < alloc / 2) {
206
        /* Major downsize; resize down to exact size. */
207
0
        alloc = size + 1;
208
0
    }
209
9.93k
    else if (size < alloc) {
210
        /* Within allocated size; quick exit */
211
0
        return 0;
212
0
    }
213
9.93k
    else if (size <= alloc * 1.125) {
214
        /* Moderate upsize; overallocate similar to list_resize() */
215
1.35k
        alloc = size + (size >> 3) + (size < 9 ? 3 : 6);
216
1.35k
    }
217
8.58k
    else {
218
        /* Major upsize; resize up to exact size */
219
8.58k
        alloc = size + 1;
220
8.58k
    }
221
9.93k
    if (alloc > PY_SSIZE_T_MAX) {
222
0
        goto overflow;
223
0
    }
224
225
9.93k
    if (SHARED_BUF(self)) {
226
2.85k
        if (unshare_buffer_lock_held(self, alloc) < 0)
227
0
            return -1;
228
2.85k
    }
229
7.08k
    else {
230
7.08k
        if (resize_unshared_buffer_lock_held(self, alloc) < 0)
231
0
            return -1;
232
7.08k
    }
233
234
9.93k
    return 0;
235
236
0
  overflow:
237
0
    PyErr_SetString(PyExc_OverflowError,
238
0
                    "new buffer size too large");
239
0
    return -1;
240
9.93k
}
241
242
/* Internal routine for writing a string of bytes to the buffer of a BytesIO
243
   object. Returns the number of bytes written, or -1 on error.
244
   Inlining is disabled because it's significantly decreases performance
245
   of writelines() in PGO build. */
246
Py_NO_INLINE static Py_ssize_t
247
write_bytes_lock_held(bytesio *self, PyObject *b)
248
15.9k
{
249
15.9k
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(self);
250
251
15.9k
    Py_buffer buf;
252
15.9k
    Py_ssize_t len;
253
15.9k
    if (PyObject_GetBuffer(b, &buf, PyBUF_CONTIG_RO) < 0) {
254
0
        return -1;
255
0
    }
256
257
15.9k
    if (check_closed(self) || check_exports(self)) {
258
0
        len = -1;
259
0
        goto done;
260
0
    }
261
262
15.9k
    len = buf.len;
263
15.9k
    if (len == 0) {
264
2.51k
        goto done;
265
2.51k
    }
266
267
15.9k
    assert(self->pos >= 0);
268
13.4k
    size_t endpos = (size_t)self->pos + len;
269
13.4k
    if (endpos > (size_t)PyBytes_GET_SIZE(self->buf)) {
270
9.93k
        if (resize_buffer_lock_held(self, endpos) < 0) {
271
0
            len = -1;
272
0
            goto done;
273
0
        }
274
9.93k
    }
275
3.51k
    else if (SHARED_BUF(self)) {
276
0
        if (unshare_buffer_lock_held(self, Py_MAX(endpos, (size_t)self->string_size)) < 0) {
277
0
            len = -1;
278
0
            goto done;
279
0
        }
280
0
    }
281
13.4k
    assert(_PyBytes_IsMutable(self->buf));
282
283
13.4k
    if (self->pos > self->string_size) {
284
        /* In case of overseek, pad with null bytes the buffer region between
285
           the end of stream and the current position.
286
287
          0   lo      string_size                           hi
288
          |   |<---used--->|<----------available----------->|
289
          |   |            <--to pad-->|<---to write--->    |
290
          0   buf                   position
291
        */
292
0
        memset(PyBytes_AS_STRING(self->buf) + self->string_size, '\0',
293
0
               (self->pos - self->string_size) * sizeof(char));
294
0
    }
295
296
    /* Copy the data to the internal buffer, overwriting some of the existing
297
       data if self->pos < self->string_size. */
298
13.4k
    memcpy(PyBytes_AS_STRING(self->buf) + self->pos, buf.buf, len);
299
13.4k
    self->pos = endpos;
300
301
    /* Set the new length of the internal string if it has changed. */
302
13.4k
    if ((size_t)self->string_size < endpos) {
303
12.8k
        self->string_size = endpos;
304
12.8k
    }
305
306
15.9k
  done:
307
15.9k
    PyBuffer_Release(&buf);
308
15.9k
    return len;
309
13.4k
}
310
311
/*[clinic input]
312
@critical_section
313
@getter
314
_io.BytesIO.closed -> bool
315
316
True if the file is closed.
317
[clinic start generated code]*/
318
319
static int
320
_io_BytesIO_closed_get_impl(bytesio *self)
321
/*[clinic end generated code: output=7cdc647cc7a71683 input=0687f923344225ee]*/
322
0
{
323
0
    return self->buf == NULL;
324
0
}
325
326
/*[clinic input]
327
@critical_section
328
_io.BytesIO.readable
329
330
Returns True if the IO object can be read.
331
[clinic start generated code]*/
332
333
static PyObject *
334
_io_BytesIO_readable_impl(bytesio *self)
335
/*[clinic end generated code: output=4e93822ad5b62263 input=ab7816facef48bfd]*/
336
0
{
337
0
    CHECK_CLOSED(self);
338
0
    Py_RETURN_TRUE;
339
0
}
340
341
/*[clinic input]
342
@critical_section
343
_io.BytesIO.writable
344
345
Returns True if the IO object can be written.
346
[clinic start generated code]*/
347
348
static PyObject *
349
_io_BytesIO_writable_impl(bytesio *self)
350
/*[clinic end generated code: output=64ff6a254b1150b8 input=4f35d49d26dab024]*/
351
0
{
352
0
    CHECK_CLOSED(self);
353
0
    Py_RETURN_TRUE;
354
0
}
355
356
/*[clinic input]
357
@critical_section
358
_io.BytesIO.seekable
359
360
Returns True if the IO object can be seeked.
361
[clinic start generated code]*/
362
363
static PyObject *
364
_io_BytesIO_seekable_impl(bytesio *self)
365
/*[clinic end generated code: output=6b417f46dcc09b56 input=9cc78d15aa1deaa3]*/
366
19.9k
{
367
19.9k
    CHECK_CLOSED(self);
368
19.9k
    Py_RETURN_TRUE;
369
19.9k
}
370
371
/*[clinic input]
372
@critical_section
373
_io.BytesIO.flush
374
375
Does nothing.
376
[clinic start generated code]*/
377
378
static PyObject *
379
_io_BytesIO_flush_impl(bytesio *self)
380
/*[clinic end generated code: output=187e3d781ca134a0 input=c60842743910b381]*/
381
10.0k
{
382
10.0k
    CHECK_CLOSED(self);
383
10.0k
    Py_RETURN_NONE;
384
10.0k
}
385
386
/*[clinic input]
387
@critical_section
388
_io.BytesIO.getbuffer
389
390
    cls: defining_class
391
    /
392
393
Get a read-write view over the contents of the BytesIO object.
394
[clinic start generated code]*/
395
396
static PyObject *
397
_io_BytesIO_getbuffer_impl(bytesio *self, PyTypeObject *cls)
398
/*[clinic end generated code: output=045091d7ce87fe4e input=8295764061be77fd]*/
399
0
{
400
0
    _PyIO_State *state = get_io_state_by_cls(cls);
401
0
    PyTypeObject *type = state->PyBytesIOBuffer_Type;
402
0
    bytesiobuf *buf;
403
0
    PyObject *view;
404
405
0
    CHECK_CLOSED(self);
406
407
0
    buf = (bytesiobuf *) type->tp_alloc(type, 0);
408
0
    if (buf == NULL)
409
0
        return NULL;
410
0
    buf->source = (bytesio*)Py_NewRef(self);
411
0
    view = PyMemoryView_FromObject((PyObject *) buf);
412
0
    Py_DECREF(buf);
413
0
    return view;
414
0
}
415
416
/*[clinic input]
417
@critical_section
418
_io.BytesIO.getvalue
419
420
Retrieve the entire contents of the BytesIO object.
421
[clinic start generated code]*/
422
423
static PyObject *
424
_io_BytesIO_getvalue_impl(bytesio *self)
425
/*[clinic end generated code: output=b3f6a3233c8fd628 input=c91bff398df0c352]*/
426
606
{
427
606
    CHECK_CLOSED(self);
428
606
    if (self->string_size <= 1 || FT_ATOMIC_LOAD_SSIZE_RELAXED(self->exports) > 0)
429
0
        return PyBytes_FromStringAndSize(PyBytes_AS_STRING(self->buf),
430
0
                                         self->string_size);
431
432
606
    if (self->string_size != PyBytes_GET_SIZE(self->buf)) {
433
604
        if (SHARED_BUF(self)) {
434
0
            if (unshare_buffer_lock_held(self, self->string_size) < 0)
435
0
                return NULL;
436
0
        }
437
604
        else {
438
604
            if (resize_unshared_buffer_lock_held(self, self->string_size) < 0)
439
0
                return NULL;
440
604
        }
441
604
    }
442
606
    set_shared_buf(self);
443
606
    return Py_NewRef(self->buf);
444
606
}
445
446
/*[clinic input]
447
@critical_section
448
_io.BytesIO.isatty
449
450
Always returns False.
451
452
BytesIO objects are not connected to a TTY-like device.
453
[clinic start generated code]*/
454
455
static PyObject *
456
_io_BytesIO_isatty_impl(bytesio *self)
457
/*[clinic end generated code: output=df67712e669f6c8f input=50487b74dc5ae8a9]*/
458
0
{
459
0
    CHECK_CLOSED(self);
460
0
    Py_RETURN_FALSE;
461
0
}
462
463
/*[clinic input]
464
@critical_section
465
_io.BytesIO.tell
466
467
Current file position, an integer.
468
[clinic start generated code]*/
469
470
static PyObject *
471
_io_BytesIO_tell_impl(bytesio *self)
472
/*[clinic end generated code: output=b54b0f93cd0e5e1d input=2c7b0e8f82e05c4d]*/
473
105k
{
474
105k
    CHECK_CLOSED(self);
475
105k
    return PyLong_FromSsize_t(self->pos);
476
105k
}
477
478
/* Read without advancing position. */
479
static PyObject *
480
peek_bytes_lock_held(bytesio *self, Py_ssize_t size)
481
19.1M
{
482
19.1M
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(self);
483
484
19.1M
    const char *output;
485
486
19.1M
    assert(self->buf != NULL);
487
19.1M
    assert(size <= self->string_size);
488
19.1M
    if (size > 1 &&
489
15.0M
        self->pos == 0 && size == PyBytes_GET_SIZE(self->buf) &&
490
30.8k
        FT_ATOMIC_LOAD_SSIZE_RELAXED(self->exports) == 0) {
491
30.8k
        set_shared_buf(self);
492
30.8k
        return Py_NewRef(self->buf);
493
30.8k
    }
494
495
    /* gh-141311: Avoid undefined behavior when self->pos (limit PY_SSIZE_T_MAX)
496
       is beyond the size of self->buf. Assert above validates size is always in
497
       bounds. When self->pos is out of bounds calling code sets size to 0. */
498
19.0M
    if (size == 0) {
499
957k
        return Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
500
957k
    }
501
502
18.1M
    output = PyBytes_AS_STRING(self->buf) + self->pos;
503
18.1M
    return PyBytes_FromStringAndSize(output, size);
504
19.0M
}
505
506
static PyObject *
507
read_bytes_lock_held(bytesio *self, Py_ssize_t size)
508
19.1M
{
509
19.1M
    PyObject *bytes = peek_bytes_lock_held(self, size);
510
19.1M
    if (bytes != NULL) {
511
19.1M
        assert(PyBytes_GET_SIZE(bytes) == size);
512
19.1M
        self->pos += size;
513
19.1M
    }
514
19.1M
    return bytes;
515
19.1M
}
516
517
/*[clinic input]
518
@critical_section
519
_io.BytesIO.read
520
    size: Py_ssize_t(accept={int, NoneType}) = -1
521
    /
522
523
Read at most size bytes, returned as a bytes object.
524
525
If the size argument is negative, read until EOF is reached.
526
Return an empty bytes object at EOF.
527
[clinic start generated code]*/
528
529
static PyObject *
530
_io_BytesIO_read_impl(bytesio *self, Py_ssize_t size)
531
/*[clinic end generated code: output=9cc025f21c75bdd2 input=9e2f7ff3075fdd39]*/
532
18.9M
{
533
18.9M
    Py_ssize_t n;
534
535
18.9M
    CHECK_CLOSED(self);
536
537
    /* adjust invalid sizes */
538
18.9M
    n = self->string_size - self->pos;
539
18.9M
    if (size < 0 || size > n) {
540
83.4k
        size = n;
541
83.4k
        if (size < 0)
542
1.88k
            size = 0;
543
83.4k
    }
544
545
18.9M
    return read_bytes_lock_held(self, size);
546
18.9M
}
547
548
549
/*[clinic input]
550
@critical_section
551
_io.BytesIO.read1
552
    size: Py_ssize_t(accept={int, NoneType}) = -1
553
    /
554
555
Read at most size bytes, returned as a bytes object.
556
557
If the size argument is negative or omitted, read until EOF is
558
reached.  Return an empty bytes object at EOF.
559
[clinic start generated code]*/
560
561
static PyObject *
562
_io_BytesIO_read1_impl(bytesio *self, Py_ssize_t size)
563
/*[clinic end generated code: output=d0f843285aa95f1c input=796ff4e0efccc4d9]*/
564
0
{
565
0
    return _io_BytesIO_read_impl(self, size);
566
0
}
567
568
569
/*[clinic input]
570
@critical_section
571
_io.BytesIO.peek
572
    size: Py_ssize_t = 0
573
    /
574
575
Return bytes from the stream without advancing the position.
576
577
Return an empty bytes object at EOF.
578
[clinic start generated code]*/
579
580
static PyObject *
581
_io_BytesIO_peek_impl(bytesio *self, Py_ssize_t size)
582
/*[clinic end generated code: output=fa4d8ce28b35db9b input=2ce74234b10aec3e]*/
583
0
{
584
0
    CHECK_CLOSED(self);
585
586
0
    if (size < 1) {
587
0
        size = DEFAULT_BUFFER_SIZE;
588
0
    }
589
590
    /* adjust invalid sizes */
591
0
    Py_ssize_t n = self->string_size - self->pos;
592
0
    if (size > n) {
593
0
        size = n;
594
        /* n can be negative after truncate() or seek() */
595
0
        if (size < 0) {
596
0
            size = 0;
597
0
        }
598
0
    }
599
0
    return peek_bytes_lock_held(self, size);
600
0
}
601
602
603
/*[clinic input]
604
@critical_section
605
_io.BytesIO.readline
606
    size: Py_ssize_t(accept={int, NoneType}) = -1
607
    /
608
609
Next line from the file, as a bytes object.
610
611
Retain newline.  A non-negative size argument limits the maximum
612
number of bytes to return (an incomplete line may be returned then).
613
Return an empty bytes object at EOF.
614
[clinic start generated code]*/
615
616
static PyObject *
617
_io_BytesIO_readline_impl(bytesio *self, Py_ssize_t size)
618
/*[clinic end generated code: output=4bff3c251df8ffcd input=db09d47e23cf2c9e]*/
619
136k
{
620
136k
    Py_ssize_t n;
621
622
136k
    CHECK_CLOSED(self);
623
624
136k
    n = scan_eol_lock_held(self, size);
625
626
136k
    return read_bytes_lock_held(self, n);
627
136k
}
628
629
/*[clinic input]
630
@critical_section
631
_io.BytesIO.readlines
632
    size as arg: object = None
633
    /
634
635
List of bytes objects, each a line from the file.
636
637
Call readline() repeatedly and return a list of the lines so read.
638
The optional size argument, if given, is an approximate bound on the
639
total number of bytes in the lines returned.
640
[clinic start generated code]*/
641
642
static PyObject *
643
_io_BytesIO_readlines_impl(bytesio *self, PyObject *arg)
644
/*[clinic end generated code: output=09b8e34c880808ff input=5c57d7d78e409985]*/
645
0
{
646
0
    Py_ssize_t maxsize, size, n;
647
0
    PyObject *result, *line;
648
0
    const char *output;
649
650
0
    CHECK_CLOSED(self);
651
652
0
    if (PyLong_Check(arg)) {
653
0
        maxsize = PyLong_AsSsize_t(arg);
654
0
        if (maxsize == -1 && PyErr_Occurred())
655
0
            return NULL;
656
0
    }
657
0
    else if (arg == Py_None) {
658
        /* No size limit, by default. */
659
0
        maxsize = -1;
660
0
    }
661
0
    else {
662
0
        PyErr_Format(PyExc_TypeError, "integer argument expected, got '%s'",
663
0
                     Py_TYPE(arg)->tp_name);
664
0
        return NULL;
665
0
    }
666
667
0
    size = 0;
668
0
    result = PyList_New(0);
669
0
    if (!result)
670
0
        return NULL;
671
672
0
    output = PyBytes_AS_STRING(self->buf) + self->pos;
673
0
    while ((n = scan_eol_lock_held(self, -1)) != 0) {
674
0
        self->pos += n;
675
0
        line = PyBytes_FromStringAndSize(output, n);
676
0
        if (!line)
677
0
            goto on_error;
678
0
        if (_PyList_AppendTakeRef((PyListObject *)result, line) < 0) {
679
0
            goto on_error;
680
0
        }
681
0
        size += n;
682
0
        if (maxsize > 0 && size >= maxsize)
683
0
            break;
684
0
        output += n;
685
0
    }
686
0
    return result;
687
688
0
  on_error:
689
0
    Py_DECREF(result);
690
0
    return NULL;
691
0
}
692
693
/*[clinic input]
694
@critical_section
695
_io.BytesIO.readinto
696
    buffer: Py_buffer(accept={rwbuffer})
697
    /
698
699
Read bytes into buffer.
700
701
Returns number of bytes read (0 for EOF), or None if the object
702
is set not to block and has no data to read.
703
[clinic start generated code]*/
704
705
static PyObject *
706
_io_BytesIO_readinto_impl(bytesio *self, Py_buffer *buffer)
707
/*[clinic end generated code: output=a5d407217dcf0639 input=093a8d330de3fcd1]*/
708
0
{
709
0
    Py_ssize_t len, n;
710
711
0
    CHECK_CLOSED(self);
712
713
    /* adjust invalid sizes */
714
0
    len = buffer->len;
715
0
    n = self->string_size - self->pos;
716
0
    if (len > n) {
717
0
        len = n;
718
0
        if (len < 0) {
719
            /* gh-141311: Avoid undefined behavior when self->pos (limit
720
               PY_SSIZE_T_MAX) points beyond the size of self->buf. */
721
0
            return PyLong_FromSsize_t(0);
722
0
        }
723
0
    }
724
725
0
    assert(self->pos + len <= PY_SSIZE_T_MAX);
726
0
    assert(len >= 0);
727
0
    memmove(buffer->buf, PyBytes_AS_STRING(self->buf) + self->pos, len);
728
0
    self->pos += len;
729
730
0
    return PyLong_FromSsize_t(len);
731
0
}
732
733
/*[clinic input]
734
@critical_section
735
_io.BytesIO.truncate
736
    size: object = None
737
    /
738
739
Truncate the file to at most size bytes.
740
741
Size defaults to the current file position, as returned by tell().
742
The current file position is unchanged.  Returns the new size.
743
[clinic start generated code]*/
744
745
static PyObject *
746
_io_BytesIO_truncate_impl(bytesio *self, PyObject *size)
747
/*[clinic end generated code: output=ab42491b4824f384 input=b4acb5f80481c053]*/
748
0
{
749
0
    CHECK_CLOSED(self);
750
0
    CHECK_EXPORTS(self);
751
752
0
    Py_ssize_t new_size;
753
754
0
    if (size == Py_None) {
755
0
        new_size = self->pos;
756
0
    }
757
0
    else {
758
0
        new_size = PyNumber_AsSsize_t(size, PyExc_OverflowError);
759
0
        if (new_size == -1 && PyErr_Occurred()) {
760
0
            return NULL;
761
0
        }
762
0
        if (new_size < 0) {
763
0
            PyErr_Format(PyExc_ValueError,
764
0
                         "negative size value %zd", new_size);
765
0
            return NULL;
766
0
        }
767
0
        CHECK_CLOSED(self);
768
0
        CHECK_EXPORTS(self);
769
0
    }
770
771
0
    if (new_size < self->string_size) {
772
0
        Py_ssize_t old_string_size = self->string_size;
773
0
        self->string_size = new_size;
774
0
        if (resize_buffer_lock_held(self, new_size) < 0) {
775
0
            self->string_size = old_string_size;
776
0
            return NULL;
777
0
        }
778
0
    }
779
780
0
    return PyLong_FromSsize_t(new_size);
781
0
}
782
783
/*[clinic input]
784
@critical_section
785
_io.BytesIO.__next__ as bytesio_iternext
786
[clinic start generated code]*/
787
788
static PyObject *
789
bytesio_iternext_impl(bytesio *self)
790
/*[clinic end generated code: output=f530bdee3a720d48 input=7fb3a763efe11a21]*/
791
0
{
792
0
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(self);
793
794
0
    Py_ssize_t n;
795
796
0
    CHECK_CLOSED(self);
797
798
0
    n = scan_eol_lock_held(self, -1);
799
800
0
    if (n == 0)
801
0
        return NULL;
802
803
0
    return read_bytes_lock_held(self, n);
804
0
}
805
806
/*[clinic input]
807
@critical_section
808
_io.BytesIO.seek
809
    pos: Py_ssize_t
810
    whence: int = 0
811
    /
812
813
Change stream position.
814
815
Seek to byte offset pos relative to position indicated by whence:
816
     0  Start of stream (the default).  pos should be >= 0;
817
     1  Current position - pos may be negative;
818
     2  End of stream - pos usually negative.
819
Returns the new absolute position.
820
[clinic start generated code]*/
821
822
static PyObject *
823
_io_BytesIO_seek_impl(bytesio *self, Py_ssize_t pos, int whence)
824
/*[clinic end generated code: output=c26204a68e9190e4 input=20f05ddf659255df]*/
825
157k
{
826
157k
    CHECK_CLOSED(self);
827
828
157k
    if (pos < 0 && whence == 0) {
829
731
        PyErr_Format(PyExc_ValueError,
830
731
                     "negative seek value %zd", pos);
831
731
        return NULL;
832
731
    }
833
834
    /* whence = 0: offset relative to beginning of the string.
835
       whence = 1: offset relative to current position.
836
       whence = 2: offset relative the end of the string. */
837
156k
    if (whence == 1) {
838
3.46k
        if (pos > PY_SSIZE_T_MAX - self->pos) {
839
0
            PyErr_SetString(PyExc_OverflowError,
840
0
                            "new position too large");
841
0
            return NULL;
842
0
        }
843
3.46k
        pos += self->pos;
844
3.46k
    }
845
153k
    else if (whence == 2) {
846
20.7k
        if (pos > PY_SSIZE_T_MAX - self->string_size) {
847
0
            PyErr_SetString(PyExc_OverflowError,
848
0
                            "new position too large");
849
0
            return NULL;
850
0
        }
851
20.7k
        pos += self->string_size;
852
20.7k
    }
853
132k
    else if (whence != 0) {
854
0
        PyErr_Format(PyExc_ValueError,
855
0
                     "invalid whence (%i, should be 0, 1 or 2)", whence);
856
0
        return NULL;
857
0
    }
858
859
156k
    if (pos < 0)
860
1.86k
        pos = 0;
861
156k
    self->pos = pos;
862
863
156k
    return PyLong_FromSsize_t(self->pos);
864
156k
}
865
866
/*[clinic input]
867
@critical_section
868
_io.BytesIO.write
869
    b: object
870
    /
871
872
Write bytes to file.
873
874
Return the number of bytes written.
875
[clinic start generated code]*/
876
877
static PyObject *
878
_io_BytesIO_write_impl(bytesio *self, PyObject *b)
879
/*[clinic end generated code: output=d3e46bcec8d9e21c input=46c0c17eac7474a4]*/
880
15.9k
{
881
15.9k
    Py_ssize_t n = write_bytes_lock_held(self, b);
882
15.9k
    return n >= 0 ? PyLong_FromSsize_t(n) : NULL;
883
15.9k
}
884
885
/*[clinic input]
886
@critical_section
887
_io.BytesIO.writelines
888
    lines: object
889
    /
890
891
Write lines to the file.
892
893
Note that newlines are not added.  lines can be any iterable object
894
producing bytes-like objects.  This is equivalent to calling write()
895
for each element.
896
[clinic start generated code]*/
897
898
static PyObject *
899
_io_BytesIO_writelines_impl(bytesio *self, PyObject *lines)
900
/*[clinic end generated code: output=03a43a75773bc397 input=d265f76533b058e7]*/
901
0
{
902
0
    PyObject *it, *item;
903
904
0
    CHECK_CLOSED(self);
905
906
0
    it = PyObject_GetIter(lines);
907
0
    if (it == NULL)
908
0
        return NULL;
909
910
0
    while ((item = PyIter_Next(it)) != NULL) {
911
0
        Py_ssize_t ret = write_bytes_lock_held(self, item);
912
0
        Py_DECREF(item);
913
0
        if (ret < 0) {
914
0
            Py_DECREF(it);
915
0
            return NULL;
916
0
        }
917
0
    }
918
0
    Py_DECREF(it);
919
920
    /* See if PyIter_Next failed */
921
0
    if (PyErr_Occurred())
922
0
        return NULL;
923
924
0
    Py_RETURN_NONE;
925
0
}
926
927
/*[clinic input]
928
@critical_section
929
_io.BytesIO.close
930
931
Disable all I/O operations.
932
[clinic start generated code]*/
933
934
static PyObject *
935
_io_BytesIO_close_impl(bytesio *self)
936
/*[clinic end generated code: output=1471bb9411af84a0 input=34ce76d8bd17a23b]*/
937
10.1k
{
938
    /* The exported buffers keep the internal buffer alive. */
939
10.1k
    Py_CLEAR(self->buf);
940
10.1k
    Py_RETURN_NONE;
941
10.1k
}
942
943
/* Pickling support.
944
945
   Note that only pickle protocol 2 and onward are supported since we use
946
   extended __reduce__ API of PEP 307 to make BytesIO instances picklable.
947
948
   Providing support for protocol < 2 would require the __reduce_ex__ method
949
   which is notably long-winded when defined properly.
950
951
   For BytesIO, the implementation would similar to one coded for
952
   object.__reduce_ex__, but slightly less general. To be more specific, we
953
   could call bytesio_getstate directly and avoid checking for the presence of
954
   a fallback __reduce__ method. However, we would still need a __newobj__
955
   function to use the efficient instance representation of PEP 307.
956
 */
957
958
959
/*[clinic input]
960
@critical_section
961
_io.BytesIO.__getstate__
962
[clinic start generated code]*/
963
964
static PyObject *
965
_io_BytesIO___getstate___impl(bytesio *self)
966
/*[clinic end generated code: output=4a776270c8443b85 input=f41e5bc9731475c4]*/
967
0
{
968
0
    PyObject *initvalue = _io_BytesIO_getvalue_impl(self);
969
0
    PyObject *dict;
970
0
    PyObject *state;
971
972
0
    if (initvalue == NULL)
973
0
        return NULL;
974
0
    if (_PyObject_IsInstanceDictEmpty((PyObject *)self)) {
975
0
        dict = Py_NewRef(Py_None);
976
0
    }
977
0
    else {
978
0
        dict = PyObject_GenericGetDict((PyObject *)self, NULL);
979
0
        if (dict == NULL) {
980
0
            Py_DECREF(initvalue);
981
0
            return NULL;
982
0
        }
983
0
        Py_SETREF(dict, PyDict_Copy(dict));
984
0
        if (dict == NULL) {
985
0
            Py_DECREF(initvalue);
986
0
            return NULL;
987
0
        }
988
0
    }
989
990
0
    state = Py_BuildValue("(OnN)", initvalue, self->pos, dict);
991
0
    Py_DECREF(initvalue);
992
0
    return state;
993
0
}
994
995
996
/*[clinic input]
997
@critical_section
998
_io.BytesIO.__setstate__
999
1000
    state: object
1001
    /
1002
[clinic start generated code]*/
1003
1004
static PyObject *
1005
_io_BytesIO___setstate___impl(bytesio *self, PyObject *state)
1006
/*[clinic end generated code: output=3605abdec171bb98 input=82a189599ba75083]*/
1007
0
{
1008
0
    PyObject *result;
1009
0
    PyObject *position_obj;
1010
0
    PyObject *dict;
1011
0
    Py_ssize_t pos;
1012
1013
0
    assert(state != NULL);
1014
1015
    /* We allow the state tuple to be longer than 3, because we may need
1016
       someday to extend the object's state without breaking
1017
       backward-compatibility. */
1018
0
    if (!PyTuple_Check(state) || PyTuple_GET_SIZE(state) < 3) {
1019
0
        PyErr_Format(PyExc_TypeError,
1020
0
                     "%.200s.__setstate__ argument should be 3-tuple, got %.200s",
1021
0
                     Py_TYPE(self)->tp_name, Py_TYPE(state)->tp_name);
1022
0
        return NULL;
1023
0
    }
1024
0
    CHECK_EXPORTS(self);
1025
    /* Reset the object to its default state. This is only needed to handle
1026
       the case of repeated calls to __setstate__. */
1027
0
    self->string_size = 0;
1028
0
    self->pos = 0;
1029
1030
    /* Set the value of the internal buffer. If state[0] does not support the
1031
       buffer protocol, bytesio_write will raise the appropriate TypeError. */
1032
0
    result = _io_BytesIO_write_impl(self, PyTuple_GET_ITEM(state, 0));
1033
0
    if (result == NULL)
1034
0
        return NULL;
1035
0
    Py_DECREF(result);
1036
1037
    /* Set carefully the position value. Alternatively, we could use the seek
1038
       method instead of modifying self->pos directly to better protect the
1039
       object internal state against erroneous (or malicious) inputs. */
1040
0
    position_obj = PyTuple_GET_ITEM(state, 1);
1041
0
    if (!PyLong_Check(position_obj)) {
1042
0
        PyErr_Format(PyExc_TypeError,
1043
0
                     "second item of state must be an integer, not %.200s",
1044
0
                     Py_TYPE(position_obj)->tp_name);
1045
0
        return NULL;
1046
0
    }
1047
0
    pos = PyLong_AsSsize_t(position_obj);
1048
0
    if (pos == -1 && PyErr_Occurred())
1049
0
        return NULL;
1050
0
    if (pos < 0) {
1051
0
        PyErr_SetString(PyExc_ValueError,
1052
0
                        "position value cannot be negative");
1053
0
        return NULL;
1054
0
    }
1055
0
    self->pos = pos;
1056
1057
    /* Set the dictionary of the instance variables. */
1058
0
    dict = PyTuple_GET_ITEM(state, 2);
1059
0
    if (dict != Py_None) {
1060
0
        if (!PyDict_Check(dict)) {
1061
0
            PyErr_Format(PyExc_TypeError,
1062
0
                         "third item of state should be a dict, got a %.200s",
1063
0
                         Py_TYPE(dict)->tp_name);
1064
0
            return NULL;
1065
0
        }
1066
        /* Alternatively, we could replace the internal dictionary
1067
           completely. However, it seems more practical to just update it. */
1068
0
        PyObject *self_dict = PyObject_GenericGetDict((PyObject *)self, NULL);
1069
0
        if (self_dict == NULL) {
1070
0
            return NULL;
1071
0
        }
1072
0
        int rc = PyDict_Update(self_dict, dict);
1073
0
        Py_DECREF(self_dict);
1074
0
        if (rc < 0) {
1075
0
            return NULL;
1076
0
        }
1077
0
    }
1078
1079
0
    Py_RETURN_NONE;
1080
0
}
1081
1082
static void
1083
bytesio_dealloc(PyObject *op)
1084
58.8k
{
1085
58.8k
    bytesio *self = bytesio_CAST(op);
1086
58.8k
    PyTypeObject *tp = Py_TYPE(self);
1087
58.8k
    _PyObject_GC_UNTRACK(self);
1088
58.8k
    if (FT_ATOMIC_LOAD_SSIZE_RELAXED(self->exports) > 0) {
1089
0
        PyErr_SetString(PyExc_SystemError,
1090
0
                        "deallocated BytesIO object has exported buffers");
1091
0
        PyErr_Print();
1092
0
    }
1093
58.8k
    Py_CLEAR(self->buf);
1094
58.8k
    PyObject_ClearManagedDict(op);
1095
58.8k
    PyObject_ClearWeakRefs(op);
1096
58.8k
    tp->tp_free(self);
1097
58.8k
    Py_DECREF(tp);
1098
58.8k
}
1099
1100
static PyObject *
1101
bytesio_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1102
58.8k
{
1103
58.8k
    bytesio *self;
1104
1105
58.8k
    assert(type != NULL && type->tp_alloc != NULL);
1106
58.8k
    self = (bytesio *)type->tp_alloc(type, 0);
1107
58.8k
    if (self == NULL)
1108
0
        return NULL;
1109
1110
    /* tp_alloc initializes all the fields to zero. So we don't have to
1111
       initialize them here. */
1112
1113
58.8k
    self->buf = Py_GetConstant(Py_CONSTANT_EMPTY_BYTES);
1114
58.8k
    if (self->buf == NULL) {
1115
0
        Py_DECREF(self);
1116
0
        return PyErr_NoMemory();
1117
0
    }
1118
1119
58.8k
    return (PyObject *)self;
1120
58.8k
}
1121
1122
/*[clinic input]
1123
@vectorcall
1124
@critical_section
1125
_io.BytesIO.__init__
1126
    initial_bytes as initvalue: object(c_default="NULL") = b''
1127
1128
Buffered I/O implementation using an in-memory bytes buffer.
1129
[clinic start generated code]*/
1130
1131
static int
1132
_io_BytesIO___init___impl(bytesio *self, PyObject *initvalue)
1133
/*[clinic end generated code: output=65c0c51e24c5b621 input=a6dc38082204df28]*/
1134
58.8k
{
1135
58.8k
    if (FT_ATOMIC_LOAD_SSIZE_RELAXED(self->exports) > 0) {
1136
0
        PyErr_SetString(PyExc_BufferError,
1137
0
                        "Existing exports of data: object cannot be re-sized");
1138
0
        return -1;
1139
0
    }
1140
1141
    /* In case, __init__ is called multiple times. */
1142
58.8k
    self->string_size = 0;
1143
58.8k
    self->pos = 0;
1144
1145
58.8k
    if (initvalue && initvalue != Py_None) {
1146
54.7k
        if (PyBytes_CheckExact(initvalue)) {
1147
54.7k
            Py_XSETREF(self->buf, Py_NewRef(initvalue));
1148
54.7k
            clear_shared_buf(self);
1149
54.7k
            self->string_size = PyBytes_GET_SIZE(initvalue);
1150
54.7k
        }
1151
0
        else {
1152
0
            PyObject *res;
1153
0
            res = _io_BytesIO_write_impl(self, initvalue);
1154
0
            if (res == NULL)
1155
0
                return -1;
1156
0
            Py_DECREF(res);
1157
0
            self->pos = 0;
1158
0
        }
1159
54.7k
    }
1160
1161
58.8k
    return 0;
1162
58.8k
}
1163
1164
1165
/*[clinic input]
1166
@critical_section
1167
_io.BytesIO.__sizeof__
1168
1169
Size of object in memory, in bytes.
1170
[clinic start generated code]*/
1171
1172
static PyObject *
1173
_io_BytesIO___sizeof___impl(bytesio *self)
1174
/*[clinic end generated code: output=f61b601bd055c4de input=6f01c36e6ff64c17]*/
1175
0
{
1176
0
    size_t res = _PyObject_SIZE(Py_TYPE(self));
1177
0
    if (self->buf && !SHARED_BUF(self)) {
1178
0
        size_t s = _PySys_GetSizeOf(self->buf);
1179
0
        if (s == (size_t)-1) {
1180
0
            return NULL;
1181
0
        }
1182
0
        res += s;
1183
0
    }
1184
0
    return PyLong_FromSize_t(res);
1185
0
}
1186
1187
static int
1188
bytesio_traverse(PyObject *op, visitproc visit, void *arg)
1189
8.48k
{
1190
8.48k
    bytesio *self = bytesio_CAST(op);
1191
8.48k
    Py_VISIT(Py_TYPE(self));
1192
8.48k
    Py_VISIT(self->buf);
1193
8.48k
    return PyObject_VisitManagedDict(op, visit, arg);
1194
8.48k
}
1195
1196
static int
1197
bytesio_clear(PyObject *op)
1198
0
{
1199
0
    bytesio *self = bytesio_CAST(op);
1200
0
    PyObject_ClearManagedDict(op);
1201
0
    if (FT_ATOMIC_LOAD_SSIZE_RELAXED(self->exports) == 0) {
1202
0
        Py_CLEAR(self->buf);
1203
0
    }
1204
0
    return 0;
1205
0
}
1206
1207
1208
#define clinic_state() (find_io_state_by_def(Py_TYPE(self)))
1209
#include "clinic/bytesio.c.h"
1210
#undef clinic_state
1211
1212
static PyGetSetDef bytesio_getsetlist[] = {
1213
    _IO_BYTESIO_CLOSED_GETSETDEF
1214
    {NULL},            /* sentinel */
1215
};
1216
1217
static struct PyMethodDef bytesio_methods[] = {
1218
    _IO_BYTESIO_READABLE_METHODDEF
1219
    _IO_BYTESIO_SEEKABLE_METHODDEF
1220
    _IO_BYTESIO_WRITABLE_METHODDEF
1221
    _IO_BYTESIO_CLOSE_METHODDEF
1222
    _IO_BYTESIO_FLUSH_METHODDEF
1223
    _IO_BYTESIO_ISATTY_METHODDEF
1224
    _IO_BYTESIO_TELL_METHODDEF
1225
    _IO_BYTESIO_WRITE_METHODDEF
1226
    _IO_BYTESIO_WRITELINES_METHODDEF
1227
    _IO_BYTESIO_READ1_METHODDEF
1228
    _IO_BYTESIO_READINTO_METHODDEF
1229
    _IO_BYTESIO_READLINE_METHODDEF
1230
    _IO_BYTESIO_READLINES_METHODDEF
1231
    _IO_BYTESIO_READ_METHODDEF
1232
    _IO_BYTESIO_PEEK_METHODDEF
1233
    _IO_BYTESIO_GETBUFFER_METHODDEF
1234
    _IO_BYTESIO_GETVALUE_METHODDEF
1235
    _IO_BYTESIO_SEEK_METHODDEF
1236
    _IO_BYTESIO_TRUNCATE_METHODDEF
1237
    _IO_BYTESIO___GETSTATE___METHODDEF
1238
    _IO_BYTESIO___SETSTATE___METHODDEF
1239
    _IO_BYTESIO___SIZEOF___METHODDEF
1240
    {NULL, NULL}        /* sentinel */
1241
};
1242
1243
static PyType_Slot bytesio_slots[] = {
1244
    {Py_tp_dealloc, bytesio_dealloc},
1245
    {Py_tp_doc, (void *)_io_BytesIO___init____doc__},
1246
    {Py_tp_traverse, bytesio_traverse},
1247
    {Py_tp_clear, bytesio_clear},
1248
    {Py_tp_iter, PyObject_SelfIter},
1249
    {Py_tp_iternext, bytesio_iternext},
1250
    {Py_tp_methods, bytesio_methods},
1251
    {Py_tp_getset, bytesio_getsetlist},
1252
    {Py_tp_init, _io_BytesIO___init__},
1253
    {Py_tp_new, bytesio_new},
1254
    {Py_tp_vectorcall, _io_BytesIO_vectorcall},
1255
    {0, NULL},
1256
};
1257
1258
PyType_Spec _Py_bytesio_spec = {
1259
    .name = "_io.BytesIO",
1260
    .basicsize = sizeof(bytesio),
1261
    .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
1262
              Py_TPFLAGS_IMMUTABLETYPE),
1263
    .slots = bytesio_slots,
1264
};
1265
1266
/*
1267
 * Implementation of the small intermediate object used by getbuffer().
1268
 * getbuffer() returns a memoryview over this object, which should make it
1269
 * invisible from Python code.
1270
 */
1271
1272
static int
1273
bytesiobuf_getbuffer_lock_held(PyObject *op, Py_buffer *view, int flags)
1274
0
{
1275
0
    bytesiobuf *obj = bytesiobuf_CAST(op);
1276
0
    bytesio *b = bytesio_CAST(obj->source);
1277
1278
0
    _Py_CRITICAL_SECTION_ASSERT_OBJECT_LOCKED(b);
1279
1280
0
    if (check_closed(b)) {
1281
0
        return -1;
1282
0
    }
1283
0
    if (FT_ATOMIC_LOAD_SSIZE_RELAXED(b->exports) == 0 && SHARED_BUF(b)) {
1284
0
        if (unshare_buffer_lock_held(b, b->string_size) < 0)
1285
0
            return -1;
1286
0
    }
1287
1288
    /* cannot fail if view != NULL and readonly == 0 */
1289
0
    (void)PyBuffer_FillInfo(view, op,
1290
0
                            PyBytes_AS_STRING(b->buf), b->string_size,
1291
0
                            0, flags);
1292
    /* Keep the internal buffer alive: the bytesio object can be closed
1293
       while the buffer is exported. */
1294
0
    view->internal = Py_NewRef(b->buf);
1295
0
    FT_ATOMIC_ADD_SSIZE(b->exports, 1);
1296
0
    return 0;
1297
0
}
1298
1299
static int
1300
bytesiobuf_getbuffer(PyObject *op, Py_buffer *view, int flags)
1301
0
{
1302
0
    if (view == NULL) {
1303
0
        PyErr_SetString(PyExc_BufferError,
1304
0
            "bytesiobuf_getbuffer: view==NULL argument is obsolete");
1305
0
        return -1;
1306
0
    }
1307
1308
0
    int ret;
1309
0
    Py_BEGIN_CRITICAL_SECTION(bytesiobuf_CAST(op)->source);
1310
0
    ret = bytesiobuf_getbuffer_lock_held(op, view, flags);
1311
0
    Py_END_CRITICAL_SECTION();
1312
0
    return ret;
1313
0
}
1314
1315
static void
1316
bytesiobuf_releasebuffer(PyObject *op, Py_buffer *view)
1317
0
{
1318
0
    bytesiobuf *obj = bytesiobuf_CAST(op);
1319
0
    bytesio *b = bytesio_CAST(obj->source);
1320
0
    FT_ATOMIC_ADD_SSIZE(b->exports, -1);
1321
0
    Py_CLEAR(view->internal);
1322
0
}
1323
1324
static int
1325
bytesiobuf_traverse(PyObject *op, visitproc visit, void *arg)
1326
0
{
1327
0
    bytesiobuf *self = bytesiobuf_CAST(op);
1328
0
    Py_VISIT(Py_TYPE(self));
1329
0
    Py_VISIT(self->source);
1330
0
    return 0;
1331
0
}
1332
1333
static void
1334
bytesiobuf_dealloc(PyObject *op)
1335
0
{
1336
0
    bytesiobuf *self = bytesiobuf_CAST(op);
1337
0
    PyTypeObject *tp = Py_TYPE(self);
1338
    /* bpo-31095: UnTrack is needed before calling any callbacks */
1339
0
    PyObject_GC_UnTrack(op);
1340
0
    Py_CLEAR(self->source);
1341
0
    tp->tp_free(self);
1342
0
    Py_DECREF(tp);
1343
0
}
1344
1345
static PyType_Slot bytesiobuf_slots[] = {
1346
    {Py_tp_dealloc, bytesiobuf_dealloc},
1347
    {Py_tp_traverse, bytesiobuf_traverse},
1348
1349
    // Buffer protocol
1350
    {Py_bf_getbuffer, bytesiobuf_getbuffer},
1351
    {Py_bf_releasebuffer, bytesiobuf_releasebuffer},
1352
    {0, NULL},
1353
};
1354
1355
PyType_Spec _Py_bytesiobuf_spec = {
1356
    .name = "_io._BytesIOBuffer",
1357
    .basicsize = sizeof(bytesiobuf),
1358
    .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
1359
              Py_TPFLAGS_IMMUTABLETYPE | Py_TPFLAGS_DISALLOW_INSTANTIATION),
1360
    .slots = bytesiobuf_slots,
1361
};