~ubuntu-branches/ubuntu/trusty/python3.4/trusty-proposed

« back to all changes in this revision

Viewing changes to Python/marshal.c

  • Committer: Package Import Robot
  • Author(s): Matthias Klose
  • Date: 2013-11-25 09:44:27 UTC
  • Revision ID: package-import@ubuntu.com-20131125094427-lzxj8ap5w01lmo7f
Tags: upstream-3.4~b1
Import upstream version 3.4~b1

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
 
 
2
/* Write Python objects to files and read them back.
 
3
   This is primarily intended for writing and reading compiled Python code,
 
4
   even though dicts, lists, sets and frozensets, not commonly seen in
 
5
   code objects, are supported.
 
6
   Version 3 of this protocol properly supports circular links
 
7
   and sharing. */
 
8
 
 
9
#define PY_SSIZE_T_CLEAN
 
10
 
 
11
#include "Python.h"
 
12
#include "longintrepr.h"
 
13
#include "code.h"
 
14
#include "marshal.h"
 
15
 
 
16
#define ABS(x) ((x) < 0 ? -(x) : (x))
 
17
 
 
18
/* High water mark to determine when the marshalled object is dangerously deep
 
19
 * and risks coring the interpreter.  When the object stack gets this deep,
 
20
 * raise an exception instead of continuing.
 
21
 * On Windows debug builds, reduce this value.
 
22
 */
 
23
#if defined(MS_WINDOWS) && defined(_DEBUG)
 
24
#define MAX_MARSHAL_STACK_DEPTH 1500
 
25
#else
 
26
#define MAX_MARSHAL_STACK_DEPTH 2000
 
27
#endif
 
28
 
 
29
#define TYPE_NULL               '0'
 
30
#define TYPE_NONE               'N'
 
31
#define TYPE_FALSE              'F'
 
32
#define TYPE_TRUE               'T'
 
33
#define TYPE_STOPITER           'S'
 
34
#define TYPE_ELLIPSIS           '.'
 
35
#define TYPE_INT                'i'
 
36
#define TYPE_FLOAT              'f'
 
37
#define TYPE_BINARY_FLOAT       'g'
 
38
#define TYPE_COMPLEX            'x'
 
39
#define TYPE_BINARY_COMPLEX     'y'
 
40
#define TYPE_LONG               'l'
 
41
#define TYPE_STRING             's'
 
42
#define TYPE_INTERNED           't'
 
43
#define TYPE_REF                'r'
 
44
#define TYPE_TUPLE              '('
 
45
#define TYPE_LIST               '['
 
46
#define TYPE_DICT               '{'
 
47
#define TYPE_CODE               'c'
 
48
#define TYPE_UNICODE            'u'
 
49
#define TYPE_UNKNOWN            '?'
 
50
#define TYPE_SET                '<'
 
51
#define TYPE_FROZENSET          '>'
 
52
#define FLAG_REF                '\x80' /* with a type, add obj to index */
 
53
 
 
54
#define TYPE_ASCII              'a'
 
55
#define TYPE_ASCII_INTERNED     'A'
 
56
#define TYPE_SMALL_TUPLE        ')'
 
57
#define TYPE_SHORT_ASCII        'z'
 
58
#define TYPE_SHORT_ASCII_INTERNED 'Z'
 
59
 
 
60
#define WFERR_OK 0
 
61
#define WFERR_UNMARSHALLABLE 1
 
62
#define WFERR_NESTEDTOODEEP 2
 
63
#define WFERR_NOMEMORY 3
 
64
 
 
65
typedef struct {
 
66
    FILE *fp;
 
67
    int error;  /* see WFERR_* values */
 
68
    int depth;
 
69
    /* If fp == NULL, the following are valid: */
 
70
    PyObject *readable;    /* Stream-like object being read from */
 
71
    PyObject *str;
 
72
    PyObject *current_filename;
 
73
    char *ptr;
 
74
    char *end;
 
75
    char *buf;
 
76
    Py_ssize_t buf_size;
 
77
    PyObject *refs; /* dict on marshal, list on unmarshal */
 
78
    int version;
 
79
} WFILE;
 
80
 
 
81
#define w_byte(c, p) if (((p)->fp)) putc((c), (p)->fp); \
 
82
                      else if ((p)->ptr != (p)->end) *(p)->ptr++ = (c); \
 
83
                           else w_more((c), p)
 
84
 
 
85
static void
 
86
w_more(char c, WFILE *p)
 
87
{
 
88
    Py_ssize_t size, newsize;
 
89
    if (p->str == NULL)
 
90
        return; /* An error already occurred */
 
91
    size = PyBytes_Size(p->str);
 
92
    newsize = size + size + 1024;
 
93
    if (newsize > 32*1024*1024) {
 
94
        newsize = size + (size >> 3);           /* 12.5% overallocation */
 
95
    }
 
96
    if (_PyBytes_Resize(&p->str, newsize) != 0) {
 
97
        p->ptr = p->end = NULL;
 
98
    }
 
99
    else {
 
100
        p->ptr = PyBytes_AS_STRING((PyBytesObject *)p->str) + size;
 
101
        p->end =
 
102
            PyBytes_AS_STRING((PyBytesObject *)p->str) + newsize;
 
103
        *p->ptr++ = c;
 
104
    }
 
105
}
 
106
 
 
107
static void
 
108
w_string(const char *s, Py_ssize_t n, WFILE *p)
 
109
{
 
110
    if (p->fp != NULL) {
 
111
        fwrite(s, 1, n, p->fp);
 
112
    }
 
113
    else {
 
114
        while (--n >= 0) {
 
115
            w_byte(*s, p);
 
116
            s++;
 
117
        }
 
118
    }
 
119
}
 
120
 
 
121
static void
 
122
w_short(int x, WFILE *p)
 
123
{
 
124
    w_byte((char)( x      & 0xff), p);
 
125
    w_byte((char)((x>> 8) & 0xff), p);
 
126
}
 
127
 
 
128
static void
 
129
w_long(long x, WFILE *p)
 
130
{
 
131
    w_byte((char)( x      & 0xff), p);
 
132
    w_byte((char)((x>> 8) & 0xff), p);
 
133
    w_byte((char)((x>>16) & 0xff), p);
 
134
    w_byte((char)((x>>24) & 0xff), p);
 
135
}
 
136
 
 
137
#define SIZE32_MAX  0x7FFFFFFF
 
138
 
 
139
#if SIZEOF_SIZE_T > 4
 
140
# define W_SIZE(n, p)  do {                     \
 
141
        if ((n) > SIZE32_MAX) {                 \
 
142
            (p)->depth--;                       \
 
143
            (p)->error = WFERR_UNMARSHALLABLE;  \
 
144
            return;                             \
 
145
        }                                       \
 
146
        w_long((long)(n), p);                   \
 
147
    } while(0)
 
148
#else
 
149
# define W_SIZE  w_long
 
150
#endif
 
151
 
 
152
static void
 
153
w_pstring(const char *s, Py_ssize_t n, WFILE *p)
 
154
{
 
155
        W_SIZE(n, p);
 
156
        w_string(s, n, p);
 
157
}
 
158
 
 
159
static void
 
160
w_short_pstring(const char *s, Py_ssize_t n, WFILE *p)
 
161
{
 
162
    w_byte(Py_SAFE_DOWNCAST(n, Py_ssize_t, unsigned char), p);
 
163
    w_string(s, n, p);
 
164
}
 
165
 
 
166
/* We assume that Python ints are stored internally in base some power of
 
167
   2**15; for the sake of portability we'll always read and write them in base
 
168
   exactly 2**15. */
 
169
 
 
170
#define PyLong_MARSHAL_SHIFT 15
 
171
#define PyLong_MARSHAL_BASE ((short)1 << PyLong_MARSHAL_SHIFT)
 
172
#define PyLong_MARSHAL_MASK (PyLong_MARSHAL_BASE - 1)
 
173
#if PyLong_SHIFT % PyLong_MARSHAL_SHIFT != 0
 
174
#error "PyLong_SHIFT must be a multiple of PyLong_MARSHAL_SHIFT"
 
175
#endif
 
176
#define PyLong_MARSHAL_RATIO (PyLong_SHIFT / PyLong_MARSHAL_SHIFT)
 
177
 
 
178
#define W_TYPE(t, p) do { \
 
179
    w_byte((t) | flag, (p)); \
 
180
} while(0)
 
181
 
 
182
static void
 
183
w_PyLong(const PyLongObject *ob, char flag, WFILE *p)
 
