Coverage Report

Created: 2026-10-31 06:21

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
3.98M
#  define MAX_MARSHAL_STACK_DEPTH 2000
55
#endif
56
57
/* Supported types */
58
0
#define TYPE_NULL               '0'
59
34.7k
#define TYPE_NONE               'N'
60
1.75k
#define TYPE_FALSE              'F'
61
1.56k
#define TYPE_TRUE               'T'
62
0
#define TYPE_STOPITER           'S'
63
450
#define TYPE_ELLIPSIS           '.'
64
601
#define TYPE_BINARY_FLOAT       'g'  // Version 0 uses TYPE_FLOAT instead.
65
0
#define TYPE_BINARY_COMPLEX     'y'  // Version 0 uses TYPE_COMPLEX instead.
66
444
#define TYPE_LONG               'l'  // See also TYPE_INT.
67
465k
#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
153k
#define TYPE_CODE               'c'
73
3.58k
#define TYPE_UNICODE            'u'
74
#define TYPE_UNKNOWN            '?'
75
// added in version 2:
76
1.32k
#define TYPE_SET                '<'
77
442
#define TYPE_FROZENSET          '>'
78
// added in version 5:
79
3.15k
#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
23.1k
#define TYPE_ASCII              'a'
85
0
#define TYPE_ASCII_INTERNED     'A'
86
1.12M
#define TYPE_SHORT_ASCII        'z'
87
988k
#define TYPE_SHORT_ASCII_INTERNED 'Z'
88
89
/* Special cases for small objects */
90
23.9k
#define TYPE_INT                'i'  // All versions. 32-bit encoding.
91
407k
#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.70M
#define TYPE_REF                'r'
100
7.88M
#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
25.8k
#define W_ENTRY_ACTIVE ((uintptr_t)1)
116
30.5k
#define W_ENTRY_SHARED ((uintptr_t)2)
117
44.0k
#define W_ENTRY_SHIFT 2
118
20.4k
#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
13.5k
#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
129k
#define w_byte(c, p) do {                               \
147
129k
        if ((p)->ptr != (p)->end || w_reserve((p), 1))  \
148
129k
            *(p)->ptr++ = (c);                          \
149
129k
    } while(0)
150
151
static int
152
w_reserve(WFILE *p, Py_ssize_t needed)
153
439
{
154
439
    Py_ssize_t pos, size, delta;
155
439
    if (p->ptr == NULL)
156
0
        return 0; /* An error already occurred */
157
439
    assert(p->str != NULL);
158
439
    pos = p->ptr - p->buf;
159
439
    size = PyBytes_GET_SIZE(p->str);
160
439
    if (size > 16*1024*1024)
161
0
        delta = (size >> 3);            /* 12.5% overallocation */
162
439
    else
163
439
        delta = size + 1024;
164
439
    delta = Py_MAX(delta, needed);
165
439
    if (delta > PY_SSIZE_T_MAX - size) {
166
0
        PyErr_NoMemory();
167
0
        p->error = true;
168
0
        return 0;
169
0
    }
170
439
    size += delta;
171
439
    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
439
    else {
177
439
        p->buf = PyBytes_AS_STRING(p->str);
178
439
        p->ptr = p->buf + pos;
179
439
        p->end = p->buf + size;
180
439
        return 1;
181
439
    }
182
439
}
183
184
static void
185
w_string(const void *s, Py_ssize_t n, WFILE *p)
186
16.8k
{
187
16.8k
    Py_ssize_t m;
188
16.8k
    if (!n || p->ptr == NULL)
189
158
        return;
190
16.7k
    m = p->end - p->ptr;
191
16.7k
    if (n <= m || w_reserve(p, n - m)) {
192
16.7k
        memcpy(p->ptr, s, n);
193
16.7k
        p->ptr += n;
194
16.7k
    }
195
16.7k
}
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
21.6k
{
207
21.6k
    w_byte((char)( x      & 0xff), p);
208
21.6k
    w_byte((char)((x>> 8) & 0xff), p);
209
21.6k
    w_byte((char)((x>>16) & 0xff), p);
210
21.6k
    w_byte((char)((x>>24) & 0xff), p);
211
21.6k
}
212
213
/* Read and write a 32-bit value in place. */
214
static inline uint32_t
215
w_get_uint32(const char *ptr)
216
23.5k
{
217
23.5k
    const unsigned char *b = (const unsigned char *)ptr;
218
23.5k
    return b[0] | (b[1] << 8) | (b[2] << 16) | ((uint32_t)b[3] << 24);
219
23.5k
}
220
221
static inline void
222
w_put_uint32(char *ptr, uint32_t x)
223
47.1k
{
224
47.1k
    ptr[0] = (char)( x      & 0xff);
225
47.1k
    ptr[1] = (char)((x>> 8) & 0xff);
226
47.1k
    ptr[2] = (char)((x>>16) & 0xff);
227
47.1k
    ptr[3] = (char)((x>>24) & 0xff);
228
47.1k
}
229
230
499k
#define SIZE32_MAX  0x7FFFFFFF
231
232
#if SIZEOF_SIZE_T > 4
233
6.19k
# define W_SIZE(n, p)  do {                                 \
234
6.19k
        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.19k
        w_long((long)(n), p);                               \
