Coverage Report

Created: 2026-10-17 06:15

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Python/marshal.c
Line
Count
Source
1
2
/* Write Python objects to files and read them back.
3
   This is primarily intended for writing and reading compiled Python code,
4
   even though dicts and frozendicts, lists, sets and frozensets,
5
   not commonly seen in code objects, are supported.
6
   Version 3 of this protocol properly supports circular links
7
   and sharing. */
8
9
#include "Python.h"
10
#include "pycore_call.h"             // _PyObject_CallNoArgs()
11
#include "pycore_code.h"             // _PyCode_New()
12
#include "pycore_hashtable.h"        // _Py_hashtable_t
13
#include "pycore_long.h"             // _PyLong_IsZero()
14
#include "pycore_object.h"           // _PyObject_IsUniquelyReferenced
15
#include "pycore_pystate.h"          // _PyInterpreterState_GET()
16
#include "pycore_setobject.h"        // _PySet_NextEntryRef()
17
#include "pycore_tuple.h"            // _PyTuple_FromPairSteal
18
#include "pycore_unicodeobject.h"    // _PyUnicode_InternImmortal()
19
20
#include "marshal.h"                 // Py_MARSHAL_VERSION
21
22
#ifdef __APPLE__
23
#  include "TargetConditionals.h"
24
#endif /* __APPLE__ */
25
26
27
/*[clinic input]
28
module marshal
29
[clinic start generated code]*/
30
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=c982b7930dee17db]*/
31
32
#include "clinic/marshal.c.h"
33
34
/* High water mark to determine when the marshalled object is dangerously deep
35
 * and risks coring the interpreter.  When the object stack gets this deep,
36
 * raise an exception instead of continuing.
37
 * On Windows debug builds, reduce this value.
38
 *
39
 * BUG: https://bugs.python.org/issue33720
40
 * On Windows PGO builds, the r_object function overallocates its stack and
41
 * can cause a stack overflow. We reduce the maximum depth for all Windows
42
 * releases to protect against this.
43
 * #if defined(MS_WINDOWS) && defined(Py_DEBUG)
44
 */
45
#if defined(MS_WINDOWS)
46
#  define MAX_MARSHAL_STACK_DEPTH 1000
47
#elif defined(__wasm__)
48
#  define MAX_MARSHAL_STACK_DEPTH 1500
49
// TARGET_OS_IPHONE covers any non-macOS Apple platform.
50
// It won't be defined on older macOS SDKs
51
#elif defined(__APPLE__) && defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
52
#  define MAX_MARSHAL_STACK_DEPTH 1500
53
#else
54
4.15M
#  define MAX_MARSHAL_STACK_DEPTH 2000
55
#endif
56
57
/* Supported types */
58
0
#define TYPE_NULL               '0'
59
36.5k
#define TYPE_NONE               'N'
60
1.92k
#define TYPE_FALSE              'F'
61
1.72k
#define TYPE_TRUE               'T'
62
0
#define TYPE_STOPITER           'S'
63
446
#define TYPE_ELLIPSIS           '.'
64
608
#define TYPE_BINARY_FLOAT       'g'  // Version 0 uses TYPE_FLOAT instead.
65
3
#define TYPE_BINARY_COMPLEX     'y'  // Version 0 uses TYPE_COMPLEX instead.
66
444
#define TYPE_LONG               'l'  // See also TYPE_INT.
67
484k
#define TYPE_STRING             's'  // Bytes. (Name comes from Python 2.)
68
70
#define TYPE_TUPLE              '('  // See also TYPE_SMALL_TUPLE.
69
0
#define TYPE_LIST               '['
70
0
#define TYPE_DICT               '{'
71
0
#define TYPE_FROZENDICT         '}'
72
160k
#define TYPE_CODE               'c'
73
3.58k
#define TYPE_UNICODE            'u'
74
#define TYPE_UNKNOWN            '?'
75
// added in version 2:
76
1.37k
#define TYPE_SET                '<'
77
459
#define TYPE_FROZENSET          '>'
78
// added in version 5:
79
3.31k
#define TYPE_SLICE              ':'
80
// Remember to update the version and documentation when adding new types.
81
82
/* Special cases for unicode strings (added in version 4) */
83
105
#define TYPE_INTERNED           't' // Version 1+
84
24.2k
#define TYPE_ASCII              'a'
85
0
#define TYPE_ASCII_INTERNED     'A'
86
1.17M
#define TYPE_SHORT_ASCII        'z'
87
1.02M
#define TYPE_SHORT_ASCII_INTERNED 'Z'
88
89
/* Special cases for small objects */
90
25.4k
#define TYPE_INT                'i'  // All versions. 32-bit encoding.
91
425k
#define TYPE_SMALL_TUPLE        ')'  // Version 4+
92
93
/* Supported for backwards compatibility */
94
0
#define TYPE_COMPLEX            'x'  // Generated for version 0 only.
95
0
#define TYPE_FLOAT              'f'  // Generated for version 0 only.
96
0
#define TYPE_INT64              'I'  // Not generated any more.
97
98
/* References (added in version 3) */
99
1.78M
#define TYPE_REF                'r'
100
8.22M
#define FLAG_REF                '\x80' /* with a type, add obj to index */
101
102
103
/* State of an object which can be the target of a TYPE_REF (version 3+),
104
   see w_ref() and w_resolve_refs().
105
106
   WFILE.hashtable maps the object to its index in WFILE.refs, shifted left
107
   by W_ENTRY_SHIFT bits, plus the flags:
108
   - W_ENTRY_ACTIVE: the object is being written (used to detect recursion,
109
     see w_complete());
110
   - W_ENTRY_SHARED: the object has been written more than once.
111
112
   The item of WFILE.refs is the offset of the type byte of the object in
113
   the output, shifted left by one bit, plus W_REF_SHARED if the object has
114
   been written more than once. */
115
28.7k
#define W_ENTRY_ACTIVE ((uintptr_t)1)
116
33.7k
#define W_ENTRY_SHARED ((uintptr_t)2)
117
48.1k
#define W_ENTRY_SHIFT 2
118
21.7k
#define W_REF_SHARED ((size_t)1)
119
120
/* Maximum number of items in WFILE.refs.  TYPE_REF has a signed 32-bit
121
   argument. */
122
14.3k
#define W_MAX_REFS Py_MIN((uintptr_t)0x7fffffff, UINTPTR_MAX >> W_ENTRY_SHIFT)
123
124
typedef struct {
125
    bool error;  /* An exception has been raised. */
126
    int depth;
127
    PyObject *str;
128
    char *ptr;
129
    const char *end;
130
    char *buf;
131
    _Py_hashtable_t *hashtable;     /* object -> index in refs, flags */
132
    size_t *refs;                   /* In order of the first occurrence. */
133
    size_t refs_allocated;
134
    unsigned char *refpos;          /* Where the TYPE_REFs are in the
135
                                       output, see w_add_refpos(). */
136
    size_t refpos_size;
137
    size_t refpos_allocated;
138
    size_t refpos_run;              /* Index in refpos of the length of
139
                                       the current run, or 0. */
140
    size_t refpos_end;              /* Offset of the end of the last
141
                                       TYPE_REF in the output. */
142
    int version;
143
    int allow_code;
144
} WFILE;
145
146
140k
#define w_byte(c, p) do {                               \
147
140k
        if ((p)->ptr != (p)->end || w_reserve((p), 1))  \
148
140k
            *(p)->ptr++ = (c);                          \
149
140k
    } while(0)
150
151
static int
152
w_reserve(WFILE *p, Py_ssize_t needed)
153
441
{
154
441
    Py_ssize_t pos, size, delta;
155
441
    if (p->ptr == NULL)
156
0
        return 0; /* An error already occurred */
157
441
    assert(p->str != NULL);
158
441
    pos = p->ptr - p->buf;
159
441
    size = PyBytes_GET_SIZE(p->str);
160
441
    if (size > 16*1024*1024)
161
0
        delta = (size >> 3);            /* 12.5% overallocation */
162
441
    else
163
441
        delta = size + 1024;
164
441
    delta = Py_MAX(delta, needed);
165
441
    if (delta > PY_SSIZE_T_MAX - size) {
166
0
        PyErr_NoMemory();
167
0
        p->error = true;
168
0
        return 0;
169
0
    }
170
441
    size += delta;
171
441
    if (_PyBytes_Resize(&p->str, size) != 0) {
172
0
        p->end = p->ptr = p->buf = NULL;
173
0
        p->error = true;
174
0
        return 0;
175
0
    }
176
441
    else {
177
441
        p->buf = PyBytes_AS_STRING(p->str);
178
441
        p->ptr = p->buf + pos;
179
441
        p->end = p->buf + size;
180
441
        return 1;
181
441
    }
182
441
}
183
184
static void
185
w_string(const void *s, Py_ssize_t n, WFILE *p)
186
18.4k
{
187
18.4k
    Py_ssize_t m;
188
18.4k
    if (!n || p->ptr == NULL)
189
158
        return;
190
18.2k
    m = p->end - p->ptr;
191
18.2k
    if (n <= m || w_reserve(p, n - m)) {
192
18.2k
        memcpy(p->ptr, s, n);
193
18.2k
        p->ptr += n;
194
18.2k
    }
195
18.2k
}
196
197
static void
198
w_short(int x, WFILE *p)
199
23
{
200
23
    w_byte((char)( x      & 0xff), p);
201
23
    w_byte((char)((x>> 8) & 0xff), p);
202
23
}
203
204
static void
205
w_long(long x, WFILE *p)
206
23.4k
{
207
23.4k
    w_byte((char)( x      & 0xff), p);
208
23.4k
    w_byte((char)((x>> 8) & 0xff), p);
209
23.4k
    w_byte((char)((x>>16) & 0xff), p);
210
23.4k
    w_byte((char)((x>>24) & 0xff), p);
211
23.4k
}
212
213
/* Read and write a 32-bit value in place. */
214
static inline uint32_t
215
w_get_uint32(const char *ptr)
216
26.3k
{
217
26.3k
    const unsigned char *b = (const unsigned char *)ptr;
218
26.3k
    return b[0] | (b[1] << 8) | (b[2] << 16) | ((uint32_t)b[3] << 24);
219
26.3k
}
220
221
static inline void
222
w_put_uint32(char *ptr, uint32_t x)
223
52.6k
{
224
52.6k
    ptr[0] = (char)( x      & 0xff);
225
52.6k
    ptr[1] = (char)((x>> 8) & 0xff);
226
52.6k
    ptr[2] = (char)((x>>16) & 0xff);
227
52.6k
    ptr[3] = (char)((x>>24) & 0xff);
228
52.6k
}
229
230
521k
#define SIZE32_MAX  0x7FFFFFFF
231
232
#if SIZEOF_SIZE_T > 4
233
6.88k
# define W_SIZE(n, p)  do {                                 \
234
6.88k
        if ((n) > SIZE32_MAX) {                             \
235
0
            (p)->depth--;                                   \
236
0
            PyErr_SetString(PyExc_ValueError,               \
237
0
                            "object too large to marshal"); \
238
0
            (p)->error = true;                              \
239
0
            return;                                         \
240
0
        }                                                   \
241
6.88k
        w_long((long)(n), p);                               \
242
6.88k
    } while(0)
243
#else
244
# define W_SIZE  w_long
245
#endif
246
247
static void
248
w_pstring(const void *s, Py_ssize_t n, WFILE *p)
249
6.87k
{
250
6.87k
        W_SIZE(n, p);
251
6.87k
        w_string(s, n, p);
252
6.87k
}
253
254
static void
255
w_short_pstring(const void *s, Py_ssize_t n, WFILE *p)
256
11.5k
{
257
11.5k
    w_byte(Py_SAFE_DOWNCAST(n, Py_ssize_t, unsigned char), p);
258
11.5k
    w_string(s, n, p);
259
11.5k
}
260
261
/* We assume that Python ints are stored internally in base some power of
262
   2**15; for the sake of portability we'll always read and write them in base
263
   exactly 2**15. */
264
265
3.89k
#define PyLong_MARSHAL_SHIFT 15
266
1.71k
#define PyLong_MARSHAL_BASE ((short)1 << PyLong_MARSHAL_SHIFT)
267
23
#define PyLong_MARSHAL_MASK (PyLong_MARSHAL_BASE - 1)
268
269
/* Write the type code of an object.  It must be the first byte written for
270
   an object passed to w_ref(): w_resolve_refs() adds FLAG_REF to that byte
271
   if the object turns out to be referenced more than once. */
272
28.8k
#define W_TYPE(t, p) w_byte((t), (p))
273
274
static PyObject *
275
_PyMarshal_WriteObjectToString(PyObject *x, int version, int allow_code);
276
277
#define _r_digits(bitsize)                                                \
278
static void                                                               \
279
_r_digits##bitsize(const uint ## bitsize ## _t *digits, Py_ssize_t n,     \
280
3
                   uint8_t negative, Py_ssize_t marshal_ratio, WFILE *p)  \