184
{
 
185
    Py_ssize_t i, j, n, l;
 
186
    digit d;
 
187
 
 
188
    W_TYPE(TYPE_LONG, p);
 
189
    if (Py_SIZE(ob) == 0) {
 
190
        w_long((long)0, p);
 
191
        return;
 
192
    }
 
193
 
 
194
    /* set l to number of base PyLong_MARSHAL_BASE digits */
 
195
    n = ABS(Py_SIZE(ob));
 
196
    l = (n-1) * PyLong_MARSHAL_RATIO;
 
197
    d = ob->ob_digit[n-1];
 
198
    assert(d != 0); /* a PyLong is always normalized */
 
199
    do {
 
200
        d >>= PyLong_MARSHAL_SHIFT;
 
201
        l++;
 
202
    } while (d != 0);
 
203
    if (l > SIZE32_MAX) {
 
204
        p->depth--;
 
205
        p->error = WFERR_UNMARSHALLABLE;
 
206
        return;
 
207
    }
 
208
    w_long((long)(Py_SIZE(ob) > 0 ? l : -l), p);
 
209
 
 
210
    for (i=0; i < n-1; i++) {
 
211
        d = ob->ob_digit[i];
 
212
        for (j=0; j < PyLong_MARSHAL_RATIO; j++) {
 
213
            w_short(d & PyLong_MARSHAL_MASK, p);
 
214
            d >>= PyLong_MARSHAL_SHIFT;
 
215
        }
 
216
        assert (d == 0);
 
217
    }
 
218
    d = ob->ob_digit[n-1];
 
219
    do {
 
220
        w_short(d & PyLong_MARSHAL_MASK, p);
 
221
        d >>= PyLong_MARSHAL_SHIFT;
 
222
    } while (d != 0);
 
223
}
 
224
 
 
225
static int
 
226
w_ref(PyObject *v, char *flag, WFILE *p)
 
227
{
 
228
    PyObject *id;
 
229
    PyObject *idx;
 
230
 
 
231
    if (p->version < 3 || p->refs == NULL)
 
232
        return 0; /* not writing object references */
 
233
 
 
234
    /* if it has only one reference, it definitely isn't shared */
 
235
    if (Py_REFCNT(v) == 1)
 
236
        return 0;
 
237
 
 
238
    id = PyLong_FromVoidPtr((void*)v);
 
239
    if (id == NULL)
 
240
        goto err;
 
241
    idx = PyDict_GetItem(p->refs, id);
 
242
    if (idx != NULL) {
 
243
        /* write the reference index to the stream */
 
244
        long w = PyLong_AsLong(idx);
 
245
        Py_DECREF(id);
 
246
        if (w == -1 && PyErr_Occurred()) {
 
247
            goto err;
 
248
        }
 
249
        /* we don't store "long" indices in the dict */
 
250
        assert(0 <= w && w <= 0x7fffffff);
 
251
        w_byte(TYPE_REF, p);
 
252
        w_long(w, p);
 
253
        return 1;
 
254
    } else {
 
255
        int ok;
 
256
        Py_ssize_t s = PyDict_Size(p->refs);
 
257
        /* we don't support long indices */
 
258
        if (s >= 0x7fffffff) {
 
259
            PyErr_SetString(PyExc_ValueError, "too many objects");
 
260
            goto err;
 
261
        }
 
262
        idx = PyLong_FromSsize_t(s);
 
263
        ok = idx && PyDict_SetItem(p->refs, id, idx) == 0;
 
264
        Py_DECREF(id);
 
265
        Py_XDECREF(idx);
 
266
        if (!ok)
 
267
            goto err;
 
268
        *flag |= FLAG_REF;
 
269
        return 0;
 
270
    }
 
271
err:
 
272
    p->error = WFERR_UNMARSHALLABLE;
 
273
    return 1;
 
274
}
 
275
 
 
276
static void
 
277
w_complex_object(PyObject *v, char flag, WFILE *p);
 
278
 
 
279
static void
 
280
w_object(PyObject *v, WFILE *p)
 
281
{
 
282
    char flag = '\0';
 
283
 
 
284
    p->depth++;
 
285
 
 
286
    if (p->depth > MAX_MARSHAL_STACK_DEPTH) {
 
287
        p->error = WFERR_NESTEDTOODEEP;
 
288
    }
 
289
    else if (v == NULL) {
 
290
        w_byte(TYPE_NULL, p);
 
291
    }
 
292
    else if (v == Py_None) {
 
293
        w_byte(TYPE_NONE, p);
 
294
    }
 
295
    else if (v == PyExc_StopIteration) {
 
296
        w_byte(TYPE_STOPITER, p);
 
297
    }
 
298
    else if (v == Py_Ellipsis) {
 
299
        w_byte(TYPE_ELLIPSIS, p);
 
300
    }
 
301
    else if (v == Py_False) {
 
302
        w_byte(TYPE_FALSE, p);
 
303
    }
 
304
    else if (v == Py_True) {
 
305
        w_byte(TYPE_TRUE, p);
 
306
    }
 
307
    else if (!w_ref(v, &flag, p))
 
308
        w_complex_object(v, flag, p);
 
309
 
 
310
    p->depth--;
 
311
}
 
312
 
 
313
static void
 
314
w_complex_object(PyObject *v, char flag, WFILE *p)
 
315
{
 
316
    Py_ssize_t i, n;
 
317
 
 
318
    if (PyLong_CheckExact(v)) {
 
319
        long x = PyLong_AsLong(v);
 
320
        if ((x == -1)  && PyErr_Occurred()) {
 
321
            PyLongObject *ob = (PyLongObject *)v;
 
322
            PyErr_Clear();
 
323
            w_PyLong(ob, flag, p);
 
324
        }
 
325
        else {
 
326
#if SIZEOF_LONG > 4
 
327
            long y = Py_ARITHMETIC_RIGHT_SHIFT(long, x, 31);
 
328
            if (y && y != -1) {
 
329
                /* Too large for TYPE_INT */
 
330
                w_PyLong((PyLongObject*)v, flag, p);
 
331
            }
 
332
            else
 
333
#endif
 
334
            {
 
335
                W_TYPE(TYPE_INT, p);
 
336
                w_long(x, p);
 
337
            }
 
338
        }
 
339
    }
 
340
    else if (PyFloat_CheckExact(v)) {
 
341
        if (p->version > 1) {
 
342
            unsigned char buf[8];
 
343
            if (_PyFloat_Pack8(PyFloat_AsDouble(v),
 
344
                               buf, 1) < 0) {
 
345
                p->error = WFERR_UNMARSHALLABLE;
 
346
                return;
 
347
            }
 
348
            W_TYPE(TYPE_BINARY_FLOAT, p);
 
349
            w_string((char*)buf, 8, p);
 
350
        }
 
351
        else {
 
352
            char *buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
 
353
                                              'g', 17, 0, NULL);
 
354
            if (!buf) {
 
355
                p->error = WFERR_NOMEMORY;
 
356
                return;
 
357
            }
 
358
            n = strlen(buf);
 
359
            W_TYPE(TYPE_FLOAT, p);
 
360
            w_byte((int)n, p);
 
361
            w_string(buf, n, p);
 
362
            PyMem_Free(buf);
 
363
        }
 
364
    }
 
365
    else if (PyComplex_CheckExact(v)) {
 
366
        if (p->version > 1) {
 
367
            unsigned char buf[8];
 
368
            if (_PyFloat_Pack8(PyComplex_RealAsDouble(v),
 
369
                               buf, 1) < 0) {
 
370
                p->error = WFERR_UNMARSHALLABLE;
 
371
                return;
 
372
            }
 
373
            W_TYPE(TYPE_BINARY_COMPLEX, p);
 
374
            w_string((char*)buf, 8, p);
 
375
            if (_PyFloat_Pack8(PyComplex_ImagAsDouble(v),
 
376
                               buf, 1) < 0) {
 
377
                p->error = WFERR_UNMARSHALLABLE;
 
378
                return;
 
379
            }
 
380
            w_string((char*)buf, 8, p);
 
381
        }
 
382
        else {
 
383
            char *buf;
 
384
            W_TYPE(TYPE_COMPLEX, p);
 
385
            buf = PyOS_double_to_string(PyComplex_RealAsDouble(v),
 
386
                                        'g', 17, 0, NULL);
 
387
            if (!buf) {
 
388
                p->error = WFERR_NOMEMORY;
 
389
                return;
 
390
            }
 
391
            n = strlen(buf);
 
392
            w_byte((int)n, p);
 
393
            w_string(buf, n, p);
 
394
            PyMem_Free(buf);
 
395
            buf = PyOS_double_to_string(PyComplex_ImagAsDouble(v),
 
396
                                        'g', 17, 0, NULL);
 
397
            if (!buf) {
 
398
                p->error = WFERR_NOMEMORY;
 
399
                return;
 
400
            }
 
401
            n = strlen(buf);
 
402
            w_byte((int)n, p);
 
403
            w_string(buf, n, p);
 
404
            PyMem_Free(buf);
 
405
        }
 
406
    }
 
407
    else if (PyBytes_CheckExact(v)) {
 
408
        W_TYPE(TYPE_STRING, p);
 
409
        w_pstring(PyBytes_AS_STRING(v), PyBytes_GET_SIZE(v), p);
 
410
    }
 