242
6.19k
    } 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.19k
{
250
6.19k
        W_SIZE(n, p);
251
6.19k
        w_string(s, n, p);
252
6.19k
}
253
254
static void
255
w_short_pstring(const void *s, Py_ssize_t n, WFILE *p)
256
10.6k
{
257
10.6k
    w_byte(Py_SAFE_DOWNCAST(n, Py_ssize_t, unsigned char), p);
258
10.6k
    w_string(s, n, p);
259
10.6k
}
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
26.7k
#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
7
{
383
7
    char buf[8];
384
7
    if (PyFloat_Pack8(v, buf, 1) < 0) {
385
0
        p->error = true;
386
0
        return;
387
0
    }
388
7
    w_string(buf, 8, p);
389
7
}
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
27.3k
{
408
27.3k
    if (n < *allocated) {
409
26.1k
        return items;
410
26.1k
    }
411
1.20k
    size_t new_allocated = *allocated ? *allocated * 2 : 16;
412
1.20k
    if (new_allocated > (size_t)PY_SSIZE_T_MAX / itemsize) {
413
0
        return NULL;
414
0
    }
415
1.20k
    items = PyMem_Realloc(items, new_allocated * itemsize);
416
1.20k
    if (items != NULL) {
417
1.20k
        *allocated = new_allocated;
418
1.20k
    }
419
1.20k
    return items;
420
1.20k
}
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
23.5k
{
436
23.5k
    size_t pos = (size_t)(p->ptr - p->buf);
437
23.5k
    size_t gap = pos - p->refpos_end;
438
23.5k
    p->refpos_end = pos + 5;
439
23.5k
    if (gap == 0 && p->refpos_run != 0 && p->refpos[p->refpos_run] < 255) {
440
9.70k
        p->refpos[p->refpos_run]++;
441
9.70k
        return 1;
442
9.70k
    }
443
13.8k
    unsigned char *refpos = w_array_grow(p->refpos,
444
13.8k
                                         p->refpos_size + sizeof(size_t),
445
13.8k
                                         &p->refpos_allocated, 1);
446
13.8k
    if (refpos == NULL) {
447
0
        PyErr_NoMemory();
448
0
        return 0;
449
0
    }
450
13.8k
    p->refpos = refpos;
451
13.8k
    size_t size = p->refpos_size;
452
13.8k
    if (gap == 0) {
453
4.90k
        refpos[size++] = 0;
454
4.90k
        p->refpos_run = size;
455
4.90k
        refpos[size++] = 1;
456
4.90k
    }
457
8.94k
    else {
458
8.94k
        p->refpos_run = 0;
459
8.94k
        if (gap < 255) {
460
8.10k
            refpos[size++] = (unsigned char)gap;
461
8.10k
        }
462
839
        else {
463
839
            refpos[size++] = 255;
464
839
            memcpy(refpos + size, &gap, sizeof(gap));
465
839
            size += sizeof(gap);
466
839
        }
467
8.94k
    }
468
13.8k
    p->refpos_size = size;
469
13.8k
    return 1;
470
13.8k
}
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
50.3k
{
501
50.3k
    _Py_hashtable_entry_t *entry;
502
503
50.3k
    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
50.3k
    if (_PyObject_IsUniquelyReferenced(v)) {
513
13.2k
        return 0;
514
13.2k
    }
515
516
37.0k
    entry = _Py_hashtable_get_entry(p->hashtable, v);
517
37.0k
    if (entry != NULL) {
518
        /* write the reference index to the stream */
519
23.5k
        uintptr_t w = (uintptr_t)entry->value;
520
23.5k
        if (w & W_ENTRY_ACTIVE) {
521
0
            PyErr_Format(PyExc_ValueError, "cannot marshal recursion %T objects", v);
522
0
            goto err;
523
0
        }
524
23.5k
        if (!(w & W_ENTRY_SHARED)) {
525
7.00k
            entry->value = (void *)(w | W_ENTRY_SHARED);
526
7.00k
            p->refs[w >> W_ENTRY_SHIFT] |= W_REF_SHARED;
527
7.00k
        }
528
23.5k
        w >>= W_ENTRY_SHIFT;
529
23.5k
        assert(w < p->hashtable->nentries);
530
23.5k
        if (p->end - p->ptr < 5 && !w_reserve(p, 5)) {
531
0
            return 1;
532
0
        }
533
23.5k
        if (!w_add_refpos(p)) {
534
0
            goto err;
535
0
        }
536
23.5k
        *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
23.5k
        w_put_uint32(p->ptr, (uint32_t)w);
540
23.5k
        p->ptr += 4;
541
23.5k
        return 1;
542
23.5k
    } else {
543
13.5k
        size_t w = p->hashtable->nentries;
544
        /* we don't support long indices */
545
13.5k
        if (w >= W_MAX_REFS) {
546
0
            PyErr_SetString(PyExc_ValueError, "too many objects");
547
0
            goto err;
548
0
        }
549
13.5k
        size_t *refs = w_array_grow(p->refs, w, &p->refs_allocated,
550
13.5k
                                    sizeof(*refs));
551
13.5k
        if (refs == NULL) {
552
0
            PyErr_NoMemory();
553
0
            goto err;
554
0
        }
555
13.5k
        p->refs = refs;
556
13.5k
        refs[w] = (size_t)(p->ptr - p->buf) << 1;
557
13.5k
        uintptr_t value = (uintptr_t)w << W_ENTRY_SHIFT;
558
        // Corresponding code should call w_complete() after
559
        // writing the object.
560
13.5k
        if (PyTuple_CheckExact(v) || PyCode_Check(v) || PySlice_Check(v) ||
561
12.3k
            PyFrozenDict_CheckExact(v))
562
1.14k
        {
563
1.14k
            value |= W_ENTRY_ACTIVE;
564
1.14k
        }
565
13.5k
        if (_Py_hashtable_set(p->hashtable, Py_NewRef(v),
566
13.5k
                              (void *)value) < 0) {
567
0
            Py_DECREF(v);
568
0
            PyErr_NoMemory();
569
0
            goto err;
570
0
        }
571
13.5k
        return 0;
572
13.5k
    }
573
0
err:
574
0
    p->error = true;
575
0
    return 1;
576
37.0k
}
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
178
{
583
178
    if (p->error || p->refpos == NULL) {
584
37
        return;
585
37
    }
586
178
    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
141
    size_t nrefs = p->hashtable->nentries;
590
141
    size_t *refs = p->refs;
591
141
    uint32_t index = 0;
592
13.6k
    for (size_t i = 0; i < nrefs; i++) {
593
13.4k
        size_t shared = refs[i] & W_REF_SHARED;
594
13.4k
        char *type = p->buf + (refs[i] >> 1);
595
13.4k
        assert(!(*type & FLAG_REF));
596
        /* No branch on shared: it would not be predictable. */
597
13.4k
        *type |= (char)(-(int)shared & FLAG_REF);
598
13.4k
        refs[i] = index;
599
13.4k
        index += (uint32_t)shared;
600
#ifdef Py_DEBUG
601
        if (!shared) {
602
            refs[i] = (size_t)-1;
603
        }
604
#endif
605
13.4k
    }
606
141
    const unsigned char *pos = p->refpos;
607
141
    const unsigned char *end = pos + p->refpos_size;
608
141
    char *ptr = p->buf;
609
13.9k
    while (pos < end) {
610
13.8k
        size_t gap = *pos++;
611
13.8k
        size_t count = 1;
612
13.8k
        if (gap == 0) {
613
4.90k
            count = *pos++;
614
4.90k
        }
615
8.94k
        else if (gap == 255) {
616
839
            memcpy(&gap, pos, sizeof(gap));
617
839
            pos += sizeof(gap);
618
839
        }
619
13.8k
        ptr += gap;
620
23.5k
        do {
621
23.5k
            assert(ptr + 5 <= p->ptr);
622
23.5k
            assert(*ptr == TYPE_REF);
623
23.5k
            uint32_t w = w_get_uint32(ptr + 1);
624
23.5k
            assert(w < nrefs);
625
23.5k
            assert(refs[w] < index);
626
23.5k
            w_put_uint32(ptr + 1, (uint32_t)refs[w]);
627
23.5k
            ptr += 5;
628
23.5k
        } while (--count);
629
13.8k
    }
630
141
}
631
632
static void
633
w_complete(PyObject *v, WFILE *p)
634
7.59k
{
635
7.59k
    if (p->version < 3 || p->hashtable == NULL) {
636
0
        return;
637
0
    }
638
7.59k
    if (_PyObject_IsUniquelyReferenced(v)) {
639
6.44k
        return;
640
6.44k
    }
641
642
1.14k
    _Py_hashtable_entry_t *entry = _Py_hashtable_get_entry(p->hashtable, v);
643
1.14k
    if (entry == NULL) {
644
0
        return;
645
0
    }
646
1.14k
    assert(entry != NULL);
647
1.14k
    uintptr_t w = (uintptr_t)entry->value;
648
1.14k
    assert(w & W_ENTRY_ACTIVE);
649
1.14k
    w &= ~W_ENTRY_ACTIVE;
650
1.14k
    entry->value = (void *)w;
651
1.14k
}
652
653
static void
654
w_complex_object(PyObject *v, WFILE *p);
655
656
static void
657
w_object(PyObject *v, WFILE *p)
658
50.7k
{
659
50.7k
    if (p->error) {
660
0
        return;
661
0
    }
662
663
50.7k
    p->depth++;
664
665
50.7k
    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
50.7k
    else if (v == NULL) {
671
0
        w_byte(TYPE_NULL, p);
672
0
    }
673
50.7k
    else if (v == Py_None) {
674
248
        w_byte(TYPE_NONE, p);
675
248
    }
676
50.4k
    else if (v == PyExc_StopIteration) {
677
0
        w_byte(TYPE_STOPITER, p);
678
0
    }
679
50.4k
    else if (v == Py_Ellipsis) {
680
1
        w_byte(TYPE_ELLIPSIS, p);
681
1
    }
682
50.4k
    else if (v == Py_False) {
683
123
        w_byte(TYPE_FALSE, p);
684
123
    }
685
50.3k
    else if (v == Py_True) {
686
26
        w_byte(TYPE_TRUE, p);
687
26
    }
688
50.3k
    else if (!w_ref(v, p))
689
26.7k
        w_complex_object(v, p);
690
691
50.7k
    p->depth--;
692
50.7k
}
693
694
static void
695
w_complex_object(PyObject *v, WFILE *p)
696
26.7k
{
697
26.7k
    Py_ssize_t i, n;
698
699
26.7k
    if (PyLong_CheckExact(v)) {
700
2.30k
        int overflow;
701
2.30k
        long x = PyLong_AsLongAndOverflow(v, &overflow);
702
2.30k
        if (overflow) {
703
3
            w_PyLong((PyLongObject *)v, p);
704
3
        }
705
2.29k
        else {
706
2.29k
#if SIZEOF_LONG > 4
707
2.29k
            long y = Py_ARITHMETIC_RIGHT_SHIFT(long, x, 31);
708
2.29k
            if (y && y != -1) {
709
                /* Too large for TYPE_INT */
710
2
                w_PyLong((PyLongObject*)v, p);
711
2
            }
712
2.29k
            else
713
2.29k
#endif
714
2.29k
            {
715
2.29k
                W_TYPE(TYPE_INT, p);
716
2.29k
                w_long(x, p);
717
2.29k
            }
718
2.29k
        }
719
2.30k
    }
720
24.4k
    else if (PyFloat_CheckExact(v)) {
721
7
        if (p->version > 1) {
722
7
            W_TYPE(TYPE_BINARY_FLOAT, p);
723
7
            w_float_bin(PyFloat_AS_DOUBLE(v), p);
724
7
        }
725
0
        else {
726
0
            W_TYPE(TYPE_FLOAT, p);
727
0
            w_float_str(PyFloat_AS_DOUBLE(v), p);
728
0
        }
729
7
    }
730
24.4k
    else if (PyComplex_CheckExact(v)) {
731
0
        if (p->version > 1) {
732
0
            W_TYPE(TYPE_BINARY_COMPLEX, p);
733
0
            w_float_bin(PyComplex_RealAsDouble(v), p);
734
0
            w_float_bin(PyComplex_ImagAsDouble(v), p);
735
0
        }
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
0
    }
742
24.4k
    else if (PyBytes_CheckExact(v)) {
743
6.01k
        W_TYPE(TYPE_STRING, p);
744
6.01k
        w_pstring(PyBytes_AS_STRING(v), PyBytes_GET_SIZE(v), p);
745
6.01k
    }
746
18.4k
    else if (PyUnicode_CheckExact(v)) {
747
10.8k
        if (p->version >= 4 && PyUnicode_IS_ASCII(v)) {
748
10.7k
            int is_short = PyUnicode_GET_LENGTH(v) < 256;
749
10.7k
            if (is_short) {
750
10.6k
                if (PyUnicode_CHECK_INTERNED(v))
751
10.6k
                    W_TYPE(TYPE_SHORT_ASCII_INTERNED, p);
752
938
                else
753
10.6k
                    W_TYPE(TYPE_SHORT_ASCII, p);
754
10.6k
                w_short_pstring(PyUnicode_1BYTE_DATA(v),
755
10.6k
                                PyUnicode_GET_LENGTH(v), p);
756
10.6k
            }
757
103
            else {
758
103
                if (PyUnicode_CHECK_INTERNED(v))
759
103
                    W_TYPE(TYPE_ASCII_INTERNED, p);
760
103
                else
761
103
                    W_TYPE(TYPE_ASCII, p);
762
103
                w_pstring(PyUnicode_1BYTE_DATA(v),
763
103
                          PyUnicode_GET_LENGTH(v), p);
764
103
            }
765
10.7k
        }
766
71
        else {
767
71
            PyObject *utf8;
768
71
            utf8 = PyUnicode_AsEncodedString(v, "utf8", "surrogatepass");
769
71
            if (utf8 == NULL) {
770
0
                p->depth--;
771
0
                p->error = true;
772
0
                return;
773
0
            }
774
71
            if (p->version >= 3 &&  PyUnicode_CHECK_INTERNED(v))
775
71
                W_TYPE(TYPE_INTERNED, p);
776
71
            else
777
71
                W_TYPE(TYPE_UNICODE, p);
778
71
            w_pstring(PyBytes_AS_STRING(utf8), PyBytes_GET_SIZE(utf8), p);
779
71
            Py_DECREF(utf8);
780
71
        }
781
10.8k
    }
782
7.59k
    else if (PyTuple_CheckExact(v)) {
783
5.37k
        n = PyTuple_GET_SIZE(v);
784
5.37k
        if (p->version >= 4 && n < 256) {
785
5.37k
            W_TYPE(TYPE_SMALL_TUPLE, p);
786
5.37k
            w_byte((unsigned char)n, p);
787
5.37k
        }
788
0
        else {
789
0
            W_TYPE(TYPE_TUPLE, p);
790
0
            W_SIZE(n, p);
791
0
        }
792
33.8k
        for (i = 0; i < n; i++) {
793
28.4k
            w_object(PyTuple_GET_ITEM(v, i), p);
794
28.4k
        }
795
5.37k
        w_complete(v, p);
796
5.37k
    }
797
2.22k
    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.22k
    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.22k
    else if (PyAnySet_CheckExact(v)) {
835
6
        PyObject *value;
836
6
        Py_ssize_t pos = 0;
837
6
        Py_hash_t hash;
838
839
6
        if (PyFrozenSet_CheckExact(v))
840
6
            W_TYPE(TYPE_FROZENSET, p);
841
0
        else
842
6
            W_TYPE(TYPE_SET, p);
843
6
        n = PySet_GET_SIZE(v);
844
6
        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
6
        PyObject *items = PyList_New(n);
854
6
        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
6
        Py_ssize_t i = 0;
863
6
        bool changed = false;
864
6
        Py_BEGIN_CRITICAL_SECTION(v);
865
43
        while (_PySet_NextEntryRef(v, &pos, &value, &hash)) {
866
37
            if (i == n) {
867
0
                changed = true;
868
0
                Py_DECREF(value);
869
0
                break;
870
0
            }
871
37
            PyObject *dump = _PyMarshal_WriteObjectToString(value,
872
37
                                    p->version, p->allow_code);
873
37
            if (dump == NULL) {
874
0
                p->error = true;
875
0
                Py_DECREF(value);
876
0
                break;
877
0
            }
878
37
            PyObject *index = PyLong_FromSsize_t(i);
879
37
            PyObject *item = NULL;
880
37
            if (index != NULL) {
881
37
                item = PyTuple_Pack(3, dump, index, value);
882
37
                Py_DECREF(index);
883
37
            }
884
37
            Py_DECREF(dump);
885
37
            Py_DECREF(value);
886
37
            if (item == NULL) {
887
0
                p->error = true;
888
0
                break;
889
0
            }
890
37
            PyList_SET_ITEM(items, i++, item);
891
37
        }
892
6
        Py_END_CRITICAL_SECTION();
893
6
        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
6
        if (p->error) {
899
0
            Py_DECREF(items);
900
0
            return;
901
0
        }
902
6
        if (PyList_Sort(items)) {
903
0
            p->error = true;
904
0
            Py_DECREF(items);
905
0
            return;
906
0
        }
907
43
        for (Py_ssize_t i = 0; i < n; i++) {
908
37
            PyObject *item = PyList_GET_ITEM(items, i);
909
37
            value = PyTuple_GET_ITEM(item, 2);
910
37
            w_object(value, p);
911
37
        }
912
6
        Py_DECREF(items);
913
6
    }
914
2.21k
    else if (PyCode_Check(v)) {
915
2.19k
        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.19k
        PyCodeObject *co = (PyCodeObject *)v;
922
2.19k
        PyObject *co_code = _PyCode_GetCode(co);
923
2.19k
        if (co_code == NULL) {
924
0
            p->error = true;
925
0
            return;
926
0
        }
927
2.19k
        W_TYPE(TYPE_CODE, p);
928
2.19k
        w_long(co->co_argcount, p);
929
2.19k
        w_long(co->co_posonlyargcount, p);
930
2.19k
        w_long(co->co_kwonlyargcount, p);
931
2.19k
        w_long(co->co_stacksize, p);
932
2.19k
        w_long(co->co_flags, p);
933
2.19k
        w_object(co_code, p);
934
2.19k
        w_object(co->co_consts, p);
935
2.19k
        w_object(co->co_names, p);
936
2.19k
        w_object(co->co_localsplusnames, p);
937
2.19k
        w_object(co->co_localspluskinds, p);
938
2.19k
        w_object(co->co_filename, p);
939
2.19k
        w_object(co->co_name, p);
940
2.19k
        w_object(co->co_qualname, p);
941
2.19k
        w_long(co->co_firstlineno, p);
942
2.19k
        w_object(co->co_linetable, p);
943
2.19k
        w_object(co->co_exceptiontable, p);
944
2.19k
        Py_DECREF(co_code);
945
2.19k
        w_complete(v, p);
946
2.19k
    }
947
20
    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
20
    else if (PySlice_Check(v)) {
961
20
        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
20
        PySliceObject *slice = (PySliceObject *)v;
970
20
        W_TYPE(TYPE_SLICE, p);
971
20
        w_object(slice->start, p);
972
20
        w_object(slice->stop, p);
973
20
        w_object(slice->step, p);
974
20
        w_complete(v, p);
975
20
    }
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
26.7k
}
982
983
static void
984
w_decref_entry(void *key)
985
13.5k
{
986
13.5k
    PyObject *entry_key = (PyObject *)key;
987
13.5k
    Py_XDECREF(entry_key);
988
13.5k
}
989
990
static int
991
w_init_refs(WFILE *wf, int version)
992
178
{
993
178
    if (version >= 3) {
994
178
        wf->hashtable = _Py_hashtable_new_full(_Py_hashtable_hash_ptr,
995
178
                                               _Py_hashtable_compare_direct,
996
178
                                               w_decref_entry, NULL, NULL);
997
178
        if (wf->hashtable == NULL) {
998
0
            PyErr_NoMemory();
999
0
            return -1;
1000
0
        }
1001
178
    }
1002
178
    return 0;
1003
178
}
1004
1005
static void
1006
w_clear_refs(WFILE *wf)
1007
178
{
1008
178
    if (wf->hashtable != NULL) {
1009
178
        _Py_hashtable_destroy(wf->hashtable);
1010
178
    }
1011
178
    PyMem_Free(wf->refs);
1012
178
    PyMem_Free(wf->refpos);
1013
178
}
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.75M
{
1068
4.75M
    Py_ssize_t read = -1;
1069
1070
4.75M
    if (p->ptr != NULL) {
1071
        /* Fast path for loads() */
1072
4.75M
        const char *res = p->ptr;
1073
4.75M
        Py_ssize_t left = p->end - p->ptr;
1074
4.75M
        if (left < n) {
1075
0
            PyErr_SetString(PyExc_EOFError,
1076
0
                            "marshal data too short");
1077
0
            return NULL;
1078
0
        }
1079
4.75M
        p->ptr += n;
1080
4.75M
        return res;
1081
4.75M
    }
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.47M
{
1152
5.47M
    if (p->ptr != NULL) {
1153
5.47M
        if (p->ptr < p->end) {
1154
5.47M
            return (unsigned char) *p->ptr++;
1155
5.47M
        }
1156
5.47M
    }
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.47M
}
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.12M
{
1204
3.12M
    long x = -1;
1205
3.12M
    const unsigned char *buffer;
1206
1207
3.12M
    buffer = (const unsigned char *) r_string(4, p);
1208
3.12M
    if (buffer != NULL) {
1209
3.12M
        x = buffer[0];
1210
3.12M
        x |= (long)buffer[1] << 8;
1211
3.12M
        x |= (long)buffer[2] << 16;
1212
3.12M
        x |= (long)buffer[3] << 24;
1213
3.12M
#if SIZEOF_LONG > 4
1214
        /* Sign extension for 64-bit machines */
1215
3.12M
        x |= -(x & 0x80000000L);
1216
3.12M
#endif
1217
3.12M
    }
1218
3.12M
    return x;
1219
3.12M
}
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
601
{
1342
601
    const char *buf = r_string(8, p);
1343
601
    if (buf == NULL)
1344
0
        return -1;
1345
601
    return PyFloat_Unpack8(buf, 1);
1346
601
}
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
565k
{
1373
565k
    if (flag) { /* currently only FLAG_REF is defined */
1374
56.7k
        Py_ssize_t idx = PyList_GET_SIZE(p->refs);
1375
56.7k
        if (idx >= 0x7ffffffe) {
1376
0
            PyErr_SetString(PyExc_ValueError, "bad marshal data (index list too large)");
1377
0
            return -1;
1378
0
        }
1379
56.7k
        if (PyList_Append(p->refs, Py_None) < 0)
1380
0
            return -1;
1381
56.7k
        return idx;
1382
56.7k
    } else
1383
508k
        return 0;
1384
565k
}
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
565k
{
1397
565k
    if (o != NULL && flag) { /* currently only FLAG_REF is defined */
1398
56.7k
        PyObject *tmp = PyList_GET_ITEM(p->refs, idx);
1399
56.7k
        PyList_SET_ITEM(p->refs, idx, Py_NewRef(o));
1400
56.7k
        Py_DECREF(tmp);
1401
56.7k
    }
1402
565k
    return o;
1403
565k
}
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
444k
{
1412
444k
    assert(flag & FLAG_REF);
1413
444k
    if (o == NULL)
1414
0
        return NULL;
1415
444k
    if (PyList_Append(p->refs, o) < 0) {
1416
0
        Py_DECREF(o); /* release the new object */
1417
0
        return NULL;
1418
0
    }
1419
444k
    return o;
1420
444k
}
1421
1422
static PyObject *
1423
r_object(RFILE *p)
1424
3.93M
{
1425
    /* NULL is a valid return value, it does not necessarily means that
1426
       an exception is set. */
1427
3.93M
    PyObject *v, *v2;
1428
3.93M
    Py_ssize_t idx = 0;
1429
3.93M
    long i, n;
1430
3.93M
    int type, code = r_byte(p);
1431
3.93M
    int flag, is_interned = 0;
1432
3.93M
    PyObject *retval = NULL;
1433
1434
3.93M
    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
3.93M
    p->depth++;
1443
1444
3.93M
    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
3.93M
    flag = code & FLAG_REF;
1451
3.93M
    type = code & ~FLAG_REF;
1452
1453
3.93M
#define R_REF(O) do{\
1454
1.64M
    if (flag) \
1455
1.64M
        O = r_ref(O, flag, p);\
1456
1.64M
} while (0)
1457
1458
3.93M
    switch (type) {
1459
1460
0
    case TYPE_NULL:
1461
0
        break;
1462
1463
34.7k
    case TYPE_NONE:
1464
34.7k
        retval = Py_None;
1465
34.7k
        break;
1466
1467
0
    case TYPE_STOPITER:
1468
0
        retval = Py_NewRef(PyExc_StopIteration);
1469
0
        break;
1470
1471
450
    case TYPE_ELLIPSIS:
1472
450
        retval = Py_Ellipsis;
1473
450
        break;
1474
1475
1.75k
    case TYPE_FALSE:
1476
1.75k
        retval = Py_False;
1477
1.75k
        break;
1478
1479
1.56k
    case TYPE_TRUE:
1480
1.56k
        retval = Py_True;
1481
1.56k
        break;
1482
1483
23.9k
    case TYPE_INT:
1484
23.9k
        n = r_long(p);
1485
23.9k
        if (n == -1 && PyErr_Occurred()) {
1486
0
            break;
1487
0
        }
1488
23.9k
        retval = PyLong_FromLong(n);
1489
23.9k
        R_REF(retval);
1490
23.9k
        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
601
    case TYPE_BINARY_FLOAT:
1513
601
        {
1514
601
            double x = r_float_bin(p);
1515
601
            if (x == -1.0 && PyErr_Occurred())
1516
0
                break;
1517
601
            retval = PyFloat_FromDouble(x);
1518
601
            R_REF(retval);
1519
601
            break;
1520
601
        }
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
0
    case TYPE_BINARY_COMPLEX:
1537
0
        {
1538
0
            Py_complex c;
1539
0
            c.real = r_float_bin(p);
1540
0
            if (c.real == -1.0 && PyErr_Occurred())
1541
0
                break;
1542
0
            c.imag = r_float_bin(p);
1543
0
            if (c.imag == -1.0 && PyErr_Occurred())
1544
0
                break;
1545
0
            retval = PyComplex_FromCComplex(c);
1546
0
            R_REF(retval);
1547
0
            break;
1548
0
        }
1549
1550
465k
    case TYPE_STRING:
1551
465k
        {
1552
465k
            const char *ptr;
1553
465k
            n = r_long(p);
1554
465k
            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
465k
            ptr = r_string(n, p);
1562
465k
            if (ptr == NULL) {
1563
0
                break;
1564
0
            }
1565
            // Get a singleton for 1-byte string
1566
465k
            retval = PyBytes_FromStringAndSize(ptr, n);  // can be NULL
1567
465k
            R_REF(retval);
1568
465k
            break;
1569
465k
        }
1570
1571
0
    case TYPE_ASCII_INTERNED:
1572
0
        is_interned = 1;
1573
0
        _Py_FALLTHROUGH;
1574
23.1k
    case TYPE_ASCII:
1575
23.1k
        n = r_long(p);
1576
23.1k
        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
23.1k
        goto _read_ascii;
1584
1585
988k
    case TYPE_SHORT_ASCII_INTERNED:
1586
988k
        is_interned = 1;
1587
988k
        _Py_FALLTHROUGH;
1588
1.12M
    case TYPE_SHORT_ASCII:
1589
1.12M
        n = r_byte(p);
1590
1.12M
        if (n == EOF) {
1591
0
            break;
1592
0
        }
1593
1.15M
    _read_ascii:
1594
1.15M
        {
1595
1.15M
            const char *ptr;
1596
1.15M
            ptr = r_string(n, p);
1597
1.15M
            if (ptr == NULL)
1598
0
                break;
1599
1.15M
            v = PyUnicode_FromKindAndData(PyUnicode_1BYTE_KIND, ptr, n);
1600
1.15M
            if (v == NULL)
1601
0
                break;
1602
1.15M
            if (is_interned) {
1603
                // marshal is meant to serialize .pyc files with code
1604
                // objects, and code-related strings are currently immortal.
1605
988k
                PyInterpreterState *interp = _PyInterpreterState_GET();
1606
988k
                _PyUnicode_InternImmortal(interp, &v);
1607
988k
            }
1608
1.15M
            retval = v;
1609
1.15M
            R_REF(retval);
1610
1.15M
            break;
1611
1.15M
        }
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
407k
    case TYPE_SMALL_TUPLE:
1651
407k
        n = r_byte(p);
1652
407k
        if (n == EOF) {
1653
0
            break;
1654
0
        }
1655
407k
        goto _read_tuple;
1656
407k
    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
407k
    _read_tuple:
1666
407k
        idx = r_ref_reserve(flag, p);
1667
407k
        if (idx < 0)
1668
0
            break;
1669
407k
        v = PyTuple_New(n);
1670
407k
        if (v == NULL)
1671
0
            break;
1672
1673
2.78M
        for (i = 0; i < n; i++) {
1674
2.37M
            v2 = r_object(p);
1675
2.37M
            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.37M
            PyTuple_SET_ITEM(v, i, v2);
1683
2.37M
        }
1684
407k
        retval = r_ref_insert(v, idx, flag, p);
1685
407k
        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
442
    case TYPE_FROZENSET:
1763
442
        n = r_long(p);
1764
442
        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
442
        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
442
        else {
1781
442
            v = (type == TYPE_SET) ? PySet_New(NULL) : PyFrozenSet_New(NULL);
1782
442
            if (type == TYPE_SET) {
1783
0
                R_REF(v);
1784
442
            } else {
1785
                /* must use delayed registration of frozensets because they must
1786
                 * be init with a refcount of 1
1787
                 */
1788
442
                idx = r_ref_reserve(flag, p);
1789
442
                if (idx < 0)
1790
0
                    Py_CLEAR(v); /* signal error */
1791
442
            }
1792
442
            if (v == NULL)
1793
0
                break;
1794
1795
2.35k
            for (i = 0; i < n; i++) {
1796
1.91k
                v2 = r_object(p);
1797
1.91k
                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.91k
                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.91k
                Py_DECREF(v2);
1811
1.91k
            }
1812
442
            if (type != TYPE_SET)
1813
442
                v = r_ref_insert(v, idx, flag, p);
1814
442
            retval = v;
1815
442
        }
1816
442
        break;
1817
1818
153k
    case TYPE_CODE:
1819
153k
        {
1820
153k
            int argcount;
1821
153k
            int posonlyargcount;
1822
153k
            int kwonlyargcount;
1823
153k
            int stacksize;
1824
153k
            int flags;
1825
153k
            PyObject *code = NULL;
1826
153k
            PyObject *consts = NULL;
1827
153k
            PyObject *names = NULL;
1828
153k
            PyObject *localsplusnames = NULL;
1829
153k
            PyObject *localspluskinds = NULL;
1830
153k
            PyObject *filename = NULL;
1831
153k
            PyObject *name = NULL;
1832
153k
            PyObject *qualname = NULL;
1833
153k
            int firstlineno;
1834
153k
            PyObject* linetable = NULL;
1835
153k
            PyObject *exceptiontable = NULL;
1836
1837
153k
            if (!p->allow_code) {
1838
0
                PyErr_SetString(PyExc_ValueError,
1839
0
                                "unmarshalling code objects is disallowed");
1840
0
                break;
1841
0
            }
1842
153k
            idx = r_ref_reserve(flag, p);
1843
153k
            if (idx < 0)
1844
0
                break;
1845
1846
153k
            v = NULL;
1847
1848
            /* XXX ignore long->int overflows for now */
1849
153k
            argcount = (int)r_long(p);
1850
153k
            if (argcount == -1 && PyErr_Occurred())
1851
0
                goto code_error;
1852
153k
            posonlyargcount = (int)r_long(p);
1853
153k
            if (posonlyargcount == -1 && PyErr_Occurred()) {
1854
0
                goto code_error;
1855
0
            }
1856
153k
            kwonlyargcount = (int)r_long(p);
1857
153k
            if (kwonlyargcount == -1 && PyErr_Occurred())
1858
0
                goto code_error;
1859
153k
            stacksize = (int)r_long(p);
1860
153k
            if (stacksize == -1 && PyErr_Occurred())
1861
0
                goto code_error;
1862
153k
            flags = (int)r_long(p);
1863
153k
            if (flags == -1 && PyErr_Occurred())
1864
0
                goto code_error;
1865
153k
            code = r_object(p);
1866
153k
            if (code == NULL)
1867
0
                goto code_error;
1868
153k
            consts = r_object(p);
1869
153k
            if (consts == NULL)
1870
0
                goto code_error;
1871
153k
            names = r_object(p);
1872
153k
            if (names == NULL)
1873
0
                goto code_error;
1874
153k
            localsplusnames = r_object(p);
1875
153k
            if (localsplusnames == NULL)
1876
0
                goto code_error;
1877
153k
            localspluskinds = r_object(p);
1878
153k
            if (localspluskinds == NULL)
1879
0
                goto code_error;
1880
153k
            filename = r_object(p);
1881
153k
            if (filename == NULL)
1882
0
                goto code_error;
1883
153k
            name = r_object(p);
1884
153k
            if (name == NULL)
1885
0
                goto code_error;
1886
153k
            qualname = r_object(p);
1887
153k
            if (qualname == NULL)
1888
0
                goto code_error;
1889
153k
            firstlineno = (int)r_long(p);
1890
153k
            if (firstlineno == -1 && PyErr_Occurred())
1891
0
                goto code_error;
1892
153k
            linetable = r_object(p);
1893
153k
            if (linetable == NULL)
1894
0
                goto code_error;
1895
153k
            exceptiontable = r_object(p);
1896
153k
            if (exceptiontable == NULL)
1897
0
                goto code_error;
1898
1899
153k
            struct _PyCodeConstructor con = {
1900
153k
                .filename = filename,
1901
153k
                .name = name,
1902
153k
                .qualname = qualname,
1903
153k
                .flags = flags,
1904
1905
153k
                .code = code,
1906
153k
                .firstlineno = firstlineno,
1907
153k
                .linetable = linetable,
1908
1909
153k
                .consts = consts,
1910
153k
                .names = names,
1911
1912
153k
                .localsplusnames = localsplusnames,
1913
153k
                .localspluskinds = localspluskinds,
1914
1915
153k
                .argcount = argcount,
1916
153k
                .posonlyargcount = posonlyargcount,
1917
153k
                .kwonlyargcount = kwonlyargcount,
1918
1919
153k
                .stacksize = stacksize,
1920
1921
153k
                .exceptiontable = exceptiontable,
1922
153k
            };
1923
1924
153k
            if (_PyCode_Validate(&con) < 0) {
1925
0
                goto code_error;
1926
0
            }
1927
1928
153k
            v = (PyObject *)_PyCode_New(&con);
1929
153k
            if (v == NULL) {
1930
0
                goto code_error;
1931
0
            }
1932
1933
153k
            v = r_ref_insert(v, idx, flag, p);
1934
1935
153k
          code_error:
1936
153k
            if (v == NULL && !PyErr_Occurred()) {
1937
0
                PyErr_SetString(PyExc_TypeError,
1938
0
                    "NULL object in marshal data for code object");
1939
0
            }
1940
153k
            Py_XDECREF(code);
1941
153k
            Py_XDECREF(consts);
1942
153k
            Py_XDECREF(names);
1943
153k
            Py_XDECREF(localsplusnames);
1944
153k
            Py_XDECREF(localspluskinds);
1945
153k
            Py_XDECREF(filename);
1946
153k
            Py_XDECREF(name);
1947
153k
            Py_XDECREF(qualname);
1948
153k
            Py_XDECREF(linetable);
1949
153k
            Py_XDECREF(exceptiontable);
1950
153k
        }
1951
0
        retval = v;
1952
153k
        break;
1953
1954
1.68M
    case TYPE_REF:
1955
1.68M
        n = r_long(p);
1956
1.68M
        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.68M
        v = PyList_GET_ITEM(p->refs, n);
1964
1.68M
        if (v == Py_None) {
1965
0
            PyErr_SetString(PyExc_ValueError, "bad marshal data (invalid reference)");
1966
0
            break;
1967
0
        }
1968
1.68M
        retval = Py_NewRef(v);
1969
1.68M
        break;
1970
1971
3.15k
    case TYPE_SLICE:
1972
3.15k
    {
1973
3.15k
        Py_ssize_t idx = r_ref_reserve(flag, p);
1974
3.15k
        if (idx < 0) {
1975
0
            break;
1976
0
        }
1977
3.15k
        PyObject *stop = NULL;
1978
3.15k
        PyObject *step = NULL;
1979
3.15k
        PyObject *start = r_object(p);
1980
3.15k
        if (start == NULL) {
1981
0
            goto cleanup;
1982
0
        }
1983
3.15k
        stop = r_object(p);
1984
3.15k
        if (stop == NULL) {
1985
0
            goto cleanup;
1986
0
        }
1987
3.15k
        step = r_object(p);
1988
3.15k
        if (step == NULL) {
1989
0
            goto cleanup;
1990
0
        }
1991
3.15k
        retval = PySlice_New(start, stop, step);
1992
3.15k
        r_ref_insert(retval, idx, flag, p);
1993
3.15k
    cleanup:
1994
3.15k
        Py_XDECREF(start);
1995
3.15k
        Py_XDECREF(stop);
1996
3.15k
        Py_XDECREF(step);
1997
3.15k
        break;
1998
3.15k
    }
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
3.93M
    }
2007
3.93M
    p->depth--;
2008
3.93M
    return retval;
2009
3.93M
}
2010
2011
static PyObject *
2012
read_object(RFILE *p)
2013
5.81k
{
2014
5.81k
    PyObject *v;
2015
5.81k
    if (PyErr_Occurred()) {
2016
0
        fprintf(stderr, "XXX readobject called with exception set\n");
2017
0
        return NULL;
2018
0
    }
2019
5.81k
    if (p->ptr && p->end) {
2020
5.81k
        if (PySys_Audit("marshal.loads", "y#", p->ptr, (Py_ssize_t)(p->end - p->ptr)) < 0) {
2021
0
            return NULL;
2022
0
        }
2023
5.81k
    } else if (p->fp || p->readable) {
2024
0
        if (PySys_Audit("marshal.load", NULL) < 0) {
2025
0
            return NULL;
2026
0
        }
2027
0
    }
2028
5.81k
    v = r_object(p);
2029
5.81k
    if (v == NULL && !PyErr_Occurred())
2030
0
        PyErr_SetString(PyExc_TypeError, "NULL object in marshal data for object");
2031
5.81k
    return v;
2032
5.81k
}
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
178
{
2167
178
    WFILE wf;
2168
2169
178
    if (PySys_Audit("marshal.dumps", "Oi", x, version) < 0) {
2170
0
        return NULL;
2171
0
    }
2172
178
    memset(&wf, 0, sizeof(wf));
2173
178
    wf.str = PyBytes_FromStringAndSize((char *)NULL, 50);
2174
178
    if (wf.str == NULL)
2175
0
        return NULL;
2176
178
    wf.ptr = wf.buf = PyBytes_AS_STRING(wf.str);
2177
178
    wf.end = wf.ptr + PyBytes_GET_SIZE(wf.str);
2178
178
    wf.error = false;
2179
178
    wf.version = version;
2180
178
    wf.allow_code = allow_code;
2181
178
    if (w_init_refs(&wf, version)) {
2182
0
        Py_DECREF(wf.str);
2183
0
        return NULL;
2184
0
    }
2185
178
    w_object(x, &wf);
2186
178
    w_resolve_refs(&wf);
2187
178
    w_clear_refs(&wf);
2188
178
    if (wf.str != NULL) {
2189
178
        const char *base = PyBytes_AS_STRING(wf.str);
2190
178
        if (_PyBytes_Resize(&wf.str, (Py_ssize_t)(wf.ptr - base)) < 0)
2191
0
            return NULL;
2192
178
    }
2193
178
    if (wf.error) {
2194
0
        assert(PyErr_Occurred());
2195
0
        Py_XDECREF(wf.str);
2196
0
        return NULL;
2197
0
    }
2198
178
    return wf.str;
2199
178
}
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
141
{
2332
141
    return _PyMarshal_WriteObjectToString(value, version, allow_code);
2333
141
}
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.24k
{
2354
5.24k
    RFILE rf;
2355
5.24k
    char *s = bytes->buf;
2356
5.24k
    Py_ssize_t n = bytes->len;
2357
5.24k
    PyObject* result;
2358
5.24k
    rf.allow_code = allow_code;
2359
5.24k
    rf.fp = NULL;
2360
5.24k
    rf.readable = NULL;
2361
5.24k
    rf.ptr = s;
2362
5.24k
    rf.end = s + n;
2363
5.24k
    rf.depth = 0;
2364
5.24k
    if ((rf.refs = PyList_New(0)) == NULL)
2365
0
        return NULL;
2366
5.24k
    result = read_object(&rf);
2367
5.24k
    Py_DECREF(rf.refs);
2368
5.24k
    return result;
2369
5.24k
}
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
}