281
3
{                                                                         \
282
3
    /* set l to number of base PyLong_MARSHAL_BASE digits */              \
283
3
    Py_ssize_t l = (n - 1)*marshal_ratio;                                 \
284
3
    uint ## bitsize ## _t d = digits[n - 1];                              \
285
3
                                                                          \
286
3
    assert(marshal_ratio > 0);                                            \
287
3
    assert(n >= 1);                                                       \
288
3
    assert(d != 0); /* a PyLong is always normalized */                   \
289
3
    do {                                                                  \
290
3
        d >>= PyLong_MARSHAL_SHIFT;                                       \
291
3
        l++;                                                              \
292
3
    } while (d != 0);                                                     \
293
3
    if (l > SIZE32_MAX) {                                                 \
294
0
        p->depth--;                                                       \
295
0
        PyErr_SetString(PyExc_ValueError, "int too large to marshal");    \
296
0
        p->error = true;                                                  \
297
0
        return;                                                           \
298
0
    }                                                                     \
299
3
    w_long((long)(negative ? -l : l), p);                                 \
300
3
                                                                          \
301
9
    for (Py_ssize_t i = 0; i < n - 1; i++) {                              \
302
6
        d = digits[i];                                                    \
303
18
        for (Py_ssize_t j = 0; j < marshal_ratio; j++) {                  \
304
12
            w_short(d & PyLong_MARSHAL_MASK, p);                          \
305
12
            d >>= PyLong_MARSHAL_SHIFT;                                   \
306
12
        }                                                                 \
307
6
        assert(d == 0);                                                   \
308
6
    }                                                                     \
309
3
    d = digits[n - 1];                                                    \
310
3
    do {                                                                  \
311
3
        w_short(d & PyLong_MARSHAL_MASK, p);                              \
312
3
        d >>= PyLong_MARSHAL_SHIFT;                                       \
313
3
    } while (d != 0);                                                     \
314
3
}
315
0
_r_digits(16)
316
3
_r_digits(32)
317
#undef _r_digits
318
319
static void
320
w_PyLong(const PyLongObject *ob, WFILE *p)
321
5
{
322
5
    W_TYPE(TYPE_LONG, p);
323
5
    if (_PyLong_IsZero(ob)) {
324
0
        w_long((long)0, p);
325
0
        return;
326
0
    }
327
328
5
    PyLongExport long_export;
329
330
5
    if (PyLong_Export((PyObject *)ob, &long_export) < 0) {
331
0
        p->depth--;
332
0
        p->error = true;
333
0
        return;
334
0
    }
335
5
    if (!long_export.digits) {
336
2
        int8_t sign = long_export.value < 0 ? -1 : 1;
337
2
        uint64_t abs_value = _Py_ABS_CAST(uint64_t, long_export.value);
338
2
        uint64_t d = abs_value;
339
2
        long l = 0;
340
341
        /* set l to number of base PyLong_MARSHAL_BASE digits */
342
8
        do {
343
8
            d >>= PyLong_MARSHAL_SHIFT;
344
8
            l += sign;
345
8
        } while (d);
346
2
        w_long(l, p);
347
348
2
        d = abs_value;
349
8
        do {
350
8
            w_short(d & PyLong_MARSHAL_MASK, p);
351
8
            d >>= PyLong_MARSHAL_SHIFT;
352
8
        } while (d);
353
2
        return;
354
2
    }
355
356
3
    const PyLongLayout *layout = PyLong_GetNativeLayout();
357
3
    Py_ssize_t marshal_ratio = layout->bits_per_digit/PyLong_MARSHAL_SHIFT;
358
359
    /* must be a multiple of PyLong_MARSHAL_SHIFT */
360
3
    assert(layout->bits_per_digit % PyLong_MARSHAL_SHIFT == 0);
361
3
    assert(layout->bits_per_digit >= PyLong_MARSHAL_SHIFT);
362
363
    /* other assumptions on PyLongObject internals */
364
3
    assert(layout->bits_per_digit <= 32);
365
3
    assert(layout->digits_order == -1);
366
3
    assert(layout->digit_endianness == (PY_LITTLE_ENDIAN ? -1 : 1));
367
3
    assert(layout->digit_size == 2 || layout->digit_size == 4);
368
369
3
    if (layout->digit_size == 4) {
370
3
        _r_digits32(long_export.digits, long_export.ndigits,
371
3
                    long_export.negative, marshal_ratio, p);
372
3
    }
373
0
    else {
374
0
        _r_digits16(long_export.digits, long_export.ndigits,
375
0
                    long_export.negative, marshal_ratio, p);
376
0
    }
377
3
    PyLong_FreeExport(&long_export);
378
3
}
379
380
static void
381
w_float_bin(double v, WFILE *p)
382
10
{
383
10
    char buf[8];
384
10
    if (PyFloat_Pack8(v, buf, 1) < 0) {
385
0
        p->error = true;
386
0
        return;
387
0
    }
388
10
    w_string(buf, 8, p);
389
10
}
390
391
static void
392
w_float_str(double v, WFILE *p)
393
0
{
394
0
    char *buf = PyOS_double_to_string(v, 'g', 17, 0, NULL);
395
0
    if (!buf) {
396
0
        p->error = true;
397
0
        return;
398
0
    }
399
0
    w_short_pstring(buf, strlen(buf), p);
400
0
    PyMem_Free(buf);
401
0
}
402
403
/* Make room for one more item in a dynamic array of n items.
404
   Return the array, which may have moved, or NULL on memory error. */
405
static void *
406
w_array_grow(void *items, size_t n, size_t *allocated, size_t itemsize)
407
29.9k
{
408
29.9k
    if (n < *allocated) {
409
28.6k
        return items;
410
28.6k
    }
411
1.24k
    size_t new_allocated = *allocated ? *allocated * 2 : 16;
412
1.24k
    if (new_allocated > (size_t)PY_SSIZE_T_MAX / itemsize) {
413
0
        return NULL;
414
0
    }
415
1.24k
    items = PyMem_Realloc(items, new_allocated * itemsize);
416
1.24k
    if (items != NULL) {
417
1.24k
        *allocated = new_allocated;
418
1.24k
    }
419
1.24k
    return items;
420
1.24k
}
421
422
/* Remember that a TYPE_REF is being written at the current end of the
423
   output.  Return 0 on memory error.
424
425
   p->refpos lists the TYPE_REFs in the order of the output, as a sequence
426
   of items which start with the byte:
427
   - 1 to 254: a TYPE_REF follows that number of other bytes of output;
428
   - 255, followed by a size_t: the same for a larger number of bytes;
429
   - 0, followed by a byte n: n more TYPE_REFs directly follow the previous
430
     one.
431
   This takes one byte for most TYPE_REFs, and much less when the output
432
   mostly consists of TYPE_REFs. */
433
static int
434
w_add_refpos(WFILE *p)
435
26.3k
{
436
26.3k
    size_t pos = (size_t)(p->ptr - p->buf);
437
26.3k
    size_t gap = pos - p->refpos_end;
438
26.3k
    p->refpos_end = pos + 5;
439
26.3k
    if (gap == 0 && p->refpos_run != 0 && p->refpos[p->refpos_run] < 255) {
440
10.8k
        p->refpos[p->refpos_run]++;
441
10.8k
        return 1;
442
10.8k
    }
443
15.5k
    unsigned char *refpos = w_array_grow(p->refpos,
444
15.5k
                                         p->refpos_size + sizeof(size_t),
445
15.5k
                                         &p->refpos_allocated, 1);
446
15.5k
    if (refpos == NULL) {
447
0
        PyErr_NoMemory();
448
0
        return 0;
449
0
    }
450
15.5k
    p->refpos = refpos;
451
15.5k
    size_t size = p->refpos_size;
452
15.5k
    if (gap == 0) {
453
5.48k
        refpos[size++] = 0;
454
5.48k
        p->refpos_run = size;
455
5.48k
        refpos[size++] = 1;
456
5.48k
    }
457
10.0k
    else {
458
10.0k
        p->refpos_run = 0;
459
10.0k
        if (gap < 255) {
460
9.09k
            refpos[size++] = (unsigned char)gap;
461
9.09k
        }
462
941
        else {
463
941
            refpos[size++] = 255;
464
941
            memcpy(refpos + size, &gap, sizeof(gap));
465
941
            size += sizeof(gap);
466
941
        }
467
10.0k
    }
468
15.5k
    p->refpos_size = size;
469
15.5k
    return 1;
470
15.5k
}
471
472
/* Object references (version 3+).
473
474
   The reader keeps a list of the objects whose type byte has FLAG_REF, in
475
   the order in which they start in the stream, and TYPE_REF refers to an
476
   object by its index in that list.
477
478
   Whether an object is flagged must only depend on the object graph being
479
   written, not on how many other references to the object happen to exist
480
   in the process, otherwise the output is not reproducible.  So an object
481
   is flagged if and only if it is written more than once.  That is not
482
   known when the object is seen for the first time, so:
483
484
   - on the first occurrence, w_ref() records the offset of the type byte
485
     (the next byte to be written, see W_TYPE) in p->refs and the object is
486
     written without FLAG_REF;
487
   - on a later occurrence, w_ref() marks the object as shared and writes
488
     a TYPE_REF whose argument is provisional: the index of the object in
489
     p->refs.  The position of the TYPE_REF is recorded in p->refpos;
490
   - once everything is written, w_resolve_refs() adds FLAG_REF to the
491
     type byte of each shared object, numbers these objects in the order
492
     of their first occurrence and fixes up the arguments of all
493
     TYPE_REFs.
494
495
   Return 1 if the object has been dealt with (TYPE_REF written or error),
496
   0 if the caller has to write it.
497
 */
498
static int
499
w_ref(PyObject *v, WFILE *p)
500
55.1k
{
501
55.1k
    _Py_hashtable_entry_t *entry;
502
503
55.1k
    if (p->version < 3 || p->hashtable == NULL)
504
0
        return 0; /* not writing object references */
505
506
    /* An object with only one reference cannot occur twice in the object
507
     * graph, so there is no need to remember it.  This is only a shortcut:
508
     * an object occurring twice has at least two references each time it is
509
     * seen, so it is never skipped and the output does not depend on this
510
     * test.
511
     */
512
55.1k
    if (_PyObject_IsUniquelyReferenced(v)) {
513
14.4k
        return 0;
514
14.4k
    }
515
516
40.7k
    entry = _Py_hashtable_get_entry(p->hashtable, v);
517
40.7k
    if (entry != NULL) {
518
        /* write the reference index to the stream */
519
26.3k
        uintptr_t w = (uintptr_t)entry->value;
520
26.3k
        if (w & W_ENTRY_ACTIVE) {
521
0
            PyErr_Format(PyExc_ValueError, "cannot marshal recursion %T objects", v);
522
0
            goto err;
523
0
        }
524
26.3k
        if (!(w & W_ENTRY_SHARED)) {
525
7.44k
            entry->value = (void *)(w | W_ENTRY_SHARED);
526
7.44k
            p->refs[w >> W_ENTRY_SHIFT] |= W_REF_SHARED;
527
7.44k
        }
528
26.3k
        w >>= W_ENTRY_SHIFT;
529
26.3k
        assert(w < p->hashtable->nentries);
530
26.3k
        if (p->end - p->ptr < 5 && !w_reserve(p, 5)) {
531
0
            return 1;
532
0
        }
533
26.3k
        if (!w_add_refpos(p)) {
534
0
            goto err;
535
0
        }
536
26.3k
        *p->ptr++ = TYPE_REF;
537
        /* The index in the reader's reference list is not known yet.
538
           Write the index in p->refs, w_resolve_refs() will replace it. */
539
26.3k
        w_put_uint32(p->ptr, (uint32_t)w);
540
26.3k
        p->ptr += 4;
541
26.3k
        return 1;
542
26.3k
    } else {
543
14.3k
        size_t w = p->hashtable->nentries;
544
        /* we don't support long indices */
545
14.3k
        if (w >= W_MAX_REFS) {
546
0
            PyErr_SetString(PyExc_ValueError, "too many objects");
547
0
            goto err;
548
0
        }
549
14.3k
        size_t *refs = w_array_grow(p->refs, w, &p->refs_allocated,
550
14.3k
                                    sizeof(*refs));
551
14.3k
        if (refs == NULL) {
552
0
            PyErr_NoMemory();
553
0
            goto err;
554
0
        }
555
14.3k
        p->refs = refs;
556
14.3k
        refs[w] = (size_t)(p->ptr - p->buf) << 1;
557
14.3k
        uintptr_t value = (uintptr_t)w << W_ENTRY_SHIFT;
558
        // Corresponding code should call w_complete() after
559
        // writing the object.
560
14.3k
        if (PyTuple_CheckExact(v) || PyCode_Check(v) || PySlice_Check(v) ||
561
13.1k
            PyFrozenDict_CheckExact(v))
562
1.19k
        {
563
1.19k
            value |= W_ENTRY_ACTIVE;
564
1.19k
        }
565
14.3k
        if (_Py_hashtable_set(p->hashtable, Py_NewRef(v),
566
14.3k
                              (void *)value) < 0) {
567
0
            Py_DECREF(v);
568
0
            PyErr_NoMemory();
569
0
            goto err;
570
0
        }
571
14.3k
        return 0;
572
14.3k
    }
573
0
err:
574
0
    p->error = true;
575
0
    return 1;
576
40.7k
}
577
578
/* Finish the output: flag the objects which are the target of a TYPE_REF
579
   and replace the provisional argument of each TYPE_REF.  See w_ref(). */