411
    else if (PyUnicode_CheckExact(v)) {
 
412
        if (p->version >= 4 && PyUnicode_IS_ASCII(v)) {
 
413
            int is_short = PyUnicode_GET_LENGTH(v) < 256;
 
414
            if (is_short) {
 
415
                if (PyUnicode_CHECK_INTERNED(v))
 
416
                    W_TYPE(TYPE_SHORT_ASCII_INTERNED, p);
 
417
                else
 
418
                    W_TYPE(TYPE_SHORT_ASCII, p);
 
419
                w_short_pstring((char *) PyUnicode_1BYTE_DATA(v),
 
420
                                PyUnicode_GET_LENGTH(v), p);
 
421
            }
 
422
            else {
 
423
                if (PyUnicode_CHECK_INTERNED(v))
 
424
                    W_TYPE(TYPE_ASCII_INTERNED, p);
 
425
                else
 
426
                    W_TYPE(TYPE_ASCII, p);
 
427
                w_pstring((char *) PyUnicode_1BYTE_DATA(v),
 
428
                          PyUnicode_GET_LENGTH(v), p);
 
429
            }
 
430
        }
 
431
        else {
 
432
            PyObject *utf8;
 
433
            utf8 = PyUnicode_AsEncodedString(v, "utf8", "surrogatepass");
 
434
            if (utf8 == NULL) {
 
435
                p->depth--;
 
436
                p->error = WFERR_UNMARSHALLABLE;
 
437
                return;
 
438
            }
 
439
            if (p->version >= 3 &&  PyUnicode_CHECK_INTERNED(v))
 
440
                W_TYPE(TYPE_INTERNED, p);
 
441
            else
 
442
                W_TYPE(TYPE_UNICODE, p);
 
443
            w_pstring(PyBytes_AS_STRING(utf8), PyBytes_GET_SIZE(utf8), p);
 
444
            Py_DECREF(utf8);
 
445
        }
 
446
    }
 
447
    else if (PyTuple_CheckExact(v)) {
 
448
        n = PyTuple_Size(v);
 
449
        if (p->version >= 4 && n < 256) {
 
450
            W_TYPE(TYPE_SMALL_TUPLE, p);
 
451
            w_byte((unsigned char)n, p);
 
452
        }
 
453
        else {
 
454
            W_TYPE(TYPE_TUPLE, p);
 
455
            W_SIZE(n, p);
 
456
        }
 
457
        for (i = 0; i < n; i++) {
 
458
            w_object(PyTuple_GET_ITEM(v, i), p);
 
459
        }
 
460
    }
 
461
    else if (PyList_CheckExact(v)) {
 
462
        W_TYPE(TYPE_LIST, p);
 
463
        n = PyList_GET_SIZE(v);
 
464
        W_SIZE(n, p);
 
465
        for (i = 0; i < n; i++) {
 
466
            w_object(PyList_GET_ITEM(v, i), p);
 
467
        }
 
468
    }
 
469
    else if (PyDict_CheckExact(v)) {
 
470
        Py_ssize_t pos;
 
471
        PyObject *key, *value;
 
472
        W_TYPE(TYPE_DICT, p);
 
473
        /* This one is NULL object terminated! */
 
474
        pos = 0;
 
475
        while (PyDict_Next(v, &pos, &key, &value)) {
 
476
            w_object(key, p);
 
477
            w_object(value, p);
 
478
        }
 
479
        w_object((PyObject *)NULL, p);
 
480
    }
 
481
    else if (PyAnySet_CheckExact(v)) {
 
482
        PyObject *value, *it;
 
483
 
 
484
        if (PyObject_TypeCheck(v, &PySet_Type))
 
485
            W_TYPE(TYPE_SET, p);
 
486
        else
 
487
            W_TYPE(TYPE_FROZENSET, p);
 
488
        n = PyObject_Size(v);
 
489
        if (n == -1) {
 
490
            p->depth--;
 
491
            p->error = WFERR_UNMARSHALLABLE;
 
492
            return;
 
493
        }
 
494
        W_SIZE(n, p);
 
495
        it = PyObject_GetIter(v);
 
496
        if (it == NULL) {
 
497
            p->depth--;
 
498
            p->error = WFERR_UNMARSHALLABLE;
 
499
            return;
 
500
        }
 
501
        while ((value = PyIter_Next(it)) != NULL) {
 
502
            w_object(value, p);
 
503
            Py_DECREF(value);
 
504
        }
 
505
        Py_DECREF(it);
 
506
        if (PyErr_Occurred()) {
 
507
            p->depth--;
 
508
            p->error = WFERR_UNMARSHALLABLE;
 
509
            return;
 
510
        }
 
511
    }
 
512
    else if (PyCode_Check(v)) {
 
513
        PyCodeObject *co = (PyCodeObject *)v;
 
514
        W_TYPE(TYPE_CODE, p);
 
515
        w_long(co->co_argcount, p);
 
516
        w_long(co->co_kwonlyargcount, p);
 
517
        w_long(co->co_nlocals, p);
 
518
        w_long(co->co_stacksize, p);
 
519
        w_long(co->co_flags, p);
 
520
        w_object(co->co_code, p);
 
521
        w_object(co->co_consts, p);
 
522
        w_object(co->co_names, p);
 
523
        w_object(co->co_varnames, p);
 
524
        w_object(co->co_freevars, p);
 
525
        w_object(co->co_cellvars, p);
 
526
        w_object(co->co_filename, p);
 
527
        w_object(co->co_name, p);
 
528
        w_long(co->co_firstlineno, p);
 
529
        w_object(co->co_lnotab, p);
 
530
    }
 
531
    else if (PyObject_CheckBuffer(v)) {
 
532
        /* Write unknown buffer-style objects as a string */
 
533
        Py_buffer view;
 
534
        if (PyObject_GetBuffer(v, &view, PyBUF_SIMPLE) != 0) {
 
535
            w_byte(TYPE_UNKNOWN, p);
 
536
            p->depth--;
 
537
            p->error = WFERR_UNMARSHALLABLE;
 
538
            return;
 
539
        }
 
540
        W_TYPE(TYPE_STRING, p);
 
541
        w_pstring(view.buf, view.len, p);
 
542
        PyBuffer_Release(&view);
 
543
    }
 
544
    else {
 
545
        W_TYPE(TYPE_UNKNOWN, p);
 
546
        p->error = WFERR_UNMARSHALLABLE;
 
547
    }
 
548
}
 
549
 
 
550
/* version currently has no effect for writing ints. */
 
551
void
 
552
PyMarshal_WriteLongToFile(long x, FILE *fp, int version)
 
553
{
 
554
    WFILE wf;
 
555
    wf.fp = fp;
 
556
    wf.error = WFERR_OK;
 
557
    wf.depth = 0;
 
558
    wf.refs = NULL;
 
559
    wf.version = version;
 
560
    w_long(x, &wf);
 
561
}
 
562
 
 
563
void
 
564
PyMarshal_WriteObjectToFile(PyObject *x, FILE *fp, int version)
 
565
{
 
566
    WFILE wf;
 
567
    wf.fp = fp;
 
568
    wf.error = WFERR_OK;
 
569
    wf.depth = 0;
 
570
    if (version >= 3) {
 
571
        if ((wf.refs = PyDict_New()) == NULL)
 
572
            return; /* caller mush check PyErr_Occurred() */
 
573
    } else
 
574
        wf.refs = NULL;
 
575
    wf.version = version;
 
576
    w_object(x, &wf);
 
577
    Py_XDECREF(wf.refs);
 
578
}
 
579
 
 
580
typedef WFILE RFILE; /* Same struct with different invariants */
 
581
 
 
582
static char *
 
583
r_string(Py_ssize_t n, RFILE *p)
 
584
{
 
585
    Py_ssize_t read = -1;
 
586
 
 
587
    if (p->ptr != NULL) {
 
588
        /* Fast path for loads() */
 
589
        char *res = p->ptr;
 
590
        Py_ssize_t left = p->end - p->ptr;
 
591
        if (left < n) {
 
592
            PyErr_SetString(PyExc_EOFError,
 
593
                            "marshal data too short");
 
594
            return NULL;
 
595
        }
 
596
        p->ptr += n;
 
597
        return res;
 
598
    }
 
599
    if (p->buf == NULL) {
 
600
        p->buf = PyMem_MALLOC(n);
 
601
        if (p->buf == NULL) {
 
602
            PyErr_NoMemory();
 
603
            return NULL;
 
604
        }
 
605
        p->buf_size = n;
 
606
    }
 
607
    else if (p->buf_size < n) {
 
608
        p->buf = PyMem_REALLOC(p->buf, n);
 
609
        if (p->buf == NULL) {
 
610
            PyErr_NoMemory();
 
611
            return NULL;
 
612
        }
 
613
        p->buf_size = n;
 
614
    }
 
615
 
 
616
    if (!p->readable) {
 
617
        assert(p->fp != NULL);
 
618
        read = fread(p->buf, 1, n, p->fp);
 
619
    }
 
620
    else {
 
621
        _Py_IDENTIFIER(readinto);
 
622
        PyObject *res, *mview;
 
623
        Py_buffer buf;
 
624
 
 
625
        if (PyBuffer_FillInfo(&buf, NULL, p->buf, n, 0, PyBUF_CONTIG) == -1)
 
626
            return NULL;
 
627
        mview = PyMemoryView_FromBuffer(&buf);
 
628
        if (mview == NULL)
 
629
            return NULL;
 
630
 
 
631
        res = _PyObject_CallMethodId(p->readable, &PyId_readinto, "N", mview);
 
632
        if (res != NULL) {
 
633
            read = PyNumber_AsSsize_t(res, PyExc_ValueError);
 
634
            Py_DECREF(res);
 
635
        }
 
636
    }
 
637
    if (read != n) {
 
638
        if (!PyErr_Occurred()) {
 
639
            if (read > n)
 
640
                PyErr_Format(PyExc_ValueError,
 
641
                             "read() returned too much data: "
 
642
                             "%zd bytes requested, %zd returned",
 
643
                             n, read);
 
644
            else
 
645
                PyErr_SetString(PyExc_EOFError,
 
646
                                "EOF read where not expected");
 
647
        }
 
648
        return NULL;
 
649
    }
 
650
    return p->buf;
 
651
}
 
