Coverage Report

Created: 2025-11-24 06:11

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