Coverage Report

Created: 2026-12-01 06:09

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