652
 
 
653
static int
 
654
r_byte(RFILE *p)
 
655
{
 
656
    int c = EOF;
 
657
 
 
658
    if (p->ptr != NULL) {
 
659
        if (p->ptr < p->end)
 
660
            c = (unsigned char) *p->ptr++;
 
661
        return c;
 
662
    }
 
663
    if (!p->readable) {
 
664
        assert(p->fp);
 
665
        c = getc(p->fp);
 
666
    }
 
667
    else {
 
668
        char *ptr = r_string(1, p);
 
669
        if (ptr != NULL)
 
670
            c = *(unsigned char *) ptr;
 
671
    }
 
672
    return c;
 
673
}
 
674
 
 
675
static int
 
676
r_short(RFILE *p)
 
677
{
 
678
    short x = -1;
 
679
    unsigned char *buffer;
 
680
 
 
681
    buffer = (unsigned char *) r_string(2, p);
 
682
    if (buffer != NULL) {
 
683
        x = buffer[0];
 
684
        x |= buffer[1] << 8;
 
685
        /* Sign-extension, in case short greater than 16 bits */
 
686
        x |= -(x & 0x8000);
 
687
    }
 
688
    return x;
 
689
}
 
690
 
 
691
static long
 
692
r_long(RFILE *p)
 
693
{
 
694
    long x = -1;
 
695
    unsigned char *buffer;
 
696
 
 
697
    buffer = (unsigned char *) r_string(4, p);
 
698
    if (buffer != NULL) {
 
699
        x = buffer[0];
 
700
        x |= (long)buffer[1] << 8;
 
701
        x |= (long)buffer[2] << 16;
 
702
        x |= (long)buffer[3] << 24;
 
703
#if SIZEOF_LONG > 4
 
704
        /* Sign extension for 64-bit machines */
 
705
        x |= -(x & 0x80000000L);
 
706
#endif
 
707
    }
 
708
    return x;
 
709
}
 
710
 
 
711
static PyObject *
 
712
r_PyLong(RFILE *p)
 
713
{
 
714
    PyLongObject *ob;
 
715
    long n, size, i;
 
716
    int j, md, shorts_in_top_digit;
 
717
    digit d;
 
718
 
 
719
    n = r_long(p);
 
720
    if (PyErr_Occurred())
 
721
        return NULL;
 
722
    if (n == 0)
 
723
        return (PyObject *)_PyLong_New(0);
 
724
    if (n < -SIZE32_MAX || n > SIZE32_MAX) {
 
725
        PyErr_SetString(PyExc_ValueError,
 
726
                       "bad marshal data (long size out of range)");
 
727
        return NULL;
 
728
    }
 
729
 
 
730
    size = 1 + (ABS(n) - 1) / PyLong_MARSHAL_RATIO;
 
731
    shorts_in_top_digit = 1 + (ABS(n) - 1) % PyLong_MARSHAL_RATIO;
 
732
    ob = _PyLong_New(size);
 
733
    if (ob == NULL)
 
734
        return NULL;
 
735
 
 
736
    Py_SIZE(ob) = n > 0 ? size : -size;
 
737
 
 
738
    for (i = 0; i < size-1; i++) {
 
739
        d = 0;
 
740
        for (j=0; j < PyLong_MARSHAL_RATIO; j++) {
 
741
            md = r_short(p);
 
742
            if (PyErr_Occurred()) {
 
743
                Py_DECREF(ob);
 
744
                return NULL;
 
745
            }
 
746
            if (md < 0 || md > PyLong_MARSHAL_BASE)
 
747
                goto bad_digit;
 
748
            d += (digit)md << j*PyLong_MARSHAL_SHIFT;
 
749
        }
 
750
        ob->ob_digit[i] = d;
 
751
    }
 
752
 
 
753
    d = 0;
 
754
    for (j=0; j < shorts_in_top_digit; j++) {
 
755
        md = r_short(p);
 
756
        if (PyErr_Occurred()) {
 
757
            Py_DECREF(ob);
 
758
            return NULL;
 
759
        }
 
760
        if (md < 0 || md > PyLong_MARSHAL_BASE)
 
761
            goto bad_digit;
 
762
        /* topmost marshal digit should be nonzero */
 
763
        if (md == 0 && j == shorts_in_top_digit - 1) {
 
764
            Py_DECREF(ob);
 
765
            PyErr_SetString(PyExc_ValueError,
 
766
                "bad marshal data (unnormalized long data)");
 
767
            return NULL;
 
768
        }
 
769
        d += (digit)md << j*PyLong_MARSHAL_SHIFT;
 
770
    }
 
771
    if (PyErr_Occurred()) {
 
772
        Py_DECREF(ob);
 
773
        return NULL;
 
774
    }
 
775
    /* top digit should be nonzero, else the resulting PyLong won't be
 
776
       normalized */
 
777
    ob->ob_digit[size-1] = d;
 
778
    return (PyObject *)ob;
 
779
  bad_digit:
 
780
    Py_DECREF(ob);
 
781
    PyErr_SetString(PyExc_ValueError,
 
782
                    "bad marshal data (digit out of range in long)");
 
783
    return NULL;
 
784
}
 
785
 
 
786
/* allocate the reflist index for a new object. Return -1 on failure */
 
787
static Py_ssize_t
 
788
r_ref_reserve(int flag, RFILE *p)
 
789
{
 
790
    if (flag) { /* currently only FLAG_REF is defined */
 
791
        Py_ssize_t idx = PyList_GET_SIZE(p->refs);
 
792
        if (idx >= 0x7ffffffe) {
 
793
            PyErr_SetString(PyExc_ValueError, "bad marshal data (index list too large)");
 
794
            return -1;
 
795
        }
 
796
        if (PyList_Append(p->refs, Py_None) < 0)
 
797
            return -1;
 
798
        return idx;
 
799
    } else
 
800
        return 0;
 
801
}
 
802
 
 
803
/* insert the new object 'o' to the reflist at previously
 
804
 * allocated index 'idx'.
 
805
 * 'o' can be NULL, in which case nothing is done.
 
806
 * if 'o' was non-NULL, and the function succeeds, 'o' is returned.
 
807
 * if 'o' was non-NULL, and the function fails, 'o' is released and
 
808
 * NULL returned. This simplifies error checking at the call site since
 
809
 * a single test for NULL for the function result is enough.
 
810
 */
 
811
static PyObject *
 
812
r_ref_insert(PyObject *o, Py_ssize_t idx, int flag, RFILE *p)
 
813
{
 
814
    if (o != NULL && flag) { /* currently only FLAG_REF is defined */
 
815
        PyObject *tmp = PyList_GET_ITEM(p->refs, idx);
 
816
        Py_INCREF(o);
 
817
        PyList_SET_ITEM(p->refs, idx, o);
 
818
        Py_DECREF(tmp);
 
819
    }
 
820
    return o;
 
821
}
 
822
 
 
823
/* combination of both above, used when an object can be
 
824
 * created whenever it is seen in the file, as opposed to
 
825
 * after having loaded its sub-objects.
 
826
 */
 
827
static PyObject *
 
828
r_ref(PyObject *o, int flag, RFILE *p)
 
829
{
 
830
    assert(flag & FLAG_REF);
 
831
    if (o == NULL)
 
832
        return NULL;
 
833
    if (PyList_Append(p->refs, o) < 0) {
 
834
        Py_DECREF(o); /* release the new object */
 
835
        return NULL;
 
836
    }
 
837
    return o;
 
838
}
 
839
 
 
840
static PyObject *
 
841
r_object(RFILE *p)
 
842
{
 
843
    /* NULL is a valid return value, it does not necessarily means that
 
844
       an exception is set. */
 
845
    PyObject *v, *v2;
 
846
    Py_ssize_t idx = 0;
 
847
    long i, n;
 
848
    int type, code = r_byte(p);
 
849
    int flag, is_interned = 0;
 
850
    PyObject *retval = NULL;
 
851
 
 
852
    if (code == EOF) {
 
853
        PyErr_SetString(PyExc_EOFError,
 
854
                        "EOF read where object expected");
 
855
        return NULL;
 
856
    }
 
857
 
 
858
    p->depth++;
 
859
 
 
860
    if (p->depth > MAX_MARSHAL_STACK_DEPTH) {
 
861
        p->depth--;
 
862
        PyErr_SetString(PyExc_ValueError, "recursion limit exceeded");
 
863
        return NULL;
 
864
    }
 
865
 
 
866
    flag = code & FLAG_REF;
 
867
    type = code & ~FLAG_REF;
 
868
 
 
869
#define R_REF(O) do{\
 
870
    if (flag) \
 
871
        O = r_ref(O, flag, p);\
 
872
} while (0)
 