580
static void
581
w_resolve_refs(WFILE *p)
582
215
{
583
215
    if (p->error || p->refpos == NULL) {
584
75
        return;
585
75
    }
586
215
    assert(p->hashtable != NULL);
587
    /* Replace the state of each object in p->refs with its index in the
588
       reader's reference list (only used for the shared objects). */
589
140
    size_t nrefs = p->hashtable->nentries;
590
140
    size_t *refs = p->refs;
591
140
    uint32_t index = 0;
592
14.4k
    for (size_t i = 0; i < nrefs; i++) {
593
14.3k
        size_t shared = refs[i] & W_REF_SHARED;
594
14.3k
        char *type = p->buf + (refs[i] >> 1);
595
14.3k
        assert(!(*type & FLAG_REF));
596
        /* No branch on shared: it would not be predictable. */
597
14.3k
        *type |= (char)(-(int)shared & FLAG_REF);
598
14.3k
        refs[i] = index;
599
14.3k
        index += (uint32_t)shared;
600
#ifdef Py_DEBUG
601
        if (!shared) {
602
            refs[i] = (size_t)-1;
603
        }
604
#endif
605
14.3k
    }
606
140
    const unsigned char *pos = p->refpos;
607
140
    const unsigned char *end = pos + p->refpos_size;
608
140
    char *ptr = p->buf;
609
15.6k
    while (pos < end) {
610
15.5k
        size_t gap = *pos++;
611
15.5k
        size_t count = 1;
612
15.5k
        if (gap == 0) {
613
5.48k
            count = *pos++;
614
5.48k
        }
615
10.0k
        else if (gap == 255) {
616
941
            memcpy(&gap, pos, sizeof(gap));
617
941
            pos += sizeof(gap);
618
941
        }
619
15.5k
        ptr += gap;
620
26.3k
        do {
621
26.3k
            assert(ptr + 5 <= p->ptr);
622
26.3k
            assert(*ptr == TYPE_REF);
623
26.3k
            uint32_t w = w_get_uint32(ptr + 1);
624
26.3k
            assert(w < nrefs);
625
26.3k
            assert(refs[w] < index);
626
26.3k
            w_put_uint32(ptr + 1, (uint32_t)refs[w]);
627
26.3k
            ptr += 5;
628
26.3k
        } while (--count);
629
15.5k
    }
630
140
}
631
632
static void
633
w_complete(PyObject *v, WFILE *p)
634
8.28k
{
635
8.28k
    if (p->version < 3 || p->hashtable == NULL) {
636
0
        return;
637
0
    }
638
8.28k
    if (_PyObject_IsUniquelyReferenced(v)) {
639
7.09k
        return;
640
7.09k
    }
641
642
1.19k
    _Py_hashtable_entry_t *entry = _Py_hashtable_get_entry(p->hashtable, v);
643
1.19k
    if (entry == NULL) {
644
0
        return;
645
0
    }
646
1.19k
    assert(entry != NULL);
647
1.19k
    uintptr_t w = (uintptr_t)entry->value;
648
1.19k
    assert(w & W_ENTRY_ACTIVE);
649
1.19k
    w &= ~W_ENTRY_ACTIVE;
650
1.19k
    entry->value = (void *)w;
651
1.19k
}
652
653
static void
654
w_complex_object(PyObject *v, WFILE *p);
655
656
static void
657
w_object(PyObject *v, WFILE *p)
658
55.5k
{
659
55.5k
    if (p->error) {
660
0
        return;
661
0
    }
662
663
55.5k
    p->depth++;
664
665
55.5k
    if (p->depth > MAX_MARSHAL_STACK_DEPTH) {
666
0
        PyErr_SetString(PyExc_ValueError,
667
0
                        "object too deeply nested to marshal");
668
0
        p->error = true;
669
0
    }
670
55.5k
    else if (v == NULL) {
671
0
        w_byte(TYPE_NULL, p);
672
0
    }
673
55.5k
    else if (v == Py_None) {
674
281
        w_byte(TYPE_NONE, p);
675
281
    }
676
55.3k
    else if (v == PyExc_StopIteration) {
677
0
        w_byte(TYPE_STOPITER, p);
678
0
    }
679
55.3k
    else if (v == Py_Ellipsis) {
680
1
        w_byte(TYPE_ELLIPSIS, p);
681
1
    }
682
55.3k
    else if (v == Py_False) {
683
137
        w_byte(TYPE_FALSE, p);
684
137
    }
685
55.1k
    else if (v == Py_True) {
686
33
        w_byte(TYPE_TRUE, p);
687
33
    }
688
55.1k
    else if (!w_ref(v, p))
689
28.8k
        w_complex_object(v, p);
690
691
55.5k
    p->depth--;
692
55.5k
}
693
694
static void
695
w_complex_object(PyObject *v, WFILE *p)
696
28.8k
{
697
28.8k
    Py_ssize_t i, n;
698
699
28.8k
    if (PyLong_CheckExact(v)) {
700
2.08k
        int overflow;
701
2.08k
        long x = PyLong_AsLongAndOverflow(v, &overflow);
702
2.08k
        if (overflow) {
703
3
            w_PyLong((PyLongObject *)v, p);
704
3
        }
705
2.07k
        else {
706
2.07k
#if SIZEOF_LONG > 4
707
2.07k
            long y = Py_ARITHMETIC_RIGHT_SHIFT(long, x, 31);
708
2.07k
            if (y && y != -1) {
709
                /* Too large for TYPE_INT */
710
2
                w_PyLong((PyLongObject*)v, p);
711
2
            }
712
2.07k
            else
713
2.07k
#endif
714
2.07k
            {
715
2.07k
                W_TYPE(TYPE_INT, p);
716
2.07k
                w_long(x, p);
717
2.07k
            }
718
2.07k
        }
719
2.08k
    }
720
26.7k
    else if (PyFloat_CheckExact(v)) {
721
8
        if (p->version > 1) {
722
8
            W_TYPE(TYPE_BINARY_FLOAT, p);
723
8
            w_float_bin(PyFloat_AS_DOUBLE(v), p);
724
8
        }
725
0
        else {
726
0
            W_TYPE(TYPE_FLOAT, p);
727
0
            w_float_str(PyFloat_AS_DOUBLE(v), p);
728
0
        }
729
8
    }
730
26.7k
    else if (PyComplex_CheckExact(v)) {
731
1
        if (p->version > 1) {
732
1
            W_TYPE(TYPE_BINARY_COMPLEX, p);
733
1
            w_float_bin(PyComplex_RealAsDouble(v), p);
734
1
            w_float_bin(PyComplex_ImagAsDouble(v), p);
735
1
        }
736
0
        else {
737
0
            W_TYPE(TYPE_COMPLEX, p);
738
0
            w_float_str(PyComplex_RealAsDouble(v), p);
739
0
            w_float_str(PyComplex_ImagAsDouble(v), p);
740
0
        }
741
1
    }
742
26.7k
    else if (PyBytes_CheckExact(v)) {
743
6.68k
        W_TYPE(TYPE_STRING, p);
744
6.68k
        w_pstring(PyBytes_AS_STRING(v), PyBytes_GET_SIZE(v), p);
745
6.68k
    }
746
20.0k
    else if (PyUnicode_CheckExact(v)) {
747
11.7k
        if (p->version >= 4 && PyUnicode_IS_ASCII(v)) {
748
11.6k
            int is_short = PyUnicode_GET_LENGTH(v) < 256;
749
11.6k
            if (is_short) {
750
11.5k
                if (PyUnicode_CHECK_INTERNED(v))
751
11.5k
                    W_TYPE(TYPE_SHORT_ASCII_INTERNED, p);
752
1.06k
                else
753
11.5k
                    W_TYPE(TYPE_SHORT_ASCII, p);
754
11.5k
                w_short_pstring(PyUnicode_1BYTE_DATA(v),
755
11.5k
                                PyUnicode_GET_LENGTH(v), p);
756
11.5k
            }
757
121
            else {
758
121
                if (PyUnicode_CHECK_INTERNED(v))
759
121
                    W_TYPE(TYPE_ASCII_INTERNED, p);
760
121
                else
761
121
                    W_TYPE(TYPE_ASCII, p);
762
121
                w_pstring(PyUnicode_1BYTE_DATA(v),
763
121
                          PyUnicode_GET_LENGTH(v), p);
764
121
            }
765
11.6k
        }
766
69
        else {
767
69
            PyObject *utf8;
768
69
            utf8 = PyUnicode_AsEncodedString(v, "utf8", "surrogatepass");
769
69
            if (utf8 == NULL) {
770
0
                p->depth--;
771
0
                p->error = true;
772
0
                return;
773
0
            }
774
69
            if (p->version >= 3 &&  PyUnicode_CHECK_INTERNED(v))
775
69
                W_TYPE(TYPE_INTERNED, p);
776
69
            else
777
69
                W_TYPE(TYPE_UNICODE, p);
778
69
            w_pstring(PyBytes_AS_STRING(utf8), PyBytes_GET_SIZE(utf8), p);
779
69
            Py_DECREF(utf8);
780
69
        }
781
11.7k
    }
782
8.29k
    else if (PyTuple_CheckExact(v)) {
783
5.85k
        n = PyTuple_GET_SIZE(v);
784
5.85k
        if (p->version >= 4 && n < 256) {
785
5.85k
            W_TYPE(TYPE_SMALL_TUPLE, p);
786
5.85k
            w_byte((unsigned char)n, p);
787
5.85k
        }
788
0
        else {
789
0
            W_TYPE(TYPE_TUPLE, p);
790
0
            W_SIZE(n, p);
791
0
        }
792
37.0k
        for (i = 0; i < n; i++) {
793
31.1k
            w_object(PyTuple_GET_ITEM(v, i), p);
794
31.1k
        }
795
5.85k
        w_complete(v, p);
796
5.85k
    }
797
2.43k
    else if (PyList_CheckExact(v)) {
798
0
        W_TYPE(TYPE_LIST, p);
799
0
        n = PyList_GET_SIZE(v);
800
0
        W_SIZE(n, p);
801
0
        for (i = 0; i < n; i++) {
802
0
            w_object(PyList_GET_ITEM(v, i), p);
803
0
        }
804
0
    }
805
2.43k
    else if (PyAnyDict_CheckExact(v)) {
806
0
        Py_ssize_t pos;
807
0
        PyObject *key, *value;
808
0
        if (PyFrozenDict_CheckExact(v)) {
809
0
            if (p->version < 6) {
810
0
                w_byte(TYPE_UNKNOWN, p);
811
0
                PyErr_Format(PyExc_ValueError,
812
0
                             "marshalling %T objects requires version 6 "
813
0
                             "or higher", v);
814
0
                p->error = true;
815
0
                return;
816
0
            }
817
818
0
            W_TYPE(TYPE_FROZENDICT, p);
819
0
        }
820
0
        else {
821
0
            W_TYPE(TYPE_DICT, p);
822
0
        }
823
        /* This one is NULL object terminated! */
824
0
        pos = 0;
825
0
        while (PyDict_Next(v, &pos, &key, &value)) {
826
0
            w_object(key, p);
827
0
            w_object(value, p);
828
0
        }
829
0
        w_object((PyObject *)NULL, p);
830
0
        if (PyFrozenDict_CheckExact(v)) {
831
0
            w_complete(v, p);
832
0
        }
833
0
    }
834
2.43k
    else if (PyAnySet_CheckExact(v)) {
835
11
        PyObject *value;
836
11
        Py_ssize_t pos = 0;
837
11
        Py_hash_t hash;
838
839
11
        if (PyFrozenSet_CheckExact(v))
840
11
            W_TYPE(TYPE_FROZENSET, p);
841
0
        else
842
11
            W_TYPE(TYPE_SET, p);
843
11
        n = PySet_GET_SIZE(v);
844
11
        W_SIZE(n, p);
845
        // bpo-37596: To support reproducible builds, sets and frozensets need
846
        // to have their elements serialized in a consistent order (even when
847
        // they have been scrambled by hash randomization). To ensure this, we
848
        // use an order equivalent to sorted(v, key=marshal.dumps).
849
        // The list has a (dump, index, element) tuple for each element.
850
        // The indexes are all different, so that sorting never compares
851
        // two elements: elements with the same dump (NaNs which are
852
        // distinct objects) may not be orderable.
853
11
        PyObject *items = PyList_New(n);
854
11
        if (items == NULL) {
855
0
            p->error = true;
856
0
            return;
857
0
        }
858
        // Marshalling an element can run arbitrary code (an audit hook, or
859
        // the __buffer__() method of the element), which can add elements
860
        // to the set or remove some: n is not trusted to still be the size
861
        // of the set.
862
11
        Py_ssize_t i = 0;
863
11
        bool changed = false;
864
11
        Py_BEGIN_CRITICAL_SECTION(v);
865
86
        while (_PySet_NextEntryRef(v, &pos, &value, &hash)) {
866
75
            if (i == n) {
867
0
                changed = true;
868
0
                Py_DECREF(value);
869
0
                break;
870
0
            }
871
75
            PyObject *dump = _PyMarshal_WriteObjectToString(value,
872
75
                                    p->version, p->allow_code);
873
75
            if (dump == NULL) {
874
0
                p->error = true;
875
0
                Py_DECREF(value);
876
0
                break;
877
0
            }
878
75
            PyObject *index = PyLong_FromSsize_t(i);
879
75
            PyObject *item = NULL;
880
75
            if (index != NULL) {
881
75
                item = PyTuple_Pack(3, dump, index, value);
882
75
                Py_DECREF(index);
883
75
            }
884
75
            Py_DECREF(dump);
885
75
            Py_DECREF(value);
886
75
            if (item == NULL) {
887
0
                p->error = true;
888
0
                break;
889
0
            }
890
75
            PyList_SET_ITEM(items, i++, item);
891
75
        }
892
11
        Py_END_CRITICAL_SECTION();
893
11
        if (!p->error && (changed || i != n)) {
894
0
            PyErr_SetString(PyExc_RuntimeError,
895
0
                            "set changed size during iteration");
896
0
            p->error = true;
897
0
        }
898
11
        if (p->error) {
899
0
            Py_DECREF(items);
900
0
            return;
901
0
        }
902
11
        if (PyList_Sort(items)) {
903
0
            p->error = true;
904
0
            Py_DECREF(items);
905
0
            return;
906
0
        }
907
86
        for (Py_ssize_t i = 0; i < n; i++) {
908
75
            PyObject *item = PyList_GET_ITEM(items, i);
909
75
            value = PyTuple_GET_ITEM(item, 2);
910
75
            w_object(value, p);
911
75
        }
912
11
        Py_DECREF(items);
913
11
    }
914
2.42k
    else if (PyCode_Check(v)) {
915
2.40k
        if (!p->allow_code) {
916
0
            PyErr_SetString(PyExc_ValueError,
917
0
                            "marshalling code objects is disallowed");
918
0
            p->error = true;
919
0
            return;
920
0
        }
921
2.40k
        PyCodeObject *co = (PyCodeObject *)v;
922
2.40k
        PyObject *co_code = _PyCode_GetCode(co);
923
2.40k
        if (co_code == NULL) {
924
0
            p->error = true;
925
0
            return;
926
0
        }
927
2.40k
        W_TYPE(TYPE_CODE, p);
928
2.40k
        w_long(co->co_argcount, p);
929
2.40k
        w_long(co->co_posonlyargcount, p);
930
2.40k
        w_long(co->co_kwonlyargcount, p);
931
2.40k
        w_long(co->co_stacksize, p);
932
2.40k
        w_long(co->co_flags, p);
933
2.40k
        w_object(co_code, p);
934
2.40k
        w_object(co->co_consts, p);
935
2.40k
        w_object(co->co_names, p);
936
2.40k
        w_object(co->co_localsplusnames, p);
937
2.40k
        w_object(co->co_localspluskinds, p);
938
2.40k
        w_object(co->co_filename, p);
939
2.40k
        w_object(co->co_name, p);
940
2.40k
        w_object(co->co_qualname, p);
941
2.40k
        w_long(co->co_firstlineno, p);
942
2.40k
        w_object(co->co_linetable, p);
943
2.40k
        w_object(co->co_exceptiontable, p);
944
2.40k
        Py_DECREF(co_code);
945
2.40k
        w_complete(v, p);
946
2.40k
    }
947
21
    else if (PyObject_CheckBuffer(v)) {
948
        /* Write unknown bytes-like objects as a bytes object */
949
0
        Py_buffer view;
950
0
        if (PyObject_GetBuffer(v, &view, PyBUF_SIMPLE) != 0) {
951
0
            w_byte(TYPE_UNKNOWN, p);
952
0
            p->depth--;
953
0
            p->error = true;
954
0
            return;
955
0
        }
956
0
        W_TYPE(TYPE_STRING, p);
957
0
        w_pstring(view.buf, view.len, p);
958
0
        PyBuffer_Release(&view);
959
0
    }
960
21
    else if (PySlice_Check(v)) {
961
21
        if (p->version < 5) {
962
0
            w_byte(TYPE_UNKNOWN, p);
963
0
            PyErr_Format(PyExc_ValueError,
964
0
                         "marshalling %T objects requires version 5 "
965
0
                         "or higher", v);
966
0
            p->error = true;
967
0
            return;
968
0
        }
969
21
        PySliceObject *slice = (PySliceObject *)v;
970
21
        W_TYPE(TYPE_SLICE, p);
971
21
        w_object(slice->start, p);
972
21
        w_object(slice->stop, p);
973
21
        w_object(slice->step, p);
974
21
        w_complete(v, p);
975
21
    }
976
0
    else {
977
0
        W_TYPE(TYPE_UNKNOWN, p);
978
0
        PyErr_Format(PyExc_ValueError, "cannot marshal %T objects", v);
979
0
        p->error = true;
980
0
    }
981
28.8k
}
982
983
static void
984
w_decref_entry(void *key)
985
14.3k
{
986
14.3k
    PyObject *entry_key = (PyObject *)key;
987
14.3k
    Py_XDECREF(entry_key);
988
14.3k
}
989
990
static int
991
w_init_refs(WFILE *wf, int version)
992
215
{
993
215
    if (version >= 3) {
994
215
        wf->hashtable = _Py_hashtable_new_full(_Py_hashtable_hash_ptr,
995
215
                                               _Py_hashtable_compare_direct,
996
215
                                               w_decref_entry, NULL, NULL);
997
215
        if (wf->hashtable == NULL) {
998
0
            PyErr_NoMemory();
999
0
            return -1;
1000
0
        }
1001
215
    }
1002
215
    return 0;
1003
215
}
1004
1005
static void
1006
w_clear_refs(WFILE *wf)
1007
215
{
1008
215
    if (wf->hashtable != NULL) {
1009
215
        _Py_hashtable_destroy(wf->hashtable);
1010
215
    }
1011
215
    PyMem_Free(wf->refs);
1012
215
    PyMem_Free(wf->refpos);
1013
215
}
1014
1015
/* Write a buffer to a file.  Set an exception on failure. */
1016
static void
1017
w_fwrite(const char *buf, size_t n, FILE *fp)
1018
0
{
1019
0
    if (fwrite(buf, 1, n, fp) != n) {
1020
0
        int saved_errno = errno;
1021
0
        if (PyErr_CheckSignals()) {
1022
            /* The signal handler has raised an exception. */
1023
0
            return;
1024
0
        }
1025
0
        errno = saved_errno;
1026
0
        PyErr_SetFromErrno(PyExc_OSError);
1027
0
    }
1028
0
}
1029
1030
/* version currently has no effect for writing ints. */
1031
void
1032
PyMarshal_WriteLongToFile(long x, FILE *fp, int Py_UNUSED(version))
1033
0
{
1034
0
    char buf[4];
1035
0
    w_put_uint32(buf, (uint32_t)x);
1036
0
    w_fwrite(buf, sizeof(buf), fp);
1037
0
}
1038
1039
void
1040
PyMarshal_WriteObjectToFile(PyObject *x, FILE *fp, int version)
1041
0
{
1042
    /* Object references are resolved once the whole object is written
1043
       (see w_ref()), so the output cannot be written to the file piece by
1044
       piece. */
1045
0
    PyObject *str = _PyMarshal_WriteObjectToString(x, version, 1);
1046
0
    if (str == NULL) {
1047
0
        return; /* caller must check PyErr_Occurred() */
1048
0
    }
1049
0
    w_fwrite(PyBytes_AS_STRING(str), (size_t)PyBytes_GET_SIZE(str), fp);
1050
0
    Py_DECREF(str);
1051
0
}
1052
1053
typedef struct {
1054
    FILE *fp;
1055
    int depth;
1056
    PyObject *readable;  /* Stream-like object being read from */
1057
    const char *ptr;
1058
    const char *end;
1059
    char *buf;
1060
    Py_ssize_t buf_size;
1061
    PyObject *refs;  /* a list */
1062
    int allow_code;
1063
} RFILE;
1064
1065
static const char *
1066
r_string(Py_ssize_t n, RFILE *p)
1067
4.94M
{
1068
4.94M
    Py_ssize_t read = -1;
1069
1070
4.94M
    if (p->ptr != NULL) {
1071
        /* Fast path for loads() */
1072
4.94M
        const char *res = p->ptr;
1073
4.94M
        Py_ssize_t left = p->end - p->ptr;
1074
4.94M
        if (left < n) {
1075
0
            PyErr_SetString(PyExc_EOFError,
1076
0
                            "marshal data too short");
1077
0
            return NULL;
1078
0
        }
1079
4.94M
        p->ptr += n;
1080
4.94M
        return res;
1081
4.94M
    }
1082
0
    if (p->buf == NULL) {
1083
0
        p->buf = PyMem_Malloc(n);
1084
0
        if (p->buf == NULL) {
1085
0
            PyErr_NoMemory();
1086
0
            return NULL;
1087
0
        }
1088
0
        p->buf_size = n;
1089
0
    }
1090
0
    else if (p->buf_size < n) {
1091
0
        char *tmp = PyMem_Realloc(p->buf, n);
1092
0
        if (tmp == NULL) {
1093
0
            PyErr_NoMemory();
1094
0
            return NULL;
1095
0
        }
1096
0
        p->buf = tmp;
1097
0
        p->buf_size = n;
1098
0
    }
1099
1100
0
    if (!p->readable) {
1101
0
        assert(p->fp != NULL);
1102
0
        read = fread(p->buf, 1, n, p->fp);
1103
0
        if (read != n) {
1104
0
            assert(read < n);
1105
0
            int saved_errno = errno;
1106
0
            if (!PyErr_CheckSignals() && ferror(p->fp)) {
1107
0
                errno = saved_errno;
1108
0
                PyErr_SetFromErrno(PyExc_OSError);
1109
0
            }
1110
0
        }
1111
0
    }
1112
0
    else {
1113
0
        PyObject *res, *mview;
1114
0
        Py_buffer buf;
1115
1116
0
        if (PyBuffer_FillInfo(&buf, NULL, p->buf, n, 0, PyBUF_CONTIG) == -1)
1117
0
            return NULL;
1118
0
        mview = PyMemoryView_FromBuffer(&buf);
1119
0
        if (mview == NULL)
1120
0
            return NULL;
1121
1122
0
        res = _PyObject_CallMethod(p->readable, &_Py_ID(readinto), "N", mview);
1123
0
        if (res == NULL) {
1124
0
            return NULL;
1125
0
        }
1126
0
        read = PyNumber_AsSsize_t(res, PyExc_ValueError);
1127
0
        Py_DECREF(res);
1128
0
        if (read == -1 && PyErr_Occurred()) {
1129
0
            return NULL;
1130
0
        }
1131
0
        if (read > n) {
1132
0
            PyErr_Format(PyExc_ValueError,
1133
0
                         "read() returned too much data: "
1134
0
                         "%zd bytes requested, %zd returned",
1135
0
                         n, read);
1136
0
            return NULL;
1137
0
        }
1138
0
    }
1139
0
    if (read != n) {
1140
0
        if (!PyErr_Occurred()) {
1141
0
            PyErr_SetString(PyExc_EOFError,
1142
0
                            "EOF read where not expected");
1143
0
        }
1144
0
        return NULL;
1145
0
    }
1146
0
    return p->buf;
1147
0
}
1148
1149
static int
1150
r_byte(RFILE *p)
1151
5.70M
{
1152
5.70M
    if (p->ptr != NULL) {
1153
5.70M
        if (p->ptr < p->end) {
1154
5.70M
            return (unsigned char) *p->ptr++;
1155
5.70M
        }
1156
5.70M
    }
1157
0
    else if (!p->readable) {
1158
0
        assert(p->fp);
1159
0
        int c = getc(p->fp);
1160
0
        if (c != EOF) {
1161
0
            return c;
1162
0
        }
1163
0
        int saved_errno = errno;
1164
0
        if (PyErr_CheckSignals()) {
1165
0
            return EOF;
1166
0
        }
1167
0
        if (ferror(p->fp)) {
1168
0
            errno = saved_errno;
1169
0
            PyErr_SetFromErrno(PyExc_OSError);
1170
0
            return EOF;
1171
0
        }
1172
0
    }
1173
0
    else {
1174
0
        const char *ptr = r_string(1, p);
1175
0
        if (ptr != NULL) {
1176
0
            return *(const unsigned char *) ptr;
1177
0
        }
1178
0
        return EOF;
1179
0
    }
1180
0
    PyErr_SetString(PyExc_EOFError,
1181
0
                    "EOF read where not expected");
1182
0
    return EOF;
1183
5.70M
}
1184
1185
static int
1186
r_short(RFILE *p)
1187
1.69k
{
1188
1.69k
    short x = -1;
1189
1.69k
    const unsigned char *buffer;
1190
1191
1.69k
    buffer = (const unsigned char *) r_string(2, p);
1192
1.69k
    if (buffer != NULL) {
1193
1.69k
        x = buffer[0];
1194
1.69k
        x |= buffer[1] << 8;
1195
        /* Sign-extension, in case short greater than 16 bits */
1196
1.69k
        x |= -(x & 0x8000);
1197
1.69k
    }
1198
1.69k
    return x;
1199
1.69k
}
1200
1201
static long
1202
r_long(RFILE *p)
1203
3.25M
{
1204
3.25M
    long x = -1;
1205
3.25M
    const unsigned char *buffer;
1206
1207
3.25M
    buffer = (const unsigned char *) r_string(4, p);
1208
3.25M
    if (buffer != NULL) {
1209
3.25M
        x = buffer[0];
1210
3.25M
        x |= (long)buffer[1] << 8;
1211
3.25M
        x |= (long)buffer[2] << 16;
1212
3.25M
        x |= (long)buffer[3] << 24;
1213
3.25M
#if SIZEOF_LONG > 4
1214
        /* Sign extension for 64-bit machines */
1215
3.25M
        x |= -(x & 0x80000000L);
1216
3.25M
#endif
1217
3.25M
    }
1218
3.25M
    return x;
1219
3.25M
}
1220
1221
/* r_long64 deals with the TYPE_INT64 code. */
1222
static PyObject *
1223
r_long64(RFILE *p)
1224
0
{
1225
0
    const unsigned char *buffer = (const unsigned char *) r_string(8, p);
1226
0
    if (buffer == NULL) {
1227
0
        return NULL;
1228
0
    }
1229
0
    return _PyLong_FromByteArray(buffer, 8,
1230
0
                                 1 /* little endian */,
1231
0
                                 1 /* signed */);
1232
0
}
1233
1234
#define _w_digits(bitsize)                                              \
1235
static int                                                              \
1236
_w_digits##bitsize(uint ## bitsize ## _t *digits, Py_ssize_t size,      \
1237
                   Py_ssize_t marshal_ratio,                            \