873
 
 
874
    switch (type) {
 
875
 
 
876
    case TYPE_NULL:
 
877
        break;
 
878
 
 
879
    case TYPE_NONE:
 
880
        Py_INCREF(Py_None);
 
881
        retval = Py_None;
 
882
        break;
 
883
 
 
884
    case TYPE_STOPITER:
 
885
        Py_INCREF(PyExc_StopIteration);
 
886
        retval = PyExc_StopIteration;
 
887
        break;
 
888
 
 
889
    case TYPE_ELLIPSIS:
 
890
        Py_INCREF(Py_Ellipsis);
 
891
        retval = Py_Ellipsis;
 
892
        break;
 
893
 
 
894
    case TYPE_FALSE:
 
895
        Py_INCREF(Py_False);
 
896
        retval = Py_False;
 
897
        break;
 
898
 
 
899
    case TYPE_TRUE:
 
900
        Py_INCREF(Py_True);
 
901
        retval = Py_True;
 
902
        break;
 
903
 
 
904
    case TYPE_INT:
 
905
        n = r_long(p);
 
906
        retval = PyErr_Occurred() ? NULL : PyLong_FromLong(n);
 
907
        R_REF(retval);
 
908
        break;
 
909
 
 
910
    case TYPE_LONG:
 
911
        retval = r_PyLong(p);
 
912
        R_REF(retval);
 
913
        break;
 
914
 
 
915
    case TYPE_FLOAT:
 
916
        {
 
917
            char buf[256], *ptr;
 
918
            double dx;
 
919
            n = r_byte(p);
 
920
            if (n == EOF) {
 
921
                PyErr_SetString(PyExc_EOFError,
 
922
                    "EOF read where object expected");
 
923
                break;
 
924
            }
 
925
            ptr = r_string(n, p);
 
926
            if (ptr == NULL)
 
927
                break;
 
928
            memcpy(buf, ptr, n);
 
929
            buf[n] = '\0';
 
930
            dx = PyOS_string_to_double(buf, NULL, NULL);
 
931
            if (dx == -1.0 && PyErr_Occurred())
 
932
                break;
 
933
            retval = PyFloat_FromDouble(dx);
 
934
            R_REF(retval);
 
935
            break;
 
936
        }
 
937
 
 
938
    case TYPE_BINARY_FLOAT:
 
939
        {
 
940
            unsigned char *buf;
 
941
            double x;
 
942
            buf = (unsigned char *) r_string(8, p);
 
943
            if (buf == NULL)
 
944
                break;
 
945
            x = _PyFloat_Unpack8(buf, 1);
 
946
            if (x == -1.0 && PyErr_Occurred())
 
947
                break;
 
948
            retval = PyFloat_FromDouble(x);
 
949
            R_REF(retval);
 
950
            break;
 
951
        }
 
952
 
 
953
    case TYPE_COMPLEX:
 
954
        {
 
955
            char buf[256], *ptr;
 
956
            Py_complex c;
 
957
            n = r_byte(p);
 
958
            if (n == EOF) {
 
959
                PyErr_SetString(PyExc_EOFError,
 
960
                    "EOF read where object expected");
 
961
                break;
 
962
            }
 
963
            ptr = r_string(n, p);
 
964
            if (ptr == NULL)
 
965
                break;
 
966
            memcpy(buf, ptr, n);
 
967
            buf[n] = '\0';
 
968
            c.real = PyOS_string_to_double(buf, NULL, NULL);
 
969
            if (c.real == -1.0 && PyErr_Occurred())
 
970
                break;
 
971
            n = r_byte(p);
 
972
            if (n == EOF) {
 
973
                PyErr_SetString(PyExc_EOFError,
 
974
                    "EOF read where object expected");
 
975
                break;
 
976
            }
 
977
            ptr = r_string(n, p);
 
978
            if (ptr == NULL)
 
979
                break;
 
980
            memcpy(buf, ptr, n);
 
981
            buf[n] = '\0';
 
982
            c.imag = PyOS_string_to_double(buf, NULL, NULL);
 
983
            if (c.imag == -1.0 && PyErr_Occurred())
 
984
                break;
 
985
            retval = PyComplex_FromCComplex(c);
 
986
            R_REF(retval);
 
987
            break;
 
988
        }
 
989
 
 
990
    case TYPE_BINARY_COMPLEX:
 
991
        {
 
992
            unsigned char *buf;
 
993
            Py_complex c;
 
994
            buf = (unsigned char *) r_string(8, p);
 
995
            if (buf == NULL)
 
996
                break;
 
997
            c.real = _PyFloat_Unpack8(buf, 1);
 
998
            if (c.real == -1.0 && PyErr_Occurred())
 
999
                break;
 
1000
            buf = (unsigned char *) r_string(8, p);
 
1001
            if (buf == NULL)
 
1002
                break;
 
1003
            c.imag = _PyFloat_Unpack8(buf, 1);
 
1004
            if (c.imag == -1.0 && PyErr_Occurred())
 
1005
                break;
 
1006
            retval = PyComplex_FromCComplex(c);
 
1007
            R_REF(retval);
 
1008
            break;
 
1009
        }
 
1010
 
 
1011
    case TYPE_STRING:
 
1012
        {
 
1013
            char *ptr;
 
1014
            n = r_long(p);
 
1015
            if (PyErr_Occurred())
 
1016
                break;
 
1017
            if (n < 0 || n > SIZE32_MAX) {
 
1018
                PyErr_SetString(PyExc_ValueError, "bad marshal data (string size out of range)");
 
1019
                break;
 
1020
            }
 
1021
            v = PyBytes_FromStringAndSize((char *)NULL, n);
 
1022
            if (v == NULL)
 
1023
                break;
 
1024
            ptr = r_string(n, p);
 
1025
            if (ptr == NULL) {
 
1026
                Py_DECREF(v);
 
1027
                break;
 
1028
            }
 
1029
            memcpy(PyBytes_AS_STRING(v), ptr, n);
 
1030
            retval = v;
 
1031
            R_REF(retval);
 
1032
            break;
 
1033
        }
 
1034
 
 
1035
    case TYPE_ASCII_INTERNED:
 
1036
        is_interned = 1;
 
1037
    case TYPE_ASCII:
 
1038
        n = r_long(p);
 
1039
        if (PyErr_Occurred())
 
1040
            break;
 
1041
        if (n < 0 || n > SIZE32_MAX) {
 
1042
            PyErr_SetString(PyExc_ValueError, "bad marshal data (unicode size out of range)");
 
1043
            break;
 
1044
        }
 
1045
        goto _read_ascii;
 
1046
 
 
1047
    case TYPE_SHORT_ASCII_INTERNED:
 
1048
        is_interned = 1;
 
1049
    case TYPE_SHORT_ASCII:
 
1050
        n = r_byte(p);
 
1051
        if (n == EOF) {
 
1052
            PyErr_SetString(PyExc_EOFError,
 
1053
                "EOF read where object expected");
 
1054
            break;
 
1055
        }
 
1056
    _read_ascii:
 
1057
        {
 
1058
            char *ptr;
 
1059
            ptr = r_string(n, p);
 
1060
            if (ptr == NULL)
 
1061
                break;
 
1062
            v = PyUnicode_FromKindAndData(PyUnicode_1BYTE_KIND, ptr, n);
 
1063
            if (v == NULL)
 
1064
                break;
 
1065
            if (is_interned)
 
1066
                PyUnicode_InternInPlace(&v);
 
1067
            retval = v;
 
1068
            R_REF(retval);
 
1069
            break;
 
1070
        }
 
1071
 
 
1072
    case TYPE_INTERNED:
 
1073
        is_interned = 1;
 
1074
    case TYPE_UNICODE:
 
1075
        {
 
1076
        char *buffer;
 
1077
 
 
1078
        n = r_long(p);
 
1079
        if (PyErr_Occurred())
 
1080
            break;
 
1081
        if (n < 0 || n > SIZE32_MAX) {
 
1082
            PyErr_SetString(PyExc_ValueError, "bad marshal data (unicode size out of range)");
 
1083
            break;
 
1084
        }
 
1085
        if (n != 0) {
 
1086
            buffer = r_string(n, p);
 
1087
            if (buffer == NULL)
 
1088
                break;
 
1089
            v = PyUnicode_DecodeUTF8(buffer, n, "surrogatepass");
 
1090
        }
 
1091
        else {
 
1092
            v = PyUnicode_New(0, 0);
 
1093
        }
 
1094
        if (v == NULL)
 
1095
            break;
 
1096
        if (is_interned)
 
1097
            PyUnicode_InternInPlace(&v);
 
1098
        retval = v;
 
1099
        R_REF(retval);
 
1100
        break;
 
1101
        }
 
1102
 
 
1103
    case TYPE_SMALL_TUPLE:
 
1104
        n = (unsigned char) r_byte(p);
 
1105
        if (PyErr_Occurred())
 
1106
            break;
 
1107
        goto _read_tuple;
 
1108
    case TYPE_TUPLE:
 
1109
        n = r_long(p);
 
1110
        if (PyErr_Occurred())
 
1111
            break;
 
1112
        if (n < 0 || n > SIZE32_MAX) {
 
1113
            PyErr_SetString(PyExc_ValueError, "bad marshal data (tuple size out of range)");
 
1114
            break;
 
1115
        }
 
1116
    _read_tuple:
 
1117
        v = PyTuple_New(n);
 
1118
        R_REF(v);
 
1119
        if (v == NULL)
 
1120
            break;
 
1121
 
 
1122
        for (i = 0; i < n; i++) {
 
1123
            v2 = r_object(p);
 
1124
            if ( v2 == NULL ) {
 
1125
                if (!PyErr_Occurred())
 
1126
                    PyErr_SetString(PyExc_TypeError,
 
1127
                        "NULL object in marshal data for tuple");
 
1128
                Py_DECREF(v);
 
1129
                v = NULL;
 
1130
                break;
 
1131
            }
 
1132
            PyTuple_SET_ITEM(v, i, v2);
 
1133
        }
 
1134
        retval = v;
 
1135
        break;
 
1136
 
 
1137
    case TYPE_LIST:
 
1138
        n = r_long(p);
 
1139
        if (PyErr_Occurred())
 
1140
            break;
 
1141
        if (n < 0 || n > SIZE32_MAX) {
 
1142
            PyErr_SetString(PyExc_ValueError, "bad marshal data (list size out of range)");
 
1143
            break;
 
1144
        }
 
1145
        v = PyList_New(n);
 
1146
        R_REF(v);
 
1147
        if (v == NULL)
 
1148
            break;
 
1149
        for (i = 0; i < n; i++) {
 
1150
            v2 = r_object(p);
 
1151
            if ( v2 == NULL ) {
 
1152
                if (!PyErr_Occurred())
 
1153
                    PyErr_SetString(PyExc_TypeError,
 
1154
                        "NULL object in marshal data for list");
 
1155
                Py_DECREF(v);
 
1156
                v = NULL;
 
1157
                break;
 
1158
            }
 
1159
            PyList_SET_ITEM(v, i, v2);
 
1160
        }
 
1161
        retval = v;
 
1162
        break;
 
1163
 
 
1164
    case TYPE_DICT:
 
1165
        v = PyDict_New();
 
1166
        R_REF(v);
 
1167
        if (v == NULL)
 
1168
            break;
 
1169
        for (;;) {
 
1170
            PyObject *key, *val;
 
1171
            key = r_object(p);
 
1172
            if (key == NULL)
 
1173
                break;
 
1174
            val = r_object(p);
 
1175
            if (val == NULL) {
 
1176
                Py_DECREF(key);
 
1177
                break;
 
1178
            }
 
1179
            if (PyDict_SetItem(v, key, val) < 0) {
 
1180
                Py_DECREF(key);
 
1181
                Py_DECREF(val);
 
1182
                break;
 
1183
            }
 
1184
            Py_DECREF(key);
 
1185
            Py_DECREF(val);
 
1186
        }
 
1187
        if (PyErr_Occurred()) {
 
1188
            Py_DECREF(v);
 
1189
            v = NULL;
 
1190
        }
 
1191
        retval = v;
 
1192
        break;
 
1193
 
 
1194
    case TYPE_SET:
 
1195
    case TYPE_FROZENSET:
 
1196
        n = r_long(p);
 
1197
        if (PyErr_Occurred())
 
1198
            break;
 
1199
        if (n < 0 || n > SIZE32_MAX) {
 
1200
            PyErr_SetString(PyExc_ValueError, "bad marshal data (set size out of range)");
 
1201
            break;
 
1202
        }
 
1203
        v = (type == TYPE_SET) ? PySet_New(NULL) : PyFrozenSet_New(NULL);
 
1204
        if (type == TYPE_SET) {
 
1205
            R_REF(v);
 
1206
        } else {
 
1207
            /* must use delayed registration of frozensets because they must
 
1208
             * be init with a refcount of 1
 
1209
             */
 
1210
            idx = r_ref_reserve(flag, p);
 
1211
            if (idx < 0)
 
1212
                Py_CLEAR(v); /* signal error */
 
1213
        }
 
1214
        if (v == NULL)
 
1215
            break;
 
1216
 
 
1217
        for (i = 0; i < n; i++) {
 
1218
            v2 = r_object(p);
 
1219
            if ( v2 == NULL ) {
 
1220
                if (!PyErr_Occurred())
 
1221
                    PyErr_SetString(PyExc_TypeError,
 
1222
                        "NULL object in marshal data for set");
 
1223
                Py_DECREF(v);
 
1224
                v = NULL;
 
1225
                break;
 
1226
            }
 
1227
            if (PySet_Add(v, v2) == -1) {
 
1228
                Py_DECREF(v);
 
1229
                Py_DECREF(v2);
 
1230
                v = NULL;
 
1231
                break;
 
1232
            }
 
1233
            Py_DECREF(v2);
 
1234
        }
 
1235
        if (type != TYPE_SET)
 
1236
            v = r_ref_insert(v, idx, flag, p);
 
1237
        retval = v;
 
1238
        break;
 
1239
 
 
1240
    case TYPE_CODE:
 
1241
        {
 
1242
            int argcount;
 
1243
            int kwonlyargcount;
 
1244
            int nlocals;
 
1245
            int stacksize;
 
1246
            int flags;
 
1247
            PyObject *code = NULL;
 
1248
            PyObject *consts = NULL;
 
1249
            PyObject *names = NULL;
 
1250
            PyObject *varnames = NULL;
 
1251
            PyObject *freevars = NULL;
 
1252
            PyObject *cellvars = NULL;
 
1253
            PyObject *filename = NULL;
 
1254
            PyObject *name = NULL;
 
1255
            int firstlineno;
 
1256
            PyObject *lnotab = NULL;
 
1257
 
 
1258
            idx = r_ref_reserve(flag, p);
 
1259
            if (idx < 0)
 
1260
                break;
 
1261
 
 
1262
            v = NULL;
 
1263
 
 
1264
            /* XXX ignore long->int overflows for now */
 
1265
            argcount = (int)r_long(p);
 
1266
            if (PyErr_Occurred())
 
1267
                goto code_error;
 
1268
            kwonlyargcount = (int)r_long(p);
 
1269
            if (PyErr_Occurred())
 
1270
                goto code_error;
 
1271
            nlocals = (int)r_long(p);
 
1272
            if (PyErr_Occurred())
 
1273
                goto code_error;
 
1274
            stacksize = (int)r_long(p);
 
1275
            if (PyErr_Occurred())
 
1276
                goto code_error;
 
1277
            flags = (int)r_long(p);
 
1278
            if (PyErr_Occurred())
 
1279
                goto code_error;
 
1280
            code = r_object(p);
 
1281
            if (code == NULL)
 
1282
                goto code_error;
 
1283
            consts = r_object(p);
 
1284
            if (consts == NULL)
 
1285
                goto code_error;
 
1286
            names = r_object(p);
 
1287
            if (names == NULL)
 
1288
                goto code_error;
 
1289
            varnames = r_object(p);
 
1290
            if (varnames == NULL)
 
1291
                goto code_error;
 
1292
            freevars = r_object(p);
 
1293
            if (freevars == NULL)
 
1294
                goto code_error;
 
1295
            cellvars = r_object(p);
 
1296
            if (cellvars == NULL)
 
1297
                goto code_error;
 
1298
            filename = r_object(p);
 
1299
            if (filename == NULL)
 
1300
                goto code_error;
 
1301
            if (PyUnicode_CheckExact(filename)) {
 
1302
                if (p->current_filename != NULL) {
 
1303
                    if (!PyUnicode_Compare(filename, p->current_filename)) {
 
1304
                        Py_DECREF(filename);
 
1305
                        Py_INCREF(p->current_filename);
 
1306
                        filename = p->current_filename;
 
1307
                    }
 
1308
                }
 
1309
                else {
 
1310
                    p->current_filename = filename;
 
1311
                }
 
1312
            }
 
1313
            name = r_object(p);
 
1314
            if (name == NULL)
 
1315
                goto code_error;
 
1316
            firstlineno = (int)r_long(p);
 
1317
            if (firstlineno == -1 && PyErr_Occurred())
 
1318
                break;
 
1319
            lnotab = r_object(p);
 
1320
            if (lnotab == NULL)
 
1321
                goto code_error;
 
1322
 
 
1323
            v = (PyObject *) PyCode_New(
 
1324
                            argcount, kwonlyargcount,
 
1325
                            nlocals, stacksize, flags,
 
1326
                            code, consts, names, varnames,
 
1327
                            freevars, cellvars, filename, name,
 
1328
                            firstlineno, lnotab);
 
1329
            v = r_ref_insert(v, idx, flag, p);
 
1330
 
 
1331
          code_error:
 
1332
            Py_XDECREF(code);
 
1333
            Py_XDECREF(consts);
 
1334
            Py_XDECREF(names);
 
1335
            Py_XDECREF(varnames);
 
1336
            Py_XDECREF(freevars);
 
1337
            Py_XDECREF(cellvars);
 
1338
            Py_XDECREF(filename);
 
1339
            Py_XDECREF(name);
 
1340
            Py_XDECREF(lnotab);
 
1341
        }
 
1342
        retval = v;
 
1343
        break;
 
1344
 
 
1345
    case TYPE_REF:
 
1346
        n = r_long(p);
 
1347
        if (n < 0 || n >= PyList_GET_SIZE(p->refs)) {
 
1348
            if (n == -1 && PyErr_Occurred())
 
1349
                break;
 
1350
            PyErr_SetString(PyExc_ValueError, "bad marshal data (invalid reference)");
 
1351
            break;
 
1352
        }
 
1353
        v = PyList_GET_ITEM(p->refs, n);
 
1354
        if (v == Py_None) {
 
1355
            PyErr_SetString(PyExc_ValueError, "bad marshal data (invalid reference)");
 
1356
            break;
 
1357
        }
 
1358
        Py_INCREF(v);
 
1359
        retval = v;
 
1360
        break;
 
1361
 
 
1362
    default:
 
1363
        /* Bogus data got written, which isn't ideal.
 
1364
           This will let you keep working and recover. */
 
1365
        PyErr_SetString(PyExc_ValueError, "bad marshal data (unknown type code)");
 
1366
        break;
 
1367
 
 
1368
    }
 
1369
    p->depth--;
 
1370
    return retval;
 
1371
}
 
1372
 
 
1373
static PyObject *
 
1374
read_object(RFILE *p)
 
1375
{
 
1376
    PyObject *v;
 
1377
    if (PyErr_Occurred()) {
 
1378
        fprintf(stderr, "XXX readobject called with exception set\n");
 
1379
        return NULL;
 
1380
    }
 
1381
    v = r_object(p);
 
1382
    if (v == NULL && !PyErr_Occurred())
 
1383
        PyErr_SetString(PyExc_TypeError, "NULL object in marshal data for object");
 
1384
    return v;
 
1385
}
 
1386
 
 
1387
int
 
1388
PyMarshal_ReadShortFromFile(FILE *fp)
 
1389
{
 
1390
    RFILE rf;
 
1391
    int res;
 
1392
    assert(fp);
 
1393
    rf.readable = NULL;
 
1394
    rf.fp = fp;
 
1395
    rf.current_filename = NULL;
 
1396
    rf.end = rf.ptr = NULL;
 
1397
    rf.buf = NULL;
 
1398
    res = r_short(&rf);
 
1399
    if (rf.buf != NULL)
 
1400
        PyMem_FREE(rf.buf);
 
1401
    return res;
 
1402
}
 