1238
444
                   int shorts_in_top_digit, RFILE *p)                   \
1239
444
{                                                                       \
1240
444
    uint ## bitsize ## _t d;                                            \
1241
444
                                                                        \
1242
444
    assert(size >= 1);                                                  \
1243
1.03k
    for (Py_ssize_t i = 0; i < size - 1; i++) {                         \
1244
587
        d = 0;                                                          \
1245
1.76k
        for (Py_ssize_t j = 0; j < marshal_ratio; j++) {                \
1246
1.17k
            int md = r_short(p);                                        \
1247
1.17k
            if (md < 0 || md > PyLong_MARSHAL_BASE) {                   \
1248
0
                goto bad_digit;                                         \
1249
0
            }                                                           \
1250
1.17k
            d += (uint ## bitsize ## _t)md << j*PyLong_MARSHAL_SHIFT;   \
1251
1.17k
        }                                                               \
1252
587
        digits[i] = d;                                                  \
1253
587
    }                                                                   \
1254
444
                                                                        \
1255
444
    d = 0;                                                              \
1256
964
    for (Py_ssize_t j = 0; j < shorts_in_top_digit; j++) {              \
1257
520
        int md = r_short(p);                                            \
1258
520
        if (md < 0 || md > PyLong_MARSHAL_BASE) {                       \
1259
0
            goto bad_digit;                                             \
1260
0
        }                                                               \
1261
520
        /* topmost marshal digit should be nonzero */                   \
1262
520
        if (md == 0 && j == shorts_in_top_digit - 1) {                  \
1263
0
            PyErr_SetString(PyExc_ValueError,                           \
1264
0
                "bad marshal data (unnormalized long data)");           \
1265
0
            return -1;                                                  \
1266
0
        }                                                               \
1267
520
        d += (uint ## bitsize ## _t)md << j*PyLong_MARSHAL_SHIFT;       \
1268
520
    }                                                                   \
1269
444
    assert(!PyErr_Occurred());                                          \
1270
444
    /* top digit should be nonzero, else the resulting PyLong won't be  \
1271
444
       normalized */                                                    \
1272
444
    digits[size - 1] = d;                                               \
1273
444
    return 0;                                                           \
1274
444
                                                                        \
1275
0
bad_digit:                                                              \
1276
0
    if (!PyErr_Occurred()) {                                            \
1277
0
        PyErr_SetString(PyExc_ValueError,                               \
1278
0
            "bad marshal data (digit out of range in long)");           \
1279
0
    }                                                                   \
1280
0
    return -1;                                                          \
1281
444
}
1282
444
_w_digits(32)
1283
0
_w_digits(16)
1284
#undef _w_digits
1285
1286
static PyObject *
1287
r_PyLong(RFILE *p)
1288
444
{
1289
444
    long n = r_long(p);
1290
444
    if (n == -1 && PyErr_Occurred()) {
1291
0
        return NULL;
1292
0
    }
1293
444
    if (n < -SIZE32_MAX || n > SIZE32_MAX) {
1294
0
        PyErr_SetString(PyExc_ValueError,
1295
0
                       "bad marshal data (long size out of range)");
1296
0
        return NULL;
1297
0
    }
1298
1299
444
    const PyLongLayout *layout = PyLong_GetNativeLayout();
1300
444
    Py_ssize_t marshal_ratio = layout->bits_per_digit/PyLong_MARSHAL_SHIFT;
1301
1302
    /* must be a multiple of PyLong_MARSHAL_SHIFT */
1303
444
    assert(layout->bits_per_digit % PyLong_MARSHAL_SHIFT == 0);
1304
444
    assert(layout->bits_per_digit >= PyLong_MARSHAL_SHIFT);
1305
1306
    /* other assumptions on PyLongObject internals */
1307
444
    assert(layout->bits_per_digit <= 32);
1308
444
    assert(layout->digits_order == -1);
1309
444
    assert(layout->digit_endianness == (PY_LITTLE_ENDIAN ? -1 : 1));
1310
444
    assert(layout->digit_size == 2 || layout->digit_size == 4);
1311
1312
444
    Py_ssize_t size = 1 + (Py_ABS(n) - 1) / marshal_ratio;
1313
1314
444
    assert(size >= 1);
1315
1316
444
    int shorts_in_top_digit = 1 + (Py_ABS(n) - 1) % marshal_ratio;
1317
444
    void *digits;
1318
444
    PyLongWriter *writer = PyLongWriter_Create(n < 0, size, &digits);
1319
1320
444
    if (writer == NULL) {
1321
0
        return NULL;
1322
0
    }
1323
1324
444
    int ret;
1325
1326
444
    if (layout->digit_size == 4) {
1327
444
        ret = _w_digits32(digits, size, marshal_ratio, shorts_in_top_digit, p);
1328
444
    }
1329
0
    else {
1330
0
        ret = _w_digits16(digits, size, marshal_ratio, shorts_in_top_digit, p);
1331
0
    }
1332
444
    if (ret < 0) {
1333
0
        PyLongWriter_Discard(writer);
1334
0
        return NULL;
1335
0
    }
1336
444
    return PyLongWriter_Finish(writer);
1337
444
}
1338
1339
static double
1340
r_float_bin(RFILE *p)
1341
614
{
1342
614
    const char *buf = r_string(8, p);
1343
614
    if (buf == NULL)
1344
0
        return -1;
1345
614
    return PyFloat_Unpack8(buf, 1);
1346
614
}
1347
1348
/* Issue #33720: Disable inlining for reducing the C stack consumption
1349
   on PGO builds. */
1350
Py_NO_INLINE static double
1351
r_float_str(RFILE *p)
1352
0
{
1353
0
    int n;
1354
0
    char buf[256];
1355
0
    const char *ptr;
1356
0
    n = r_byte(p);
1357
0
    if (n == EOF) {
1358
0
        return -1;
1359
0
    }
1360
0
    ptr = r_string(n, p);
1361
0
    if (ptr == NULL) {
1362
0
        return -1;
1363
0
    }
1364
0
    memcpy(buf, ptr, n);
1365
0
    buf[n] = '\0';
1366
0
    return PyOS_string_to_double(buf, NULL, NULL);
1367
0
}
1368
1369
/* allocate the reflist index for a new object. Return -1 on failure */
1370
static Py_ssize_t
1371
r_ref_reserve(int flag, RFILE *p)
1372
589k
{
1373
589k
    if (flag) { /* currently only FLAG_REF is defined */
1374
58.9k
        Py_ssize_t idx = PyList_GET_SIZE(p->refs);
1375
58.9k
        if (idx >= 0x7ffffffe) {
1376
0
            PyErr_SetString(PyExc_ValueError, "bad marshal data (index list too large)");
1377
0
            return -1;
1378
0
        }
1379
58.9k
        if (PyList_Append(p->refs, Py_None) < 0)
1380
0
            return -1;
1381
58.9k
        return idx;
1382
58.9k
    } else
1383
530k
        return 0;
1384
589k
}
1385
1386
/* insert the new object 'o' to the reflist at previously
1387
 * allocated index 'idx'.
1388
 * 'o' can be NULL, in which case nothing is done.
1389
 * if 'o' was non-NULL, and the function succeeds, 'o' is returned.
1390
 * if 'o' was non-NULL, and the function fails, 'o' is released and
1391
 * NULL returned. This simplifies error checking at the call site since
1392
 * a single test for NULL for the function result is enough.
1393
 */
1394
static PyObject *
1395
r_ref_insert(PyObject *o, Py_ssize_t idx, int flag, RFILE *p)
1396
589k
{
1397
589k
    if (o != NULL && flag) { /* currently only FLAG_REF is defined */
1398
58.9k
        PyObject *tmp = PyList_GET_ITEM(p->refs, idx);
1399
58.9k
        PyList_SET_ITEM(p->refs, idx, Py_NewRef(o));
1400
58.9k
        Py_DECREF(tmp);
1401
58.9k
    }
1402
589k
    return o;
1403
589k
}
1404
1405
/* combination of both above, used when an object can be
1406
 * created whenever it is seen in the file, as opposed to
1407
 * after having loaded its sub-objects.
1408
 */
1409
static PyObject *
1410
r_ref(PyObject *o, int flag, RFILE *p)
1411
463k
{
1412
463k
    assert(flag & FLAG_REF);
1413
463k
    if (o == NULL)
1414
0
        return NULL;
1415
463k
    if (PyList_Append(p->refs, o) < 0) {
1416
0
        Py_DECREF(o); /* release the new object */
1417
0
        return NULL;
1418
0
    }
1419
463k
    return o;
1420
463k
}
1421
1422
static PyObject *
1423
r_object(RFILE *p)
1424
4.10M
{
1425
    /* NULL is a valid return value, it does not necessarily means that
1426
       an exception is set. */
1427
4.10M
    PyObject *v, *v2;
1428
4.10M
    Py_ssize_t idx = 0;
1429
4.10M
    long i, n;
1430
4.10M
    int type, code = r_byte(p);
1431
4.10M
    int flag, is_interned = 0;
1432
4.10M
    PyObject *retval = NULL;
1433
1434
4.10M
    if (code == EOF) {
1435
0
        if (PyErr_ExceptionMatches(PyExc_EOFError)) {
1436
0
            PyErr_SetString(PyExc_EOFError,
1437
0
                            "EOF read where object expected");
1438
0
        }
1439
0
        return NULL;
1440
0
    }
1441
1442
4.10M
    p->depth++;
1443
1444
4.10M
    if (p->depth > MAX_MARSHAL_STACK_DEPTH) {
1445
0
        p->depth--;
1446
0
        PyErr_SetString(PyExc_ValueError, "recursion limit exceeded");
1447
0
        return NULL;
1448
0
    }
1449
1450
4.10M
    flag = code & FLAG_REF;
1451
4.10M
    type = code & ~FLAG_REF;
1452
1453
4.10M
#define R_REF(O) do{\
1454
1.71M
    if (flag) \
1455
1.71M
        O = r_ref(O, flag, p);\
1456
1.71M
} while (0)
1457
1458
4.10M
    switch (type) {
1459
1460
0
    case TYPE_NULL:
1461
0
        break;
1462
1463
36.5k
    case TYPE_NONE:
1464
36.5k
        retval = Py_None;
1465
36.5k
        break;
1466
1467
0
    case TYPE_STOPITER:
1468
0
        retval = Py_NewRef(PyExc_StopIteration);
1469
0
        break;
1470
1471
446
    case TYPE_ELLIPSIS:
1472
446
        retval = Py_Ellipsis;
1473
446
        break;
1474
1475
1.92k
    case TYPE_FALSE:
1476
1.92k
        retval = Py_False;
1477
1.92k
        break;
1478
1479
1.72k
    case TYPE_TRUE:
1480
1.72k
        retval = Py_True;
1481
1.72k
        break;
1482
1483
25.4k
    case TYPE_INT:
1484
25.4k
        n = r_long(p);
1485
25.4k
        if (n == -1 && PyErr_Occurred()) {
1486
0
            break;
1487
0
        }
1488
25.4k
        retval = PyLong_FromLong(n);
1489
25.4k
        R_REF(retval);
1490
25.4k
        break;
1491
1492
0
    case TYPE_INT64:
1493
0
        retval = r_long64(p);
1494
0
        R_REF(retval);
1495
0
        break;
1496
1497
444
    case TYPE_LONG:
1498
444
        retval = r_PyLong(p);
1499
444
        R_REF(retval);
1500
444
        break;
1501
1502
0
    case TYPE_FLOAT:
1503
0
        {
1504
0
            double x = r_float_str(p);
1505
0
            if (x == -1.0 && PyErr_Occurred())
1506
0
                break;
1507
0
            retval = PyFloat_FromDouble(x);
1508
0
            R_REF(retval);
1509
0
            break;
1510
0
        }
1511
1512
608
    case TYPE_BINARY_FLOAT:
1513
608
        {
1514
608
            double x = r_float_bin(p);
1515
608
            if (x == -1.0 && PyErr_Occurred())
1516
0
                break;
1517
608
            retval = PyFloat_FromDouble(x);
1518
608
            R_REF(retval);
1519
608
            break;
1520
608
        }
1521
1522
0
    case TYPE_COMPLEX:
1523
0
        {
1524
0
            Py_complex c;
1525
0
            c.real = r_float_str(p);
1526
0
            if (c.real == -1.0 && PyErr_Occurred())
1527
0
                break;
1528
0
            c.imag = r_float_str(p);
1529
0
            if (c.imag == -1.0 && PyErr_Occurred())
1530
0
                break;
1531
0
            retval = PyComplex_FromCComplex(c);
1532
0
            R_REF(retval);
1533
0
            break;
1534
0
        }
1535
1536
3
    case TYPE_BINARY_COMPLEX:
1537
3
        {
1538
3
            Py_complex c;
1539
3
            c.real = r_float_bin(p);
1540
3
            if (c.real == -1.0 && PyErr_Occurred())
1541
0
                break;
1542
3
            c.imag = r_float_bin(p);
1543
3
            if (c.imag == -1.0 && PyErr_Occurred())
1544
0
                break;
1545
3
            retval = PyComplex_FromCComplex(c);
1546
3
            R_REF(retval);
1547
3
            break;
1548
3
        }
1549
1550
484k
    case TYPE_STRING:
1551
484k
        {
1552
484k
            const char *ptr;
1553
484k
            n = r_long(p);
1554
484k
            if (n < 0 || n > SIZE32_MAX) {
1555
0
                if (!PyErr_Occurred()) {
1556
0
                    PyErr_SetString(PyExc_ValueError,
1557
0
                        "bad marshal data (bytes object size out of range)");
1558
0
                }
1559
0
                break;
1560
0
            }
1561
484k
            ptr = r_string(n, p);
1562
484k
            if (ptr == NULL) {
1563
0
                break;
1564
0
            }
1565
            // Get a singleton for 1-byte string
1566
484k
            retval = PyBytes_FromStringAndSize(ptr, n);  // can be NULL
1567
484k
            R_REF(retval);
1568
484k
            break;
1569
484k
        }
1570
1571
0
    case TYPE_ASCII_INTERNED:
1572
0
        is_interned = 1;
1573
0
        _Py_FALLTHROUGH;
1574
24.2k
    case TYPE_ASCII:
1575
24.2k
        n = r_long(p);
1576
24.2k
        if (n < 0 || n > SIZE32_MAX) {
1577
0
            if (!PyErr_Occurred()) {
1578
0
                PyErr_SetString(PyExc_ValueError,
1579
0
                    "bad marshal data (string size out of range)");
1580
0
            }
1581
0
            break;
1582
0
        }
1583
24.2k
        goto _read_ascii;
1584
1585
1.02M
    case TYPE_SHORT_ASCII_INTERNED:
1586
1.02M
        is_interned = 1;
1587
1.02M
        _Py_FALLTHROUGH;
1588
1.17M
    case TYPE_SHORT_ASCII:
1589
1.17M
        n = r_byte(p);
1590
1.17M
        if (n == EOF) {
1591
0
            break;
1592
0
        }
1593
1.20M
    _read_ascii:
1594
1.20M
        {
1595
1.20M
            const char *ptr;
1596
1.20M
            ptr = r_string(n, p);
1597
1.20M
            if (ptr == NULL)
1598
0
                break;
1599
1.20M
            v = PyUnicode_FromKindAndData(PyUnicode_1BYTE_KIND, ptr, n);
1600
1.20M
            if (v == NULL)
1601
0
                break;
1602
1.20M
            if (is_interned) {
1603
                // marshal is meant to serialize .pyc files with code
1604
                // objects, and code-related strings are currently immortal.
1605
1.02M
                PyInterpreterState *interp = _PyInterpreterState_GET();
1606
1.02M
                _PyUnicode_InternImmortal(interp, &v);
1607
1.02M
            }
1608
1.20M
            retval = v;
1609
1.20M
            R_REF(retval);
1610
1.20M
            break;
1611
1.20M
        }
1612
1613
105
    case TYPE_INTERNED:
1614
105
        is_interned = 1;
1615
105
        _Py_FALLTHROUGH;
1616
3.58k
    case TYPE_UNICODE:
1617
3.58k
        {
1618
3.58k
        const char *buffer;
1619
1620
3.58k
        n = r_long(p);
1621
3.58k
        if (n < 0 || n > SIZE32_MAX) {
1622
0
            if (!PyErr_Occurred()) {
1623
0
                PyErr_SetString(PyExc_ValueError,
1624
0
                    "bad marshal data (string size out of range)");
1625
0
            }
1626
0
            break;
1627
0
        }
1628
3.58k
        if (n != 0) {
1629
3.58k
            buffer = r_string(n, p);
1630
3.58k
            if (buffer == NULL)
1631
0
                break;
1632
3.58k
            v = PyUnicode_DecodeUTF8(buffer, n, "surrogatepass");
1633
3.58k
        }
1634
0
        else {
1635
0
            v = Py_GetConstant(Py_CONSTANT_EMPTY_STR);
1636
0
        }
1637
3.58k
        if (v == NULL)
1638
0
            break;
1639
3.58k
        if (is_interned) {
1640
            // marshal is meant to serialize .pyc files with code
1641
            // objects, and code-related strings are currently immortal.
1642
105
            PyInterpreterState *interp = _PyInterpreterState_GET();
1643
105
            _PyUnicode_InternImmortal(interp, &v);
1644
105
        }
1645
3.58k
        retval = v;
1646
3.58k
        R_REF(retval);
1647
3.58k
        break;
1648
3.58k
        }
1649
1650
425k
    case TYPE_SMALL_TUPLE:
1651
425k
        n = r_byte(p);
1652
425k
        if (n == EOF) {
1653
0
            break;
1654
0
        }
1655
425k
        goto _read_tuple;
1656
425k
    case TYPE_TUPLE:
1657
70
        n = r_long(p);
1658
70
        if (n < 0 || n > SIZE32_MAX) {
1659
0
            if (!PyErr_Occurred()) {
1660
0
                PyErr_SetString(PyExc_ValueError,
1661
0
                    "bad marshal data (tuple size out of range)");
1662
0
            }
1663
0
            break;
1664
0
        }
1665
425k
    _read_tuple:
1666
425k
        idx = r_ref_reserve(flag, p);
1667
425k
        if (idx < 0)
1668
0
            break;
1669
425k
        v = PyTuple_New(n);
1670
425k
        if (v == NULL)
1671
0
            break;
1672
1673
2.90M
        for (i = 0; i < n; i++) {
1674
2.48M
            v2 = r_object(p);
1675
2.48M
            if ( v2 == NULL ) {
1676
0
                if (!PyErr_Occurred())
1677
0
                    PyErr_SetString(PyExc_TypeError,
1678
0
                        "NULL object in marshal data for tuple");
1679
0
                Py_SETREF(v, NULL);
1680
0
                break;
1681
0
            }
1682
2.48M
            PyTuple_SET_ITEM(v, i, v2);
1683
2.48M
        }
1684
425k
        retval = r_ref_insert(v, idx, flag, p);
1685
425k
        break;
1686
1687
0
    case TYPE_LIST:
1688
0
        n = r_long(p);
1689
0
        if (n < 0 || n > SIZE32_MAX) {
1690
0
            if (!PyErr_Occurred()) {
1691
0
                PyErr_SetString(PyExc_ValueError,
1692
0
                    "bad marshal data (list size out of range)");
1693
0
            }
1694
0
            break;
1695
0
        }
1696
0
        v = PyList_New(n);
1697
0
        R_REF(v);
1698
0
        if (v == NULL)
1699
0
            break;
1700
0
        for (i = 0; i < n; i++) {
1701
0
            v2 = r_object(p);
1702
0
            if ( v2 == NULL ) {
1703
0
                if (!PyErr_Occurred())
1704
0
                    PyErr_SetString(PyExc_TypeError,
1705
0
                        "NULL object in marshal data for list");
1706
0
                Py_SETREF(v, NULL);
1707
0
                break;
1708
0
            }
1709
0
            PyList_SET_ITEM(v, i, v2);
1710
0
        }
1711
0
        retval = v;
1712
0
        break;
1713
1714
0
    case TYPE_DICT:
1715
0
    case TYPE_FROZENDICT:
1716
0
        v = PyDict_New();
1717
0
        if (v == NULL) {
1718
0
            break;
1719
0
        }
1720
0
        if (type == TYPE_DICT) {
1721
0
            R_REF(v);
1722
0
            if (v == NULL) {
1723
0
                break;
1724
0
            }
1725
0
        }
1726
0
        else {
1727
0
            idx = r_ref_reserve(flag, p);
1728
0
            if (idx < 0) {
1729
0
                Py_CLEAR(v);
1730
0
                break;
1731
0
            }
1732
0
        }
1733
0
        for (;;) {
1734
0
            PyObject *key, *val;
1735
0
            key = r_object(p);
1736
0
            if (key == NULL)
1737
0
                break;
1738
0
            val = r_object(p);
1739
0
            if (val == NULL) {
1740
0
                Py_DECREF(key);
1741
0
                break;
1742
0
            }
1743
0
            if (PyDict_SetItem(v, key, val) < 0) {
1744
0
                Py_DECREF(key);
1745
0
                Py_DECREF(val);
1746
0
                break;
1747
0
            }
1748
0
            Py_DECREF(key);
1749
0
            Py_DECREF(val);
1750
0
        }
1751
0
        if (PyErr_Occurred()) {
1752
0
            Py_CLEAR(v);
1753
0
        }
1754
0
        if (type == TYPE_FROZENDICT && v != NULL) {
1755
0
            Py_SETREF(v, PyFrozenDict_New(v));
1756
0
            v = r_ref_insert(v, idx, flag, p);
1757
0
        }
1758
0
        retval = v;
1759
0
        break;
1760
1761
0
    case TYPE_SET:
1762
459
    case TYPE_FROZENSET:
1763
459
        n = r_long(p);
1764
459
        if (n < 0 || n > SIZE32_MAX) {
1765
0
            if (!PyErr_Occurred()) {
1766
0
                PyErr_SetString(PyExc_ValueError,
1767
0
                    "bad marshal data (set size out of range)");
1768
0
            }
1769
0
            break;
1770
0
        }
1771
1772
459
        if (n == 0 && type == TYPE_FROZENSET) {
1773
            /* call frozenset() to get the empty frozenset singleton */
1774
0
            v = _PyObject_CallNoArgs((PyObject*)&PyFrozenSet_Type);
1775
0
            if (v == NULL)
1776
0
                break;
1777
0
            R_REF(v);
1778
0
            retval = v;
1779
0
        }
1780
459
        else {
1781
459
            v = (type == TYPE_SET) ? PySet_New(NULL) : PyFrozenSet_New(NULL);
1782
459
            if (type == TYPE_SET) {
1783
0
                R_REF(v);
1784
459
            } else {
1785
                /* must use delayed registration of frozensets because they must
1786
                 * be init with a refcount of 1
1787
                 */
1788
459
                idx = r_ref_reserve(flag, p);
1789
459
                if (idx < 0)
1790
0
                    Py_CLEAR(v); /* signal error */
1791
459
            }
1792
459
            if (v == NULL)
1793
0
                break;
1794
1795
2.39k
            for (i = 0; i < n; i++) {
1796
1.93k
                v2 = r_object(p);
1797
1.93k
                if ( v2 == NULL ) {
1798
0
                    if (!PyErr_Occurred())
1799
0
                        PyErr_SetString(PyExc_TypeError,
1800
0
                            "NULL object in marshal data for set");
1801
0
                    Py_SETREF(v, NULL);
1802
0
                    break;
1803
0
                }
1804
1.93k
                if (PySet_Add(v, v2) == -1) {
1805
0
                    Py_DECREF(v);
1806
0
                    Py_DECREF(v2);
1807
0
                    v = NULL;
1808
0
                    break;
1809
0
                }
1810
1.93k
                Py_DECREF(v2);
1811
1.93k
            }
1812
459
            if (type != TYPE_SET)
1813
459
                v = r_ref_insert(v, idx, flag, p);
1814
459
            retval = v;
1815
459
        }
1816
459
        break;
1817
1818
160k
    case TYPE_CODE:
1819
160k
        {
1820
160k
            int argcount;
1821
160k
            int posonlyargcount;
1822
160k
            int kwonlyargcount;
1823
160k
            int stacksize;
1824
160k
            int flags;
1825
160k
            PyObject *code = NULL;
1826
160k
            PyObject *consts = NULL;
1827
160k
            PyObject *names = NULL;
1828
160k
            PyObject *localsplusnames = NULL;
1829
160k
            PyObject *localspluskinds = NULL;
1830
160k
            PyObject *filename = NULL;
1831
160k
            PyObject *name = NULL;
1832
160k
            PyObject *qualname = NULL;
1833
160k
            int firstlineno;
1834
160k
            PyObject* linetable = NULL;
1835
160k
            PyObject *exceptiontable = NULL;
1836
1837
160k
            if (!p->allow_code) {
1838
0
                PyErr_SetString(PyExc_ValueError,
1839
0
                                "unmarshalling code objects is disallowed");
1840
0
                break;
1841
0
            }
1842
160k
            idx = r_ref_reserve(flag, p);
1843
160k
            if (idx < 0)
1844
0
                break;
1845
1846
160k
            v = NULL;
1847
1848
            /* XXX ignore long->int overflows for now */
1849
160k
            argcount = (int)r_long(p);
1850
160k
            if (argcount == -1 && PyErr_Occurred())
1851
0
                goto code_error;
1852
160k
            posonlyargcount = (int)r_long(p);
1853
160k
            if (posonlyargcount == -1 && PyErr_Occurred()) {
1854
0
                goto code_error;
1855
0
            }
1856
160k
            kwonlyargcount = (int)r_long(p);
1857
160k
            if (kwonlyargcount == -1 && PyErr_Occurred())
1858
0
                goto code_error;
1859
160k
            stacksize = (int)r_long(p);
1860
160k
            if (stacksize == -1 && PyErr_Occurred())
1861
0
                goto code_error;
1862
160k
            flags = (int)r_long(p);
1863
160k
            if (flags == -1 && PyErr_Occurred())
1864
0
                goto code_error;
1865
160k
            code = r_object(p);
1866
160k
            if (code == NULL)
1867
0
                goto code_error;
1868
160k
            consts = r_object(p);
1869
160k
            if (consts == NULL)
1870
0
                goto code_error;
1871
160k
            names = r_object(p);
1872
160k
            if (names == NULL)
1873
0
                goto code_error;
1874
160k
            localsplusnames = r_object(p);
1875
160k
            if (localsplusnames == NULL)
1876
0
                goto code_error;
1877
160k
            localspluskinds = r_object(p);
1878
160k
            if (localspluskinds == NULL)
1879
0
                goto code_error;
1880
160k
            filename = r_object(p);
1881
160k
            if (filename == NULL)
1882
0
                goto code_error;
1883
160k
            name = r_object(p);
1884
160k
            if (name == NULL)
1885
0
                goto code_error;
1886
160k
            qualname = r_object(p);
1887
160k
            if (qualname == NULL)
1888
0
                goto code_error;
1889
160k
            firstlineno = (int)r_long(p);
1890
160k
            if (firstlineno == -1 && PyErr_Occurred())
1891
0
                goto code_error;
1892
160k
            linetable = r_object(p);
1893
160k
            if (linetable == NULL)
1894
0
                goto code_error;
1895
160k
            exceptiontable = r_object(p);
1896
160k
            if (exceptiontable == NULL)
1897
0
                goto code_error;
1898
1899
160k
            struct _PyCodeConstructor con = {
1900
160k
                .filename = filename,
1901
160k
                .name = name,
1902
160k
                .qualname = qualname,
1903
160k
                .flags = flags,
1904
1905
160k
                .code = code,
1906
160k
                .firstlineno = firstlineno,
1907
160k
                .linetable = linetable,
1908
1909
160k
                .consts = consts,
1910
160k
                .names = names,
1911
1912
160k
                .localsplusnames = localsplusnames,
1913
160k
                .localspluskinds = localspluskinds,
1914
1915
160k
                .argcount = argcount,
1916
160k
                .posonlyargcount = posonlyargcount,
1917
160k
                .kwonlyargcount = kwonlyargcount,
1918
1919
160k
                .stacksize = stacksize,
1920
1921
160k
                .exceptiontable = exceptiontable,
1922
160k
            };
1923
1924
160k
            if (_PyCode_Validate(&con) < 0) {
1925
0
                goto code_error;
1926
0
            }
1927
1928
160k
            v = (PyObject *)_PyCode_New(&con);
1929
160k
            if (v == NULL) {
1930
0
                goto code_error;
1931
0
            }
1932
1933
160k
            v = r_ref_insert(v, idx, flag, p);
1934
1935
160k
          code_error:
1936
160k
            if (v == NULL && !PyErr_Occurred()) {
1937
0
                PyErr_SetString(PyExc_TypeError,
1938
0
                    "NULL object in marshal data for code object");
1939
0
            }
1940
160k
            Py_XDECREF(code);
1941
160k
            Py_XDECREF(consts);
1942
160k
            Py_XDECREF(names);
1943
160k
            Py_XDECREF(localsplusnames);
1944
160k
            Py_XDECREF(localspluskinds);
1945
160k
            Py_XDECREF(filename);
1946
160k
            Py_XDECREF(name);
1947
160k
            Py_XDECREF(qualname);
1948
160k
            Py_XDECREF(linetable);
1949
160k
            Py_XDECREF(exceptiontable);
1950
160k
        }
1951
0
        retval = v;
1952
160k
        break;
1953
1954
1.75M
    case TYPE_REF:
1955
1.75M
        n = r_long(p);
1956
1.75M
        if (n < 0 || n >= PyList_GET_SIZE(p->refs)) {
1957
0
            if (!PyErr_Occurred()) {
1958
0
                PyErr_SetString(PyExc_ValueError,
1959
0
                    "bad marshal data (invalid reference)");
1960
0
            }
1961
0
            break;
1962
0
        }
1963
1.75M
        v = PyList_GET_ITEM(p->refs, n);
1964
1.75M
        if (v == Py_None) {
1965
0
            PyErr_SetString(PyExc_ValueError, "bad marshal data (invalid reference)");
1966
0
            break;
1967
0
        }
1968
1.75M
        retval = Py_NewRef(v);
1969
1.75M
        break;
1970
1971
3.31k
    case TYPE_SLICE:
1972
3.31k
    {
1973
3.31k
        Py_ssize_t idx = r_ref_reserve(flag, p);
1974
3.31k
        if (idx < 0) {
1975
0
            break;
1976
0
        }
1977
3.31k
        PyObject *stop = NULL;
1978
3.31k
        PyObject *step = NULL;
1979
3.31k
        PyObject *start = r_object(p);
1980
3.31k
        if (start == NULL) {
1981
0
            goto cleanup;
1982
0
        }
1983
3.31k
        stop = r_object(p);
1984
3.31k
        if (stop == NULL) {
1985
0
            goto cleanup;
1986
0
        }
1987
3.31k
        step = r_object(p);
1988
3.31k
        if (step == NULL) {
1989
0
            goto cleanup;
1990
0
        }
1991
3.31k
        retval = PySlice_New(start, stop, step);
1992
3.31k
        r_ref_insert(retval, idx, flag, p);
1993
3.31k
    cleanup:
1994
3.31k
        Py_XDECREF(start);
1995
3.31k
        Py_XDECREF(stop);
1996
3.31k
        Py_XDECREF(step);
1997
3.31k
        break;
1998
3.31k
    }
1999
2000
0
    default:
2001
        /* Bogus data got written, which isn't ideal.
2002
           This will let you keep working and recover. */
2003
0
        PyErr_SetString(PyExc_ValueError, "bad marshal data (unknown type code)");
2004
0
        break;
2005
2006
4.10M
    }
2007
4.10M
    p->depth--;
2008
4.10M
    return retval;
2009
4.10M
}
2010
2011
static PyObject *
2012
read_object(RFILE *p)
2013
6.06k
{
2014
6.06k
    PyObject *v;
2015
6.06k
    if (PyErr_Occurred()) {
2016
0
        fprintf(stderr, "XXX readobject called with exception set\n");
2017
0
        return NULL;
2018
0
    }
2019
6.06k
    if (p->ptr && p->end) {
2020
6.06k
        if (PySys_Audit("marshal.loads", "y#", p->ptr, (Py_ssize_t)(p->end - p->ptr)) < 0) {
2021
0
            return NULL;
2022
0
        }
2023
6.06k
    } else if (p->fp || p->readable) {
2024
0
        if (PySys_Audit("marshal.load", NULL) < 0) {
2025
0
            return NULL;
2026
0
        }
2027
0
    }
2028
6.06k
    v = r_object(p);
2029
6.06k
    if (v == NULL && !PyErr_Occurred())
2030
0
        PyErr_SetString(PyExc_TypeError, "NULL object in marshal data for object");
2031
6.06k
    return v;
2032
6.06k
}
2033
2034
int
2035
PyMarshal_ReadShortFromFile(FILE *fp)
2036
0
{
2037
0
    RFILE rf;
2038
0
    int res;
2039
0
    assert(fp);
2040
0
    rf.readable = NULL;
2041
0
    rf.fp = fp;
2042
0
    rf.end = rf.ptr = NULL;
2043
0
    rf.buf = NULL;
2044
0
    res = r_short(&rf);
2045
0
    if (rf.buf != NULL)
2046
0
        PyMem_Free(rf.buf);
2047
0
    return res;
2048
0
}
2049
2050
long
2051
PyMarshal_ReadLongFromFile(FILE *fp)
2052
0
{
2053
0
    RFILE rf;
2054
0
    long res;
2055
0
    rf.fp = fp;
2056
0
    rf.readable = NULL;
2057
0
    rf.ptr = rf.end = NULL;
2058
0
    rf.buf = NULL;
2059
0
    res = r_long(&rf);
2060
0
    if (rf.buf != NULL)
2061
0
        PyMem_Free(rf.buf);
2062
0
    return res;
2063
0
}
2064
2065
/* Return size of file in bytes; < 0 if unknown or INT_MAX if too big */
2066
static off_t
2067
getfilesize(FILE *fp)
2068
0
{
2069
0
    struct _Py_stat_struct st;
2070
0
    if (_Py_fstat_noraise(fileno(fp), &st) != 0)
2071
0
        return -1;
2072
#if SIZEOF_OFF_T == 4
2073
    else if (st.st_size >= INT_MAX)
2074
        return (off_t)INT_MAX;
2075
#endif
2076
0
    else
2077
0
        return (off_t)st.st_size;
2078
0
}
2079
2080
/* If we can get the size of the file up-front, and it's reasonably small,
2081
 * read it in one gulp and delegate to ...FromString() instead.  Much quicker
2082
 * than reading a byte at a time from file; speeds .pyc imports.
2083
 * CAUTION:  since this may read the entire remainder of the file, don't
2084
 * call it unless you know you're done with the file.
2085
 */
2086
PyObject *
2087
PyMarshal_ReadLastObjectFromFile(FILE *fp)
2088
0
{
2089
/* REASONABLE_FILE_LIMIT is by defn something big enough for Tkinter.pyc. */
2090
0
#define REASONABLE_FILE_LIMIT (1L << 18)
2091
0
    off_t filesize;
2092
0
    filesize = getfilesize(fp);
2093
0
    if (filesize > 0 && filesize <= REASONABLE_FILE_LIMIT) {
2094
0
        char* pBuf = (char *)PyMem_Malloc(filesize);
2095
0
        if (pBuf != NULL) {
2096
0
            PyObject *v = NULL;
2097
0
            size_t n = fread(pBuf, 1, (size_t)filesize, fp);
2098
0
            int saved_errno = errno;
2099
0
            if (!PyErr_CheckSignals()) {
2100
0
                if (ferror(fp)) {
2101
0
                    errno = saved_errno;
2102
0
                    PyErr_SetFromErrno(PyExc_OSError);
2103
0
                }
2104
0
                else {
2105
0
                    v = PyMarshal_ReadObjectFromString(pBuf, n);
2106
0
                }
2107
0
            }
2108
0
            PyMem_Free(pBuf);
2109
0
            return v;
2110
0
        }
2111
2112
0
    }
2113
    /* We don't have fstat, or we do but the file is larger than
2114
     * REASONABLE_FILE_LIMIT or malloc failed -- read a byte at a time.
2115
     */
2116
0
    return PyMarshal_ReadObjectFromFile(fp);
2117
2118
0
#undef REASONABLE_FILE_LIMIT
2119
0
}
2120
2121
PyObject *
2122
PyMarshal_ReadObjectFromFile(FILE *fp)
2123
0
{
2124
0
    RFILE rf;
2125
0
    PyObject *result;
2126
0
    rf.allow_code = 1;
2127
0
    rf.fp = fp;
2128
0
    rf.readable = NULL;
2129
0
    rf.depth = 0;
2130
0
    rf.ptr = rf.end = NULL;
2131
0
    rf.buf = NULL;
2132
0
    rf.refs = PyList_New(0);
2133
0
    if (rf.refs == NULL)
2134
0
        return NULL;
2135
0
    result = read_object(&rf);
2136
0
    Py_DECREF(rf.refs);
2137
0
    if (rf.buf != NULL)
2138
0
        PyMem_Free(rf.buf);
2139
0
    return result;
2140
0
}
2141
2142
PyObject *
2143
PyMarshal_ReadObjectFromString(const char *str, Py_ssize_t len)
2144
572
{
2145
572
    RFILE rf;
2146
572
    PyObject *result;
2147
572
    rf.allow_code = 1;
2148
572
    rf.fp = NULL;
2149
572
    rf.readable = NULL;
2150
572
    rf.ptr = str;
2151
572
    rf.end = str + len;
2152
572
    rf.buf = NULL;
2153
572
    rf.depth = 0;
2154
572
    rf.refs = PyList_New(0);
2155
572
    if (rf.refs == NULL)
2156
0
        return NULL;
2157
572
    result = read_object(&rf);
2158
572
    Py_DECREF(rf.refs);
2159
572
    if (rf.buf != NULL)
2160
0
        PyMem_Free(rf.buf);
2161
572
    return result;
2162
572
}
2163
2164
static PyObject *
2165
_PyMarshal_WriteObjectToString(PyObject *x, int version, int allow_code)
2166
215
{
2167
215
    WFILE wf;
2168
2169
215
    if (PySys_Audit("marshal.dumps", "Oi", x, version) < 0) {
2170
0
        return NULL;
2171
0
    }
2172
215
    memset(&wf, 0, sizeof(wf));
2173
215
    wf.str = PyBytes_FromStringAndSize((char *)NULL, 50);
2174
215
    if (wf.str == NULL)
2175
0
        return NULL;
2176
215
    wf.ptr = wf.buf = PyBytes_AS_STRING(wf.str);
2177
215
    wf.end = wf.ptr + PyBytes_GET_SIZE(wf.str);
2178
215
    wf.error = false;
2179
215
    wf.version = version;
2180
215
    wf.allow_code = allow_code;
2181
215
    if (w_init_refs(&wf, version)) {
2182
0
        Py_DECREF(wf.str);
2183
0
        return NULL;
2184
0
    }
2185
215
    w_object(x, &wf);
2186
215
    w_resolve_refs(&wf);
2187
215
    w_clear_refs(&wf);
2188
215
    if (wf.str != NULL) {
2189
215
        const char *base = PyBytes_AS_STRING(wf.str);
2190
215
        if (_PyBytes_Resize(&wf.str, (Py_ssize_t)(wf.ptr - base)) < 0)
2191
0
            return NULL;
2192
215
    }
2193
215
    if (wf.error) {
2194
0
        assert(PyErr_Occurred());
2195
0
        Py_XDECREF(wf.str);
2196
0
        return NULL;
2197
0
    }
2198
215
    return wf.str;
2199
215
}
2200
2201
PyObject *
2202
PyMarshal_WriteObjectToString(PyObject *x, int version)
2203
0
{
2204
0
    return _PyMarshal_WriteObjectToString(x, version, 1);
2205
0
}
2206
2207
/* And an interface for Python programs... */
2208
/*[clinic input]
2209
marshal.dump
2210
2211
    value: object
2212
        Must be a supported type.
2213
    file: object
2214
        Must be a writeable binary file.
2215
    version: int(c_default="Py_MARSHAL_VERSION") = version
2216
        Indicates the data format that dump should use.
2217
    /
2218
    *
2219
    allow_code: bool = True
2220
        Allow to write code objects.
2221
2222
Write the value on the open file.
2223
2224
If the value has (or contains an object that has) an unsupported type, a
2225
ValueError exception is raised - but garbage data will also be written
2226
to the file. The object will not be properly read back by load().
2227
[clinic start generated code]*/
2228
2229
static PyObject *
2230
marshal_dump_impl(PyObject *module, PyObject *value, PyObject *file,
2231
                  int version, int allow_code)
2232
/*[clinic end generated code: output=429e5fd61c2196b9 input=041f7f6669b0aafb]*/
2233
0
{
2234
    /* XXX Quick hack -- need to do this differently */
2235
0
    PyObject *s;
2236
0
    PyObject *res;
2237
2238
0
    s = _PyMarshal_WriteObjectToString(value, version, allow_code);
2239
0
    if (s == NULL)
2240
0
        return NULL;
2241
0
    res = PyObject_CallMethodOneArg(file, &_Py_ID(write), s);
2242
0
    Py_DECREF(s);
2243
0
    return res;
2244
0
}
2245
2246
/*[clinic input]
2247
marshal.load
2248
2249
    file: object
2250
        Must be readable binary file.
2251
    /
2252
    *
2253
    allow_code: bool = True
2254
        Allow to load code objects.
2255
2256
Read one value from the open file and return it.
2257
2258
If no valid value is read (e.g. because the data has a different Python
2259
version's incompatible marshal format), raise EOFError, ValueError or
2260
TypeError.
2261
2262
Note: If an object containing an unsupported type was marshalled with
2263
dump(), load() will substitute None for the unmarshallable type.
2264
[clinic start generated code]*/
2265
2266
static PyObject *
2267
marshal_load_impl(PyObject *module, PyObject *file, int allow_code)
2268
/*[clinic end generated code: output=0c1aaf3546ae3ed3 input=2dca7b570653b82f]*/
2269
0
{
2270
0
    PyObject *data, *result;
2271
0
    RFILE rf;
2272
2273
    /*
2274
     * Make a call to the read method, but read zero bytes.
2275
     * This is to ensure that the object passed in at least
2276
     * has a read method which returns bytes.
2277
     * This can be removed if we guarantee good error handling
2278
     * for r_string()
2279
     */
2280
0
    data = _PyObject_CallMethod(file, &_Py_ID(read), "i", 0);
2281
0
    if (data == NULL)
2282
0
        return NULL;
2283
0
    if (!PyBytes_Check(data)) {
2284
0
        PyErr_Format(PyExc_TypeError,
2285
0
                     "file.read() returned not bytes but %.100s",
2286
0
                     Py_TYPE(data)->tp_name);
2287
0
        result = NULL;
2288
0
    }
2289
0
    else {
2290
0
        rf.allow_code = allow_code;
2291
0
        rf.depth = 0;
2292
0
        rf.fp = NULL;
2293
0
        rf.readable = file;
2294
0
        rf.ptr = rf.end = NULL;
2295
0
        rf.buf = NULL;
2296
0
        if ((rf.refs = PyList_New(0)) != NULL) {
2297
0
            result = read_object(&rf);
2298
0
            Py_DECREF(rf.refs);
2299
0
            if (rf.buf != NULL)
2300
0
                PyMem_Free(rf.buf);
2301
0
        } else
2302
0
            result = NULL;
2303
0
    }
2304
0
    Py_DECREF(data);
2305
0
    return result;
2306
0
}
2307
2308
/*[clinic input]
2309
@permit_long_summary
2310
marshal.dumps
2311
2312
    value: object
2313
        Must be a supported type.
2314
    version: int(c_default="Py_MARSHAL_VERSION") = version
2315
        Indicates the data format that dumps should use.
2316
    /
2317
    *
2318
    allow_code: bool = True
2319
        Allow to write code objects.
2320
2321
Return the bytes object that would be written to a file by dump(value, file).
2322
2323
Raise a ValueError exception if value has (or contains an object that
2324
has) an unsupported type.
2325
[clinic start generated code]*/
2326
2327
static PyObject *
2328
marshal_dumps_impl(PyObject *module, PyObject *value, int version,
2329
                   int allow_code)
2330
/*[clinic end generated code: output=115f90da518d1d49 input=dc1edcafd43124c5]*/
2331
140
{
2332
140
    return _PyMarshal_WriteObjectToString(value, version, allow_code);
2333
140
}
2334
2335
/*[clinic input]
2336
marshal.loads
2337
2338
    bytes: Py_buffer
2339
    /
2340
    *
2341
    allow_code: bool = True
2342
        Allow to load code objects.
2343
2344
Convert the bytes-like object to a value.
2345
2346
If no valid value is found, raise EOFError, ValueError or TypeError.
2347
Extra bytes in the input are ignored.
2348
[clinic start generated code]*/
2349
2350
static PyObject *
2351
marshal_loads_impl(PyObject *module, Py_buffer *bytes, int allow_code)
2352
/*[clinic end generated code: output=62c0c538d3edc31f input=286f1dbd6811d2ad]*/
2353
5.49k
{
2354
5.49k
    RFILE rf;
2355
5.49k
    char *s = bytes->buf;
2356
5.49k
    Py_ssize_t n = bytes->len;
2357
5.49k
    PyObject* result;
2358
5.49k
    rf.allow_code = allow_code;
2359
5.49k
    rf.fp = NULL;
2360
5.49k
    rf.readable = NULL;
2361
5.49k
    rf.ptr = s;
2362
5.49k
    rf.end = s + n;
2363
5.49k
    rf.depth = 0;
2364
5.49k
    if ((rf.refs = PyList_New(0)) == NULL)
2365
0
        return NULL;
2366
5.49k
    result = read_object(&rf);
2367
5.49k
    Py_DECREF(rf.refs);
2368
5.49k
    return result;
2369
5.49k
}
2370
2371
static PyMethodDef marshal_methods[] = {
2372
    MARSHAL_DUMP_METHODDEF
2373
    MARSHAL_LOAD_METHODDEF
2374
    MARSHAL_DUMPS_METHODDEF
2375
    MARSHAL_LOADS_METHODDEF
2376
    {NULL,              NULL}           /* sentinel */
2377
};
2378
2379
2380
PyDoc_STRVAR(module_doc,
2381
"This module contains functions that can read and write Python values in\n\
2382
a binary format. The format is specific to Python, but independent of\n\
2383
machine architecture issues.\n\
2384
\n\
2385
Not all Python object types are supported; in general, only objects\n\
2386
whose value is independent from a particular invocation of Python can be\n\
2387
written and read by this module. The following types are supported:\n\
2388
None, integers, floating-point numbers, strings, bytes, bytearrays,\n\
2389
tuples, lists, sets, dictionaries, and code objects, where it\n\
2390
should be understood that tuples, lists and dictionaries are only\n\
2391
supported as long as the values contained therein are themselves\n\
2392
supported; and recursive lists and dictionaries should not be written\n\
2393
(they will cause infinite loops).\n\
2394
\n\
2395
Variables:\n\
2396
\n\
2397
version -- indicates the format that the module uses. Version 0 is the\n\
2398
    historical format, version 1 shares interned strings and version 2\n\
2399
    uses a binary format for floating-point numbers.\n\
2400
    Version 3 shares common object references (New in version 3.4).\n\
2401
\n\
2402
Functions:\n\
2403
\n\
2404
dump() -- write value to a file\n\
2405
load() -- read value from a file\n\
2406
dumps() -- marshal value as a bytes object\n\
2407
loads() -- read value from a bytes-like object");
2408
2409
2410
static int
2411
marshal_module_exec(PyObject *mod)
2412
37
{
2413
37
    if (PyModule_AddIntConstant(mod, "version", Py_MARSHAL_VERSION) < 0) {
2414
0
        return -1;
2415
0
    }
2416
37
    return 0;
2417
37
}
2418
2419
static PyModuleDef_Slot marshalmodule_slots[] = {
2420
     _Py_ABI_SLOT,
2421
    {Py_mod_exec, marshal_module_exec},
2422
    {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
2423
    {Py_mod_gil, Py_MOD_GIL_NOT_USED},
2424
    {0, NULL}
2425
};
2426
2427
static struct PyModuleDef marshalmodule = {
2428
    PyModuleDef_HEAD_INIT,
2429
    .m_name = "marshal",
2430
    .m_doc = module_doc,
2431
    .m_methods = marshal_methods,
2432
    .m_slots = marshalmodule_slots,
2433
};
2434
2435
PyMODINIT_FUNC
2436
PyMarshal_Init(void)
2437
37
{
2438
37
    return PyModuleDef_Init(&marshalmodule);
2439
37
}