1403
 
 
1404
long
 
1405
PyMarshal_ReadLongFromFile(FILE *fp)
 
1406
{
 
1407
    RFILE rf;
 
1408
    long res;
 
1409
    rf.fp = fp;
 
1410
    rf.readable = NULL;
 
1411
    rf.current_filename = NULL;
 
1412
    rf.ptr = rf.end = NULL;
 
1413
    rf.buf = NULL;
 
1414
    res = r_long(&rf);
 
1415
    if (rf.buf != NULL)
 
1416
        PyMem_FREE(rf.buf);
 
1417
    return res;
 
1418
}
 
1419
 
 
1420
#ifdef HAVE_FSTAT
 
1421
/* Return size of file in bytes; < 0 if unknown. */
 
1422
static off_t
 
1423
getfilesize(FILE *fp)
 
1424
{
 
1425
    struct stat st;
 
1426
    if (fstat(fileno(fp), &st) != 0)
 
1427
        return -1;
 
1428
    else
 
1429
        return st.st_size;
 
1430
}
 
1431
#endif
 
1432
 
 
1433
/* If we can get the size of the file up-front, and it's reasonably small,
 
1434
 * read it in one gulp and delegate to ...FromString() instead.  Much quicker
 
1435
 * than reading a byte at a time from file; speeds .pyc imports.
 
1436
 * CAUTION:  since this may read the entire remainder of the file, don't
 
1437
 * call it unless you know you're done with the file.
 
1438
 */
 
1439
PyObject *
 
1440
PyMarshal_ReadLastObjectFromFile(FILE *fp)
 
1441
{
 
1442
/* REASONABLE_FILE_LIMIT is by defn something big enough for Tkinter.pyc. */
 
1443
#define REASONABLE_FILE_LIMIT (1L << 18)
 
1444
#ifdef HAVE_FSTAT
 
1445
    off_t filesize;
 
1446
    filesize = getfilesize(fp);
 
1447
    if (filesize > 0 && filesize <= REASONABLE_FILE_LIMIT) {
 
1448
        char* pBuf = (char *)PyMem_MALLOC(filesize);
 
1449
        if (pBuf != NULL) {
 
1450
            size_t n = fread(pBuf, 1, (size_t)filesize, fp);
 
1451
            PyObject* v = PyMarshal_ReadObjectFromString(pBuf, n);
 
1452
            PyMem_FREE(pBuf);
 
1453
            return v;
 
1454
        }
 
1455
 
 
1456
    }
 
1457
#endif
 
1458
    /* We don't have fstat, or we do but the file is larger than
 
1459
     * REASONABLE_FILE_LIMIT or malloc failed -- read a byte at a time.
 
1460
     */
 
1461
    return PyMarshal_ReadObjectFromFile(fp);
 
1462
 
 
1463
#undef REASONABLE_FILE_LIMIT
 
1464
}
 
1465
 
 
1466
PyObject *
 
1467
PyMarshal_ReadObjectFromFile(FILE *fp)
 
1468
{
 
1469
    RFILE rf;
 
1470
    PyObject *result;
 
1471
    rf.fp = fp;
 
1472
    rf.readable = NULL;
 
1473
    rf.current_filename = NULL;
 
1474
    rf.depth = 0;
 
1475
    rf.ptr = rf.end = NULL;
 
1476
    rf.buf = NULL;
 
1477
    rf.refs = PyList_New(0);
 
1478
    if (rf.refs == NULL)
 
1479
        return NULL;
 
1480
    result = r_object(&rf);
 
1481
    Py_DECREF(rf.refs);
 
1482
    if (rf.buf != NULL)
 
1483
        PyMem_FREE(rf.buf);
 
1484
    return result;
 
1485
}
 
1486
 
 
1487
PyObject *
 
1488
PyMarshal_ReadObjectFromString(const char *str, Py_ssize_t len)
 
1489
{
 
1490
    RFILE rf;
 
1491
    PyObject *result;
 
1492
    rf.fp = NULL;
 
1493
    rf.readable = NULL;
 
1494
    rf.current_filename = NULL;
 
1495
    rf.ptr = (char *)str;
 
1496
    rf.end = (char *)str + len;
 
1497
    rf.buf = NULL;
 
1498
    rf.depth = 0;
 
1499
    rf.refs = PyList_New(0);
 
1500
    if (rf.refs == NULL)
 
1501
        return NULL;
 
1502
    result = r_object(&rf);
 
1503
    Py_DECREF(rf.refs);
 
1504
    if (rf.buf != NULL)
 
1505
        PyMem_FREE(rf.buf);
 
1506
    return result;
 
1507
}
 
1508
 
 
1509
PyObject *
 
1510
PyMarshal_WriteObjectToString(PyObject *x, int version)
 
1511
{
 
1512
    WFILE wf;
 
1513
 
 
1514
    wf.fp = NULL;
 
1515
    wf.readable = NULL;
 
1516
    wf.str = PyBytes_FromStringAndSize((char *)NULL, 50);
 
1517
    if (wf.str == NULL)
 
1518
        return NULL;
 
1519
    wf.ptr = PyBytes_AS_STRING((PyBytesObject *)wf.str);
 
1520
    wf.end = wf.ptr + PyBytes_Size(wf.str);
 
1521
    wf.error = WFERR_OK;
 
1522
    wf.depth = 0;
 
1523
    wf.version = version;
 
1524
    if (version >= 3) {
 
1525
        if ((wf.refs = PyDict_New()) == NULL)
 
1526
            return NULL;
 
1527
    } else
 
1528
        wf.refs = NULL;
 
1529
    w_object(x, &wf);
 
1530
    Py_XDECREF(wf.refs);
 
1531
    if (wf.str != NULL) {
 
1532
        char *base = PyBytes_AS_STRING((PyBytesObject *)wf.str);
 
1533
        if (wf.ptr - base > PY_SSIZE_T_MAX) {
 
1534
            Py_DECREF(wf.str);
 
1535
            PyErr_SetString(PyExc_OverflowError,
 
1536
                            "too much marshal data for a string");
 
1537
            return NULL;
 
1538
        }
 
1539
        if (_PyBytes_Resize(&wf.str, (Py_ssize_t)(wf.ptr - base)) < 0)
 
1540
            return NULL;
 
1541
    }
 
1542
    if (wf.error != WFERR_OK) {
 
1543
        Py_XDECREF(wf.str);
 
1544
        if (wf.error == WFERR_NOMEMORY)
 
1545
            PyErr_NoMemory();
 
1546
        else
 
1547
            PyErr_SetString(PyExc_ValueError,
 
1548
              (wf.error==WFERR_UNMARSHALLABLE)?"unmarshallable object"
 
1549
               :"object too deeply nested to marshal");
 
1550
        return NULL;
 
1551
    }
 
1552
    return wf.str;
 
1553
}
 
1554
 
 
1555
/* And an interface for Python programs... */
 
1556
 
 
1557
static PyObject *
 
1558
marshal_dump(PyObject *self, PyObject *args)
 
1559
{
 
1560
    /* XXX Quick hack -- need to do this differently */
 
1561
    PyObject *x;
 
1562
    PyObject *f;
 
1563
    int version = Py_MARSHAL_VERSION;
 
1564
    PyObject *s;
 
1565
    PyObject *res;
 
1566
    _Py_IDENTIFIER(write);
 
1567
 
 
1568
    if (!PyArg_ParseTuple(args, "OO|i:dump", &x, &f, &version))
 
1569
        return NULL;
 
1570
    s = PyMarshal_WriteObjectToString(x, version);
 
1571
    if (s == NULL)
 
1572
        return NULL;
 
1573
    res = _PyObject_CallMethodId(f, &PyId_write, "O", s);
 
1574
    Py_DECREF(s);
 
1575
    return res;
 
1576
}
 
1577
 
 
1578
PyDoc_STRVAR(dump_doc,
 
1579
"dump(value, file[, version])\n\
 
1580
\n\
 
1581
Write the value on the open file. The value must be a supported type.\n\
 
1582
The file must be an open file object such as sys.stdout or returned by\n\
 
1583
open() or os.popen(). It must be opened in binary mode ('wb' or 'w+b').\n\
 
1584
\n\
 
1585
If the value has (or contains an object that has) an unsupported type, a\n\
 
1586
ValueError exception is raised — but garbage data will also be written\n\
 
1587
to the file. The object will not be properly read back by load()\n\
 
1588
\n\
 
1589
The version argument indicates the data format that dump should use.");
 
1590
 
 
1591
static PyObject *
 
1592
marshal_load(PyObject *self, PyObject *f)
 
1593
{
 
1594
    PyObject *data, *result;
 
1595
    _Py_IDENTIFIER(read);
 
1596
    RFILE rf;
 
1597
 
 
1598
    /*
 
1599
     * Make a call to the read method, but read zero bytes.
 
1600
     * This is to ensure that the object passed in at least
 
1601
     * has a read method which returns bytes.
 
1602
     * This can be removed if we guarantee good error handling
 
1603
     * for r_string()
 
1604
     */
 
1605
    data = _PyObject_CallMethodId(f, &PyId_read, "i", 0);
 
1606
    if (data == NULL)
 
1607
        return NULL;
 
1608
    if (!PyBytes_Check(data)) {
 
1609
        PyErr_Format(PyExc_TypeError,
 
1610
                     "f.read() returned not bytes but %.100s",
 
1611
                     data->ob_type->tp_name);
 
1612
        result = NULL;
 
1613
    }
 
1614
    else {
 
1615
        rf.depth = 0;
 
1616
        rf.fp = NULL;
 
1617
        rf.readable = f;
 
1618
        rf.current_filename = NULL;
 
1619
        rf.ptr = rf.end = NULL;
 
1620
        rf.buf = NULL;
 
1621
        if ((rf.refs = PyList_New(0)) != NULL) {
 
1622
            result = read_object(&rf);
 
1623
            Py_DECREF(rf.refs);
 
1624
            if (rf.buf != NULL)
 
1625
                PyMem_FREE(rf.buf);
 
1626
        } else
 
1627
            result = NULL;
 
1628
    }
 
1629
    Py_DECREF(data);
 
1630
    return result;
 
1631
}
 
1632
 
 
1633
PyDoc_STRVAR(load_doc,
 
1634
"load(file)\n\
 
1635
\n\
 
1636
Read one value from the open file and return it. If no valid value is\n\
 
1637
read (e.g. because the data has a different Python version’s\n\
 
1638
incompatible marshal format), raise EOFError, ValueError or TypeError.\n\
 
1639
The file must be an open file object opened in binary mode ('rb' or\n\
 
1640
'r+b').\n\
 
1641
\n\
 
1642
Note: If an object containing an unsupported type was marshalled with\n\
 
1643
dump(), load() will substitute None for the unmarshallable type.");
 
1644
 
 
1645
 
 
1646
static PyObject *
 
1647
marshal_dumps(PyObject *self, PyObject *args)
 
1648
{
 
1649
    PyObject *x;
 
1650
    int version = Py_MARSHAL_VERSION;
 
1651
    if (!PyArg_ParseTuple(args, "O|i:dumps", &x, &version))
 
1652
        return NULL;
 
1653
    return PyMarshal_WriteObjectToString(x, version);
 
1654
}
 
1655
 
 
1656
PyDoc_STRVAR(dumps_doc,
 
1657
"dumps(value[, version])\n\
 
1658
\n\
 
1659
Return the string that would be written to a file by dump(value, file).\n\
 
1660
The value must be a supported type. Raise a ValueError exception if\n\
 
1661
value has (or contains an object that has) an unsupported type.\n\
 
1662
\n\
 
1663
The version argument indicates the data format that dumps should use.");
 
1664
 
 
1665
 
 
1666
static PyObject *
 
1667
marshal_loads(PyObject *self, PyObject *args)
 
1668
{
 
1669
    RFILE rf;
 
1670
    Py_buffer p;
 
1671
    char *s;
 
1672
    Py_ssize_t n;
 
1673
    PyObject* result;
 
1674
    if (!PyArg_ParseTuple(args, "y*:loads", &p))
 
1675
        return NULL;
 
1676
    s = p.buf;
 
1677
    n = p.len;
 
1678
    rf.fp = NULL;
 
1679
    rf.readable = NULL;
 
1680
    rf.current_filename = NULL;
 
1681
    rf.ptr = s;
 
1682
    rf.end = s + n;
 
1683
    rf.depth = 0;
 
1684
    if ((rf.refs = PyList_New(0)) == NULL)
 
1685
        return NULL;
 
1686
    result = read_object(&rf);
 
1687
    PyBuffer_Release(&p);
 
1688
    Py_DECREF(rf.refs);
 
1689
    return result;
 
1690
}
 
1691
 
 
1692
PyDoc_STRVAR(loads_doc,
 
1693
"loads(bytes)\n\
 
1694
\n\
 
1695
Convert the bytes object to a value. If no valid value is found, raise\n\
 
1696
EOFError, ValueError or TypeError. Extra characters in the input are\n\
 
1697
ignored.");
 
1698
 
 
1699
static PyMethodDef marshal_methods[] = {
 
1700
    {"dump",            marshal_dump,   METH_VARARGS,   dump_doc},
 
1701
    {"load",            marshal_load,   METH_O,         load_doc},
 
1702
    {"dumps",           marshal_dumps,  METH_VARARGS,   dumps_doc},
 
1703
    {"loads",           marshal_loads,  METH_VARARGS,   loads_doc},
 
1704
    {NULL,              NULL}           /* sentinel */
 
1705
};
 
1706
 
 
1707
 
 
1708
PyDoc_STRVAR(module_doc,
 
1709
"This module contains functions that can read and write Python values in\n\
 
1710
a binary format. The format is specific to Python, but independent of\n\
 
1711
machine architecture issues.\n\
 
1712
\n\
 
1713
Not all Python object types are supported; in general, only objects\n\
 
1714
whose value is independent from a particular invocation of Python can be\n\
 
1715
written and read by this module. The following types are supported:\n\
 
1716
None, integers, floating point numbers, strings, bytes, bytearrays,\n\
 
1717
tuples, lists, sets, dictionaries, and code objects, where it\n\
 
1718
should be understood that tuples, lists and dictionaries are only\n\
 
1719
supported as long as the values contained therein are themselves\n\
 
1720
supported; and recursive lists and dictionaries should not be written\n\
 
1721
(they will cause infinite loops).\n\
 
1722
\n\
 
1723
Variables:\n\
 
1724
\n\
 
1725
version -- indicates the format that the module uses. Version 0 is the\n\
 
1726
    historical format, version 1 shares interned strings and version 2\n\
 
1727
    uses a binary format for floating point numbers.\n\
 
1728
    Version 3 shares common object references (New in version 3.4).\n\
 
1729
\n\
 
1730
Functions:\n\
 
1731
\n\
 
1732
dump() -- write value to a file\n\
 
1733
load() -- read value from a file\n\
 
1734
dumps() -- write value to a string\n\
 
1735
loads() -- read value from a string");
 
1736
 
 
1737
 
 
1738
 
 
1739
static struct PyModuleDef marshalmodule = {
 
1740
    PyModuleDef_HEAD_INIT,
 
1741
    "marshal",
 
1742
    module_doc,
 
1743
    0,
 
1744
    marshal_methods,
 
1745
    NULL,
 
1746
    NULL,
 
1747
    NULL,
 
1748
    NULL
 
1749
};
 
1750
 
 
1751
PyMODINIT_FUNC
 
1752
PyMarshal_Init(void)
 
1753
{
 
1754
    PyObject *mod = PyModule_Create(&marshalmodule);
 
1755
    if (mod == NULL)
 
1756
        return NULL;
 
1757
    PyModule_AddIntConstant(mod, "version", Py_MARSHAL_VERSION);
 
1758
    return mod;
 
1759
}