3 #include "structmember.h"
5 PyDoc_STRVAR(cPickle_module_documentation
,
6 "C implementation and optimization of the Python pickle module.");
10 #define Py_eval_input eval_input
11 #endif /* Py_eval_input */
13 #define DEL_LIST_SLICE(list, from, to) (PyList_SetSlice(list, from, to, NULL))
15 #define WRITE_BUF_SIZE 256
17 /* Bump this when new opcodes are added to the pickle protocol. */
18 #define HIGHEST_PROTOCOL 2
21 * Pickle opcodes. These must be kept in synch with pickle.py. Extensive
22 * docs are in pickletools.py.
42 #define SHORT_BINSTRING 'U'
44 #define BINUNICODE 'X'
49 #define EMPTY_DICT '}'
54 #define LONG_BINGET 'j'
56 #define EMPTY_LIST ']'
60 #define LONG_BINPUT 'r'
63 #define EMPTY_TUPLE ')'
67 #define PROTO '\x80' /* identify pickle protocol */
68 #define NEWOBJ '\x81' /* build object by applying cls.__new__ to argtuple */
69 #define EXT1 '\x82' /* push object from extension registry; 1-byte index */
70 #define EXT2 '\x83' /* ditto, but 2-byte index */
71 #define EXT4 '\x84' /* ditto, but 4-byte index */
72 #define TUPLE1 '\x85' /* build 1-tuple from stack top */
73 #define TUPLE2 '\x86' /* build 2-tuple from two topmost stack items */
74 #define TUPLE3 '\x87' /* build 3-tuple from three topmost stack items */
75 #define NEWTRUE '\x88' /* push True */
76 #define NEWFALSE '\x89' /* push False */
77 #define LONG1 '\x8a' /* push long from < 256 bytes */
78 #define LONG4 '\x8b' /* push really big long */
80 /* There aren't opcodes -- they're ways to pickle bools before protocol 2,
81 * so that unpicklers written before bools were introduced unpickle them
82 * as ints, but unpicklers after can recognize that bools were intended.
83 * Note that protocol 2 added direct ways to pickle bools.
90 /* Keep in synch with pickle.Pickler._BATCHSIZE. This is how many elements
91 * batch_list/dict() pumps out before doing APPENDS/SETITEMS. Nothing will
92 * break if this gets out of synch with pickle.py, but it's unclear that
93 * would help anything either.
95 #define BATCHSIZE 1000
97 static char MARKv
= MARK
;
99 static PyObject
*PickleError
;
100 static PyObject
*PicklingError
;
101 static PyObject
*UnpickleableError
;
102 static PyObject
*UnpicklingError
;
103 static PyObject
*BadPickleGet
;
105 /* As the name says, an empty tuple. */
106 static PyObject
*empty_tuple
;
108 /* copy_reg.dispatch_table, {type_object: pickling_function} */
109 static PyObject
*dispatch_table
;
111 /* For EXT[124] opcodes. */
112 /* copy_reg._extension_registry, {(module_name, function_name): code} */
113 static PyObject
*extension_registry
;
114 /* copy_reg._inverted_registry, {code: (module_name, function_name)} */
115 static PyObject
*inverted_registry
;
116 /* copy_reg._extension_cache, {code: object} */
117 static PyObject
*extension_cache
;
119 /* For looking up name pairs in copy_reg._extension_registry. */
120 static PyObject
*two_tuple
;
122 static PyObject
*__class___str
, *__getinitargs___str
, *__dict___str
,
123 *__getstate___str
, *__setstate___str
, *__name___str
, *__reduce___str
,
125 *write_str
, *append_str
,
126 *read_str
, *readline_str
, *__main___str
,
127 *copy_reg_str
, *dispatch_table_str
;
129 /*************************************************************************
130 Internal Data type for pickle data. */
134 int length
; /* number of initial slots in data currently used */
135 int size
; /* number of slots in data allocated */
140 Pdata_dealloc(Pdata
*self
)
145 for (i
= self
->length
, p
= self
->data
; --i
>= 0; p
++) {
153 static PyTypeObject PdataType
= {
154 PyObject_HEAD_INIT(NULL
) 0, "cPickle.Pdata", sizeof(Pdata
), 0,
155 (destructor
)Pdata_dealloc
,
156 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0L,0L,0L,0L, ""
159 #define Pdata_Check(O) ((O)->ob_type == &PdataType)
166 if (!(self
= PyObject_New(Pdata
, &PdataType
)))
170 self
->data
= malloc(self
->size
* sizeof(PyObject
*));
172 return (PyObject
*)self
;
174 return PyErr_NoMemory();
180 PyErr_SetString(UnpicklingError
, "unpickling stack underflow");
184 /* Retain only the initial clearto items. If clearto >= the current
185 * number of items, this is a (non-erroneous) NOP.
188 Pdata_clear(Pdata
*self
, int clearto
)
193 if (clearto
< 0) return stackUnderflow();
194 if (clearto
>= self
->length
) return 0;
196 for (i
= self
->length
, p
= self
->data
+ clearto
;
201 self
->length
= clearto
;
207 Pdata_grow(Pdata
*self
)
213 bigger
= self
->size
<< 1;
214 if (bigger
<= 0) /* was 0, or new value overflows */
216 if ((int)(size_t)bigger
!= bigger
)
218 nbytes
= (size_t)bigger
* sizeof(PyObject
*);
219 if (nbytes
/ sizeof(PyObject
*) != (size_t)bigger
)
221 tmp
= realloc(self
->data
, nbytes
);
233 /* D is a Pdata*. Pop the topmost element and store it into V, which
234 * must be an lvalue holding PyObject*. On stack underflow, UnpicklingError
235 * is raised and V is set to NULL. D and V may be evaluated several times.
237 #define PDATA_POP(D, V) { \
239 (V) = (D)->data[--((D)->length)]; \
241 PyErr_SetString(UnpicklingError, "bad pickle data"); \
246 /* PDATA_PUSH and PDATA_APPEND both push rvalue PyObject* O on to Pdata*
247 * D. If the Pdata stack can't be grown to hold the new value, both
248 * raise MemoryError and execute "return ER". The difference is in ownership
249 * of O after: _PUSH transfers ownership of O from the caller to the stack
250 * (no incref of O is done, and in case of error O is decrefed), while
251 * _APPEND pushes a new reference.
254 /* Push O on stack D, giving ownership of O to the stack. */
255 #define PDATA_PUSH(D, O, ER) { \
256 if (((Pdata*)(D))->length == ((Pdata*)(D))->size && \
257 Pdata_grow((Pdata*)(D)) < 0) { \
261 ((Pdata*)(D))->data[((Pdata*)(D))->length++] = (O); \
264 /* Push O on stack D, pushing a new reference. */
265 #define PDATA_APPEND(D, O, ER) { \
266 if (((Pdata*)(D))->length == ((Pdata*)(D))->size && \
267 Pdata_grow((Pdata*)(D)) < 0) \
270 ((Pdata*)(D))->data[((Pdata*)(D))->length++] = (O); \
275 Pdata_popTuple(Pdata
*self
, int start
)
280 l
= self
->length
-start
;
284 for (i
= start
, j
= 0 ; j
< l
; i
++, j
++)
285 PyTuple_SET_ITEM(r
, j
, self
->data
[i
]);
287 self
->length
= start
;
292 Pdata_popList(Pdata
*self
, int start
)
297 l
=self
->length
-start
;
298 if (!( r
=PyList_New(l
))) return NULL
;
299 for (i
=start
, j
=0 ; j
< l
; i
++, j
++)
300 PyList_SET_ITEM(r
, j
, self
->data
[i
]);
306 /*************************************************************************/
308 #define ARG_TUP(self, o) { \
309 if (self->arg || (self->arg=PyTuple_New(1))) { \
310 Py_XDECREF(PyTuple_GET_ITEM(self->arg,0)); \
311 PyTuple_SET_ITEM(self->arg,0,o); \
318 #define FREE_ARG_TUP(self) { \
319 if (self->arg->ob_refcnt > 1) { \
320 Py_DECREF(self->arg); \
325 typedef struct Picklerobject
{
333 PyObject
*inst_pers_func
;
335 /* pickle protocol number, >= 0 */
338 /* bool, true if proto > 0 */
341 int fast
; /* Fast mode doesn't save in memo, don't use if circ ref */
343 int (*write_func
)(struct Picklerobject
*, const char *, Py_ssize_t
);
346 PyObject
*dispatch_table
;
347 int fast_container
; /* count nested container dumps */
351 #ifndef PY_CPICKLE_FAST_LIMIT
352 #define PY_CPICKLE_FAST_LIMIT 50
355 static PyTypeObject Picklertype
;
357 typedef struct Unpicklerobject
{
368 PyObject
*last_string
;
372 Py_ssize_t (*read_func
)(struct Unpicklerobject
*, char **, Py_ssize_t
);
373 Py_ssize_t (*readline_func
)(struct Unpicklerobject
*, char **);
376 PyObject
*find_class
;
379 static PyTypeObject Unpicklertype
;
381 /* Forward decls that need the above structs */
382 static int save(Picklerobject
*, PyObject
*, int);
383 static int put2(Picklerobject
*, PyObject
*);
387 cPickle_ErrFormat(PyObject
*ErrType
, char *stringformat
, char *format
, ...)
390 PyObject
*args
=0, *retval
=0;
391 va_start(va
, format
);
393 if (format
) args
= Py_VaBuildValue(format
, va
);
395 if (format
&& ! args
) return NULL
;
396 if (stringformat
&& !(retval
=PyString_FromString(stringformat
)))
402 v
=PyString_Format(retval
, args
);
405 if (! v
) return NULL
;
410 if (args
) retval
=args
;
412 PyErr_SetObject(ErrType
,Py_None
);
415 PyErr_SetObject(ErrType
,retval
);
421 write_file(Picklerobject
*self
, const char *s
, Py_ssize_t n
)
423 size_t nbyteswritten
;
430 /* String too large */
434 Py_BEGIN_ALLOW_THREADS
435 nbyteswritten
= fwrite(s
, sizeof(char), n
, self
->fp
);
437 if (nbyteswritten
!= (size_t)n
) {
438 PyErr_SetFromErrno(PyExc_IOError
);
446 write_cStringIO(Picklerobject
*self
, const char *s
, Py_ssize_t n
)
452 if (PycStringIO
->cwrite((PyObject
*)self
->file
, s
, n
) != n
) {
460 write_none(Picklerobject
*self
, const char *s
, Py_ssize_t n
)
462 if (s
== NULL
) return 0;
463 if (n
> INT_MAX
) return -1;
468 write_other(Picklerobject
*self
, const char *s
, Py_ssize_t _n
)
470 PyObject
*py_str
= 0, *junk
= 0;
477 if (!( self
->buf_size
)) return 0;
478 py_str
= PyString_FromStringAndSize(self
->write_buf
,
484 if (self
->buf_size
&& (n
+ self
->buf_size
) > WRITE_BUF_SIZE
) {
485 if (write_other(self
, NULL
, 0) < 0)
489 if (n
> WRITE_BUF_SIZE
) {
491 PyString_FromStringAndSize(s
, n
)))
495 memcpy(self
->write_buf
+ self
->buf_size
, s
, n
);
502 /* object with write method */
503 ARG_TUP(self
, py_str
);
505 junk
= PyObject_Call(self
->write
, self
->arg
, NULL
);
508 if (junk
) Py_DECREF(junk
);
512 PDATA_PUSH(self
->file
, py_str
, -1);
520 read_file(Unpicklerobject
*self
, char **s
, Py_ssize_t n
)
524 if (self
->buf_size
== 0) {
527 size
= ((n
< 32) ? 32 : n
);
528 if (!( self
->buf
= (char *)malloc(size
))) {
533 self
->buf_size
= size
;
535 else if (n
> self
->buf_size
) {
536 char *newbuf
= (char *)realloc(self
->buf
, n
);
545 Py_BEGIN_ALLOW_THREADS
546 nbytesread
= fread(self
->buf
, sizeof(char), n
, self
->fp
);
548 if (nbytesread
!= (size_t)n
) {
549 if (feof(self
->fp
)) {
550 PyErr_SetNone(PyExc_EOFError
);
554 PyErr_SetFromErrno(PyExc_IOError
);
565 readline_file(Unpicklerobject
*self
, char **s
)
569 if (self
->buf_size
== 0) {
570 if (!( self
->buf
= (char *)malloc(40))) {
581 for (; i
< (self
->buf_size
- 1); i
++) {
582 if (feof(self
->fp
) ||
583 (self
->buf
[i
] = getc(self
->fp
)) == '\n') {
584 self
->buf
[i
+ 1] = '\0';
589 bigger
= self
->buf_size
<< 1;
590 if (bigger
<= 0) { /* overflow */
594 newbuf
= (char *)realloc(self
->buf
, bigger
);
600 self
->buf_size
= bigger
;
606 read_cStringIO(Unpicklerobject
*self
, char **s
, Py_ssize_t n
)
610 if (PycStringIO
->cread((PyObject
*)self
->file
, &ptr
, n
) != n
) {
611 PyErr_SetNone(PyExc_EOFError
);
622 readline_cStringIO(Unpicklerobject
*self
, char **s
)
627 if ((n
= PycStringIO
->creadline((PyObject
*)self
->file
, &ptr
)) < 0) {
638 read_other(Unpicklerobject
*self
, char **s
, Py_ssize_t n
)
640 PyObject
*bytes
, *str
=0;
642 if (!( bytes
= PyInt_FromSsize_t(n
))) return -1;
644 ARG_TUP(self
, bytes
);
646 str
= PyObject_Call(self
->read
, self
->arg
, NULL
);
649 if (! str
) return -1;
651 Py_XDECREF(self
->last_string
);
652 self
->last_string
= str
;
654 if (! (*s
= PyString_AsString(str
))) return -1;
660 readline_other(Unpicklerobject
*self
, char **s
)
665 if (!( str
= PyObject_CallObject(self
->readline
, empty_tuple
))) {
669 if ((str_size
= PyString_Size(str
)) < 0)
672 Py_XDECREF(self
->last_string
);
673 self
->last_string
= str
;
675 if (! (*s
= PyString_AsString(str
)))
681 /* Copy the first n bytes from s into newly malloc'ed memory, plus a
682 * trailing 0 byte. Return a pointer to that, or NULL if out of memory.
683 * The caller is responsible for free()'ing the return value.
686 pystrndup(const char *s
, int n
)
688 char *r
= (char *)malloc(n
+1);
690 return (char*)PyErr_NoMemory();
698 get(Picklerobject
*self
, PyObject
*id
)
700 PyObject
*value
, *mv
;
705 if (!( mv
= PyDict_GetItem(self
->memo
, id
))) {
706 PyErr_SetObject(PyExc_KeyError
, id
);
710 if (!( value
= PyTuple_GetItem(mv
, 0)))
713 if (!( PyInt_Check(value
))) {
714 PyErr_SetString(PicklingError
, "no int where int expected in memo");
717 c_value
= PyInt_AS_LONG((PyIntObject
*)value
);
721 PyOS_snprintf(s
+ 1, sizeof(s
) - 1, "%ld\n", c_value
);
724 else if (Pdata_Check(self
->file
)) {
725 if (write_other(self
, NULL
, 0) < 0) return -1;
726 PDATA_APPEND(self
->file
, mv
, -1);
732 s
[1] = (int)(c_value
& 0xff);
737 s
[1] = (int)(c_value
& 0xff);
738 s
[2] = (int)((c_value
>> 8) & 0xff);
739 s
[3] = (int)((c_value
>> 16) & 0xff);
740 s
[4] = (int)((c_value
>> 24) & 0xff);
745 if (self
->write_func(self
, s
, len
) < 0)
753 put(Picklerobject
*self
, PyObject
*ob
)
755 if (ob
->ob_refcnt
< 2 || self
->fast
)
758 return put2(self
, ob
);
763 put2(Picklerobject
*self
, PyObject
*ob
)
769 PyObject
*py_ob_id
= 0, *memo_len
= 0, *t
= 0;
774 if ((p
= PyDict_Size(self
->memo
)) < 0)
777 /* Make sure memo keys are positive! */
779 * XXX And does "positive" really mean non-negative?
780 * XXX pickle.py starts with PUT index 0, not 1. This makes for
781 * XXX gratuitous differences between the pickling modules.
785 if (!( py_ob_id
= PyLong_FromVoidPtr(ob
)))
788 if (!( memo_len
= PyInt_FromLong(p
)))
791 if (!( t
= PyTuple_New(2)))
794 PyTuple_SET_ITEM(t
, 0, memo_len
);
796 PyTuple_SET_ITEM(t
, 1, ob
);
799 if (PyDict_SetItem(self
->memo
, py_ob_id
, t
) < 0)
804 PyOS_snprintf(c_str
+ 1, sizeof(c_str
) - 1, "%d\n", p
);
807 else if (Pdata_Check(self
->file
)) {
808 if (write_other(self
, NULL
, 0) < 0) return -1;
809 PDATA_APPEND(self
->file
, memo_len
, -1);
810 res
=0; /* Job well done ;) */
815 c_str
[0] = LONG_BINPUT
;
816 c_str
[1] = (int)(p
& 0xff);
817 c_str
[2] = (int)((p
>> 8) & 0xff);
818 c_str
[3] = (int)((p
>> 16) & 0xff);
819 c_str
[4] = (int)((p
>> 24) & 0xff);
829 if (self
->write_func(self
, c_str
, len
) < 0)
835 Py_XDECREF(py_ob_id
);
836 Py_XDECREF(memo_len
);
843 whichmodule(PyObject
*global
, PyObject
*global_name
)
846 PyObject
*module
= 0, *modules_dict
= 0,
847 *global_name_attr
= 0, *name
= 0;
849 module
= PyObject_GetAttrString(global
, "__module__");
852 if (PyErr_ExceptionMatches(PyExc_AttributeError
))
857 if (!( modules_dict
= PySys_GetObject("modules")))
861 while ((j
= PyDict_Next(modules_dict
, &i
, &name
, &module
))) {
863 if (PyObject_Compare(name
, __main___str
)==0) continue;
865 global_name_attr
= PyObject_GetAttr(module
, global_name
);
866 if (!global_name_attr
) {
867 if (PyErr_ExceptionMatches(PyExc_AttributeError
))
874 if (global_name_attr
!= global
) {
875 Py_DECREF(global_name_attr
);
879 Py_DECREF(global_name_attr
);
884 /* The following implements the rule in pickle.py added in 1.5
885 that used __main__ if no module is found. I don't actually
899 fast_save_enter(Picklerobject
*self
, PyObject
*obj
)
901 /* if fast_container < 0, we're doing an error exit. */
902 if (++self
->fast_container
>= PY_CPICKLE_FAST_LIMIT
) {
903 PyObject
*key
= NULL
;
904 if (self
->fast_memo
== NULL
) {
905 self
->fast_memo
= PyDict_New();
906 if (self
->fast_memo
== NULL
) {
907 self
->fast_container
= -1;
911 key
= PyLong_FromVoidPtr(obj
);
914 if (PyDict_GetItem(self
->fast_memo
, key
)) {
916 PyErr_Format(PyExc_ValueError
,
917 "fast mode: can't pickle cyclic objects "
918 "including object type %s at %p",
919 obj
->ob_type
->tp_name
, obj
);
920 self
->fast_container
= -1;
923 if (PyDict_SetItem(self
->fast_memo
, key
, Py_None
) < 0) {
925 self
->fast_container
= -1;
934 fast_save_leave(Picklerobject
*self
, PyObject
*obj
)
936 if (self
->fast_container
-- >= PY_CPICKLE_FAST_LIMIT
) {
937 PyObject
*key
= PyLong_FromVoidPtr(obj
);
940 if (PyDict_DelItem(self
->fast_memo
, key
) < 0) {
950 save_none(Picklerobject
*self
, PyObject
*args
)
952 static char none
= NONE
;
953 if (self
->write_func(self
, &none
, 1) < 0)
960 save_bool(Picklerobject
*self
, PyObject
*args
)
962 static const char *buf
[2] = {FALSE
, TRUE
};
963 static char len
[2] = {sizeof(FALSE
)-1, sizeof(TRUE
)-1};
964 long l
= PyInt_AS_LONG((PyIntObject
*)args
);
966 if (self
->proto
>= 2) {
967 char opcode
= l
? NEWTRUE
: NEWFALSE
;
968 if (self
->write_func(self
, &opcode
, 1) < 0)
971 else if (self
->write_func(self
, buf
[l
], len
[l
]) < 0)
977 save_int(Picklerobject
*self
, PyObject
*args
)
980 long l
= PyInt_AS_LONG((PyIntObject
*)args
);
989 /* Text-mode pickle, or long too big to fit in the 4-byte
990 * signed BININT format: store as a string.
993 PyOS_snprintf(c_str
+ 1, sizeof(c_str
) - 1, "%ld\n", l
);
994 if (self
->write_func(self
, c_str
, strlen(c_str
)) < 0)
998 /* Binary pickle and l fits in a signed 4-byte int. */
999 c_str
[1] = (int)( l
& 0xff);
1000 c_str
[2] = (int)((l
>> 8) & 0xff);
1001 c_str
[3] = (int)((l
>> 16) & 0xff);
1002 c_str
[4] = (int)((l
>> 24) & 0xff);
1004 if ((c_str
[4] == 0) && (c_str
[3] == 0)) {
1005 if (c_str
[2] == 0) {
1019 if (self
->write_func(self
, c_str
, len
) < 0)
1028 save_long(Picklerobject
*self
, PyObject
*args
)
1032 PyObject
*repr
= NULL
;
1034 static char l
= LONG
;
1036 if (self
->proto
>= 2) {
1037 /* Linear-time pickling. */
1040 unsigned char *pdata
;
1043 int sign
= _PyLong_Sign(args
);
1046 /* It's 0 -- an empty bytestring. */
1049 i
= self
->write_func(self
, c_str
, 2);
1050 if (i
< 0) goto finally
;
1054 nbits
= _PyLong_NumBits(args
);
1055 if (nbits
== (size_t)-1 && PyErr_Occurred())
1057 /* How many bytes do we need? There are nbits >> 3 full
1058 * bytes of data, and nbits & 7 leftover bits. If there
1059 * are any leftover bits, then we clearly need another
1060 * byte. Wnat's not so obvious is that we *probably*
1061 * need another byte even if there aren't any leftovers:
1062 * the most-significant bit of the most-significant byte
1063 * acts like a sign bit, and it's usually got a sense
1064 * opposite of the one we need. The exception is longs
1065 * of the form -(2**(8*j-1)) for j > 0. Such a long is
1066 * its own 256's-complement, so has the right sign bit
1067 * even without the extra byte. That's a pain to check
1068 * for in advance, though, so we always grab an extra
1069 * byte at the start, and cut it back later if possible.
1071 nbytes
= (nbits
>> 3) + 1;
1072 if (nbytes
> INT_MAX
) {
1073 PyErr_SetString(PyExc_OverflowError
, "long too large "
1077 repr
= PyString_FromStringAndSize(NULL
, (int)nbytes
);
1078 if (repr
== NULL
) goto finally
;
1079 pdata
= (unsigned char *)PyString_AS_STRING(repr
);
1080 i
= _PyLong_AsByteArray((PyLongObject
*)args
,
1082 1 /* little endian */, 1 /* signed */);
1083 if (i
< 0) goto finally
;
1084 /* If the long is negative, this may be a byte more than
1085 * needed. This is so iff the MSB is all redundant sign
1088 if (sign
< 0 && nbytes
> 1 && pdata
[nbytes
- 1] == 0xff &&
1089 (pdata
[nbytes
- 2] & 0x80) != 0)
1094 c_str
[1] = (char)nbytes
;
1100 for (i
= 1; i
< 5; i
++) {
1101 c_str
[i
] = (char)(size
& 0xff);
1106 i
= self
->write_func(self
, c_str
, size
);
1107 if (i
< 0) goto finally
;
1108 i
= self
->write_func(self
, (char *)pdata
, (int)nbytes
);
1109 if (i
< 0) goto finally
;
1114 /* proto < 2: write the repr and newline. This is quadratic-time
1115 * (in the number of digits), in both directions.
1117 if (!( repr
= PyObject_Repr(args
)))
1120 if ((size
= PyString_Size(repr
)) < 0)
1123 if (self
->write_func(self
, &l
, 1) < 0)
1126 if (self
->write_func(self
,
1127 PyString_AS_STRING((PyStringObject
*)repr
),
1131 if (self
->write_func(self
, "\n", 1) < 0)
1143 save_float(Picklerobject
*self
, PyObject
*args
)
1145 double x
= PyFloat_AS_DOUBLE((PyFloatObject
*)args
);
1150 if (_PyFloat_Pack8(x
, (unsigned char *)&str
[1], 0) < 0)
1152 if (self
->write_func(self
, str
, 9) < 0)
1158 PyOS_ascii_formatd(c_str
+ 1, sizeof(c_str
) - 2, "%.17g", x
);
1159 /* Extend the formatted string with a newline character */
1160 strcat(c_str
, "\n");
1162 if (self
->write_func(self
, c_str
, strlen(c_str
)) < 0)
1171 save_string(Picklerobject
*self
, PyObject
*args
, int doput
)
1176 if ((size
= PyString_Size(args
)) < 0)
1182 static char string
= STRING
;
1184 if (!( repr
= PyObject_Repr(args
)))
1187 if ((len
= PyString_Size(repr
)) < 0)
1189 repr_str
= PyString_AS_STRING((PyStringObject
*)repr
);
1191 if (self
->write_func(self
, &string
, 1) < 0)
1194 if (self
->write_func(self
, repr_str
, len
) < 0)
1197 if (self
->write_func(self
, "\n", 1) < 0)
1206 if ((size
= PyString_Size(args
)) < 0)
1210 c_str
[0] = SHORT_BINSTRING
;
1214 else if (size
<= INT_MAX
) {
1215 c_str
[0] = BINSTRING
;
1216 for (i
= 1; i
< 5; i
++)
1217 c_str
[i
] = (int)(size
>> ((i
- 1) * 8));
1221 return -1; /* string too large */
1223 if (self
->write_func(self
, c_str
, len
) < 0)
1226 if (size
> 128 && Pdata_Check(self
->file
)) {
1227 if (write_other(self
, NULL
, 0) < 0) return -1;
1228 PDATA_APPEND(self
->file
, args
, -1);
1231 if (self
->write_func(self
,
1233 (PyStringObject
*)args
),
1240 if (put(self
, args
) < 0)
1251 #ifdef Py_USING_UNICODE
1252 /* A copy of PyUnicode_EncodeRawUnicodeEscape() that also translates
1253 backslash and newline characters to \uXXXX escapes. */
1255 modified_EncodeRawUnicodeEscape(const Py_UNICODE
*s
, int size
)
1261 static const char *hexdigit
= "0123456789ABCDEF";
1263 repr
= PyString_FromStringAndSize(NULL
, 6 * size
);
1269 p
= q
= PyString_AS_STRING(repr
);
1270 while (size
-- > 0) {
1271 Py_UNICODE ch
= *s
++;
1272 /* Map 16-bit characters to '\uxxxx' */
1273 if (ch
>= 256 || ch
== '\\' || ch
== '\n') {
1276 *p
++ = hexdigit
[(ch
>> 12) & 0xf];
1277 *p
++ = hexdigit
[(ch
>> 8) & 0xf];
1278 *p
++ = hexdigit
[(ch
>> 4) & 0xf];
1279 *p
++ = hexdigit
[ch
& 15];
1281 /* Copy everything else as-is */
1286 _PyString_Resize(&repr
, p
- q
);
1292 save_unicode(Picklerobject
*self
, PyObject
*args
, int doput
)
1294 Py_ssize_t size
, len
;
1297 if (!PyUnicode_Check(args
))
1302 static char string
= UNICODE
;
1304 repr
= modified_EncodeRawUnicodeEscape(
1305 PyUnicode_AS_UNICODE(args
), PyUnicode_GET_SIZE(args
));
1309 if ((len
= PyString_Size(repr
)) < 0)
1311 repr_str
= PyString_AS_STRING((PyStringObject
*)repr
);
1313 if (self
->write_func(self
, &string
, 1) < 0)
1316 if (self
->write_func(self
, repr_str
, len
) < 0)
1319 if (self
->write_func(self
, "\n", 1) < 0)
1328 if (!( repr
= PyUnicode_AsUTF8String(args
)))
1331 if ((size
= PyString_Size(repr
)) < 0)
1334 return -1; /* string too large */
1336 c_str
[0] = BINUNICODE
;
1337 for (i
= 1; i
< 5; i
++)
1338 c_str
[i
] = (int)(size
>> ((i
- 1) * 8));
1341 if (self
->write_func(self
, c_str
, len
) < 0)
1344 if (size
> 128 && Pdata_Check(self
->file
)) {
1345 if (write_other(self
, NULL
, 0) < 0)
1347 PDATA_APPEND(self
->file
, repr
, -1);
1350 if (self
->write_func(self
, PyString_AS_STRING(repr
),
1359 if (put(self
, args
) < 0)
1370 /* A helper for save_tuple. Push the len elements in tuple t on the stack. */
1372 store_tuple_elements(Picklerobject
*self
, PyObject
*t
, int len
)
1375 int res
= -1; /* guilty until proved innocent */
1377 assert(PyTuple_Size(t
) == len
);
1379 for (i
= 0; i
< len
; i
++) {
1380 PyObject
*element
= PyTuple_GET_ITEM(t
, i
);
1382 if (element
== NULL
)
1384 if (save(self
, element
, 0) < 0)
1393 /* Tuples are ubiquitous in the pickle protocols, so many techniques are
1394 * used across protocols to minimize the space needed to pickle them.
1395 * Tuples are also the only builtin immutable type that can be recursive
1396 * (a tuple can be reached from itself), and that requires some subtle
1397 * magic so that it works in all cases. IOW, this is a long routine.
1400 save_tuple(Picklerobject
*self
, PyObject
*args
)
1402 PyObject
*py_tuple_id
= NULL
;
1406 static char tuple
= TUPLE
;
1407 static char pop
= POP
;
1408 static char pop_mark
= POP_MARK
;
1409 static char len2opcode
[] = {EMPTY_TUPLE
, TUPLE1
, TUPLE2
, TUPLE3
};
1411 if ((len
= PyTuple_Size(args
)) < 0)
1418 c_str
[0] = EMPTY_TUPLE
;
1426 if (self
->write_func(self
, c_str
, len
) >= 0)
1428 /* Don't memoize an empty tuple. */
1432 /* A non-empty tuple. */
1434 /* id(tuple) isn't in the memo now. If it shows up there after
1435 * saving the tuple elements, the tuple must be recursive, in
1436 * which case we'll pop everything we put on the stack, and fetch
1437 * its value from the memo.
1439 py_tuple_id
= PyLong_FromVoidPtr(args
);
1440 if (py_tuple_id
== NULL
)
1443 if (len
<= 3 && self
->proto
>= 2) {
1444 /* Use TUPLE{1,2,3} opcodes. */
1445 if (store_tuple_elements(self
, args
, len
) < 0)
1447 if (PyDict_GetItem(self
->memo
, py_tuple_id
)) {
1448 /* pop the len elements */
1449 for (i
= 0; i
< len
; ++i
)
1450 if (self
->write_func(self
, &pop
, 1) < 0)
1452 /* fetch from memo */
1453 if (get(self
, py_tuple_id
) < 0)
1458 /* Not recursive. */
1459 if (self
->write_func(self
, len2opcode
+ len
, 1) < 0)
1464 /* proto < 2 and len > 0, or proto >= 2 and len > 3.
1465 * Generate MARK elt1 elt2 ... TUPLE
1467 if (self
->write_func(self
, &MARKv
, 1) < 0)
1470 if (store_tuple_elements(self
, args
, len
) < 0)
1473 if (PyDict_GetItem(self
->memo
, py_tuple_id
)) {
1474 /* pop the stack stuff we pushed */
1476 if (self
->write_func(self
, &pop_mark
, 1) < 0)
1480 /* Note that we pop one more than len, to remove
1483 for (i
= 0; i
<= len
; i
++)
1484 if (self
->write_func(self
, &pop
, 1) < 0)
1487 /* fetch from memo */
1488 if (get(self
, py_tuple_id
) >= 0)
1493 /* Not recursive. */
1494 if (self
->write_func(self
, &tuple
, 1) < 0)
1498 if (put(self
, args
) >= 0)
1502 Py_XDECREF(py_tuple_id
);
1506 /* iter is an iterator giving items, and we batch up chunks of
1507 * MARK item item ... item APPENDS
1508 * opcode sequences. Calling code should have arranged to first create an
1509 * empty list, or list-like object, for the APPENDS to operate on.
1510 * Returns 0 on success, <0 on error.
1513 batch_list(Picklerobject
*self
, PyObject
*iter
)
1516 PyObject
*slice
[BATCHSIZE
];
1519 static char append
= APPEND
;
1520 static char appends
= APPENDS
;
1522 assert(iter
!= NULL
);
1524 if (self
->proto
== 0) {
1525 /* APPENDS isn't available; do one at a time. */
1527 obj
= PyIter_Next(iter
);
1529 if (PyErr_Occurred())
1533 i
= save(self
, obj
, 0);
1537 if (self
->write_func(self
, &append
, 1) < 0)
1543 /* proto > 0: write in batches of BATCHSIZE. */
1545 /* Get next group of (no more than) BATCHSIZE elements. */
1546 for (n
= 0; n
< BATCHSIZE
; ++n
) {
1547 obj
= PyIter_Next(iter
);
1549 if (PyErr_Occurred())
1557 /* Pump out MARK, slice[0:n], APPENDS. */
1558 if (self
->write_func(self
, &MARKv
, 1) < 0)
1560 for (i
= 0; i
< n
; ++i
) {
1561 if (save(self
, slice
[i
], 0) < 0)
1564 if (self
->write_func(self
, &appends
, 1) < 0)
1568 if (save(self
, slice
[0], 0) < 0)
1570 if (self
->write_func(self
, &append
, 1) < 0)
1574 for (i
= 0; i
< n
; ++i
) {
1575 Py_DECREF(slice
[i
]);
1577 } while (n
== BATCHSIZE
);
1582 Py_DECREF(slice
[n
]);
1588 save_list(Picklerobject
*self
, PyObject
*args
)
1595 if (self
->fast
&& !fast_save_enter(self
, args
))
1598 /* Create an empty list. */
1609 if (self
->write_func(self
, s
, len
) < 0)
1612 /* Get list length, and bow out early if empty. */
1613 if ((len
= PyList_Size(args
)) < 0)
1618 if (put(self
, args
) >= 0)
1622 if (put2(self
, args
) < 0)
1625 /* Materialize the list elements. */
1626 iter
= PyObject_GetIter(args
);
1629 res
= batch_list(self
, iter
);
1633 if (self
->fast
&& !fast_save_leave(self
, args
))
1640 /* iter is an iterator giving (key, value) pairs, and we batch up chunks of
1641 * MARK key value ... key value SETITEMS
1642 * opcode sequences. Calling code should have arranged to first create an
1643 * empty dict, or dict-like object, for the SETITEMS to operate on.
1644 * Returns 0 on success, <0 on error.
1646 * This is very much like batch_list(). The difference between saving
1647 * elements directly, and picking apart two-tuples, is so long-winded at
1648 * the C level, though, that attempts to combine these routines were too
1652 batch_dict(Picklerobject
*self
, PyObject
*iter
)
1655 PyObject
*slice
[BATCHSIZE
];
1658 static char setitem
= SETITEM
;
1659 static char setitems
= SETITEMS
;
1661 assert(iter
!= NULL
);
1663 if (self
->proto
== 0) {
1664 /* SETITEMS isn't available; do one at a time. */
1666 p
= PyIter_Next(iter
);
1668 if (PyErr_Occurred())
1672 if (!PyTuple_Check(p
) || PyTuple_Size(p
) != 2) {
1673 PyErr_SetString(PyExc_TypeError
, "dict items "
1674 "iterator must return 2-tuples");
1677 i
= save(self
, PyTuple_GET_ITEM(p
, 0), 0);
1679 i
= save(self
, PyTuple_GET_ITEM(p
, 1), 0);
1683 if (self
->write_func(self
, &setitem
, 1) < 0)
1689 /* proto > 0: write in batches of BATCHSIZE. */
1691 /* Get next group of (no more than) BATCHSIZE elements. */
1692 for (n
= 0; n
< BATCHSIZE
; ++n
) {
1693 p
= PyIter_Next(iter
);
1695 if (PyErr_Occurred())
1699 if (!PyTuple_Check(p
) || PyTuple_Size(p
) != 2) {
1700 PyErr_SetString(PyExc_TypeError
, "dict items "
1701 "iterator must return 2-tuples");
1708 /* Pump out MARK, slice[0:n], SETITEMS. */
1709 if (self
->write_func(self
, &MARKv
, 1) < 0)
1711 for (i
= 0; i
< n
; ++i
) {
1713 if (save(self
, PyTuple_GET_ITEM(p
, 0), 0) < 0)
1715 if (save(self
, PyTuple_GET_ITEM(p
, 1), 0) < 0)
1718 if (self
->write_func(self
, &setitems
, 1) < 0)
1723 if (save(self
, PyTuple_GET_ITEM(p
, 0), 0) < 0)
1725 if (save(self
, PyTuple_GET_ITEM(p
, 1), 0) < 0)
1727 if (self
->write_func(self
, &setitem
, 1) < 0)
1731 for (i
= 0; i
< n
; ++i
) {
1732 Py_DECREF(slice
[i
]);
1734 } while (n
== BATCHSIZE
);
1739 Py_DECREF(slice
[n
]);
1745 save_dict(Picklerobject
*self
, PyObject
*args
)
1752 if (self
->fast
&& !fast_save_enter(self
, args
))
1755 /* Create an empty dict. */
1766 if (self
->write_func(self
, s
, len
) < 0)
1769 /* Get dict size, and bow out early if empty. */
1770 if ((len
= PyDict_Size(args
)) < 0)
1774 if (put(self
, args
) >= 0)
1778 if (put2(self
, args
) < 0)
1781 /* Materialize the dict items. */
1782 iter
= PyObject_CallMethod(args
, "iteritems", "()");
1785 res
= batch_dict(self
, iter
);
1789 if (self
->fast
&& !fast_save_leave(self
, args
))
1797 save_inst(Picklerobject
*self
, PyObject
*args
)
1799 PyObject
*class = 0, *module
= 0, *name
= 0, *state
= 0,
1800 *getinitargs_func
= 0, *getstate_func
= 0, *class_args
= 0;
1801 char *module_str
, *name_str
;
1802 int module_size
, name_size
, res
= -1;
1804 static char inst
= INST
, obj
= OBJ
, build
= BUILD
;
1806 if (self
->fast
&& !fast_save_enter(self
, args
))
1809 if (self
->write_func(self
, &MARKv
, 1) < 0)
1812 if (!( class = PyObject_GetAttr(args
, __class___str
)))
1816 if (save(self
, class, 0) < 0)
1820 if ((getinitargs_func
= PyObject_GetAttr(args
, __getinitargs___str
))) {
1821 PyObject
*element
= 0;
1825 PyObject_Call(getinitargs_func
, empty_tuple
, NULL
)))
1828 if ((len
= PyObject_Size(class_args
)) < 0)
1831 for (i
= 0; i
< len
; i
++) {
1832 if (!( element
= PySequence_GetItem(class_args
, i
)))
1835 if (save(self
, element
, 0) < 0) {
1844 if (PyErr_ExceptionMatches(PyExc_AttributeError
))
1851 if (!( name
= ((PyClassObject
*)class)->cl_name
)) {
1852 PyErr_SetString(PicklingError
, "class has no name");
1856 if (!( module
= whichmodule(class, name
)))
1860 if ((module_size
= PyString_Size(module
)) < 0 ||
1861 (name_size
= PyString_Size(name
)) < 0)
1864 module_str
= PyString_AS_STRING((PyStringObject
*)module
);
1865 name_str
= PyString_AS_STRING((PyStringObject
*)name
);
1867 if (self
->write_func(self
, &inst
, 1) < 0)
1870 if (self
->write_func(self
, module_str
, module_size
) < 0)
1873 if (self
->write_func(self
, "\n", 1) < 0)
1876 if (self
->write_func(self
, name_str
, name_size
) < 0)
1879 if (self
->write_func(self
, "\n", 1) < 0)
1882 else if (self
->write_func(self
, &obj
, 1) < 0) {
1886 if ((getstate_func
= PyObject_GetAttr(args
, __getstate___str
))) {
1887 state
= PyObject_Call(getstate_func
, empty_tuple
, NULL
);
1892 if (PyErr_ExceptionMatches(PyExc_AttributeError
))
1897 if (!( state
= PyObject_GetAttr(args
, __dict___str
))) {
1898 if (PyErr_ExceptionMatches(PyExc_AttributeError
))
1907 if (!PyDict_Check(state
)) {
1908 if (put2(self
, args
) < 0)
1912 if (put(self
, args
) < 0)
1916 if (save(self
, state
, 0) < 0)
1919 if (self
->write_func(self
, &build
, 1) < 0)
1925 if (self
->fast
&& !fast_save_leave(self
, args
))
1931 Py_XDECREF(getinitargs_func
);
1932 Py_XDECREF(getstate_func
);
1933 Py_XDECREF(class_args
);
1940 save_global(Picklerobject
*self
, PyObject
*args
, PyObject
*name
)
1942 PyObject
*global_name
= 0, *module
= 0, *mod
= 0, *klass
= 0;
1943 char *name_str
, *module_str
;
1944 int module_size
, name_size
, res
= -1;
1946 static char global
= GLOBAL
;
1950 Py_INCREF(global_name
);
1953 if (!( global_name
= PyObject_GetAttr(args
, __name___str
)))
1957 if (!( module
= whichmodule(args
, global_name
)))
1960 if ((module_size
= PyString_Size(module
)) < 0 ||
1961 (name_size
= PyString_Size(global_name
)) < 0)
1964 module_str
= PyString_AS_STRING((PyStringObject
*)module
);
1965 name_str
= PyString_AS_STRING((PyStringObject
*)global_name
);
1967 /* XXX This can be doing a relative import. Clearly it shouldn't,
1968 but I don't know how to stop it. :-( */
1969 mod
= PyImport_ImportModule(module_str
);
1971 cPickle_ErrFormat(PicklingError
,
1972 "Can't pickle %s: import of module %s "
1974 "OS", args
, module
);
1977 klass
= PyObject_GetAttrString(mod
, name_str
);
1978 if (klass
== NULL
) {
1979 cPickle_ErrFormat(PicklingError
,
1980 "Can't pickle %s: attribute lookup %s.%s "
1982 "OSS", args
, module
, global_name
);
1985 if (klass
!= args
) {
1987 cPickle_ErrFormat(PicklingError
,
1988 "Can't pickle %s: it's not the same object "
1990 "OSS", args
, module
, global_name
);
1995 if (self
->proto
>= 2) {
1996 /* See whether this is in the extension registry, and if
1997 * so generate an EXT opcode.
1999 PyObject
*py_code
; /* extension code as Python object */
2000 long code
; /* extension code as C value */
2004 PyTuple_SET_ITEM(two_tuple
, 0, module
);
2005 PyTuple_SET_ITEM(two_tuple
, 1, global_name
);
2006 py_code
= PyDict_GetItem(extension_registry
, two_tuple
);
2007 if (py_code
== NULL
)
2008 goto gen_global
; /* not registered */
2010 /* Verify py_code has the right type and value. */
2011 if (!PyInt_Check(py_code
)) {
2012 cPickle_ErrFormat(PicklingError
, "Can't pickle %s: "
2013 "extension code %s isn't an integer",
2014 "OO", args
, py_code
);
2017 code
= PyInt_AS_LONG(py_code
);
2018 if (code
<= 0 || code
> 0x7fffffffL
) {
2019 cPickle_ErrFormat(PicklingError
, "Can't pickle %s: "
2020 "extension code %ld is out of range",
2025 /* Generate an EXT opcode. */
2028 c_str
[1] = (char)code
;
2031 else if (code
<= 0xffff) {
2033 c_str
[1] = (char)(code
& 0xff);
2034 c_str
[2] = (char)((code
>> 8) & 0xff);
2039 c_str
[1] = (char)(code
& 0xff);
2040 c_str
[2] = (char)((code
>> 8) & 0xff);
2041 c_str
[3] = (char)((code
>> 16) & 0xff);
2042 c_str
[4] = (char)((code
>> 24) & 0xff);
2046 if (self
->write_func(self
, c_str
, n
) >= 0)
2048 goto finally
; /* and don't memoize */
2052 if (self
->write_func(self
, &global
, 1) < 0)
2055 if (self
->write_func(self
, module_str
, module_size
) < 0)
2058 if (self
->write_func(self
, "\n", 1) < 0)
2061 if (self
->write_func(self
, name_str
, name_size
) < 0)
2064 if (self
->write_func(self
, "\n", 1) < 0)
2067 if (put(self
, args
) < 0)
2074 Py_XDECREF(global_name
);
2081 save_pers(Picklerobject
*self
, PyObject
*args
, PyObject
*f
)
2086 static char persid
= PERSID
, binpersid
= BINPERSID
;
2089 ARG_TUP(self
, args
);
2091 pid
= PyObject_Call(f
, self
->arg
, NULL
);
2094 if (! pid
) return -1;
2096 if (pid
!= Py_None
) {
2098 if (!PyString_Check(pid
)) {
2099 PyErr_SetString(PicklingError
,
2100 "persistent id must be string");
2104 if (self
->write_func(self
, &persid
, 1) < 0)
2107 if ((size
= PyString_Size(pid
)) < 0)
2110 if (self
->write_func(self
,
2112 (PyStringObject
*)pid
),
2116 if (self
->write_func(self
, "\n", 1) < 0)
2122 else if (save(self
, pid
, 1) >= 0) {
2123 if (self
->write_func(self
, &binpersid
, 1) < 0)
2140 /* We're saving ob, and args is the 2-thru-5 tuple returned by the
2141 * appropriate __reduce__ method for ob.
2144 save_reduce(Picklerobject
*self
, PyObject
*args
, PyObject
*ob
)
2148 PyObject
*state
= NULL
;
2149 PyObject
*listitems
= NULL
;
2150 PyObject
*dictitems
= NULL
;
2152 int use_newobj
= self
->proto
>= 2;
2154 static char reduce
= REDUCE
;
2155 static char build
= BUILD
;
2156 static char newobj
= NEWOBJ
;
2158 if (! PyArg_UnpackTuple(args
, "save_reduce", 2, 5,
2166 if (!PyTuple_Check(argtup
)) {
2167 PyErr_SetString(PicklingError
,
2168 "args from reduce() should be a tuple");
2172 if (state
== Py_None
)
2174 if (listitems
== Py_None
)
2176 if (dictitems
== Py_None
)
2179 /* Protocol 2 special case: if callable's name is __newobj__, use
2180 * NEWOBJ. This consumes a lot of code.
2183 PyObject
*temp
= PyObject_GetAttr(callable
, __name___str
);
2186 if (PyErr_ExceptionMatches(PyExc_AttributeError
))
2193 use_newobj
= PyString_Check(temp
) &&
2194 strcmp(PyString_AS_STRING(temp
),
2201 PyObject
*newargtup
;
2204 /* Sanity checks. */
2205 n
= PyTuple_Size(argtup
);
2207 PyErr_SetString(PicklingError
, "__newobj__ arglist "
2212 cls
= PyTuple_GET_ITEM(argtup
, 0);
2213 if (! PyObject_HasAttrString(cls
, "__new__")) {
2214 PyErr_SetString(PicklingError
, "args[0] from "
2215 "__newobj__ args has no __new__");
2219 /* XXX How could ob be NULL? */
2221 PyObject
*ob_dot_class
;
2223 ob_dot_class
= PyObject_GetAttr(ob
, __class___str
);
2224 if (ob_dot_class
== NULL
) {
2225 if (PyErr_ExceptionMatches(
2226 PyExc_AttributeError
))
2231 i
= ob_dot_class
!= cls
; /* true iff a problem */
2232 Py_XDECREF(ob_dot_class
);
2234 PyErr_SetString(PicklingError
, "args[0] from "
2235 "__newobj__ args has the wrong class");
2240 /* Save the class and its __new__ arguments. */
2241 if (save(self
, cls
, 0) < 0)
2244 newargtup
= PyTuple_New(n
-1); /* argtup[1:] */
2245 if (newargtup
== NULL
)
2247 for (i
= 1; i
< n
; ++i
) {
2248 PyObject
*temp
= PyTuple_GET_ITEM(argtup
, i
);
2250 PyTuple_SET_ITEM(newargtup
, i
-1, temp
);
2252 i
= save(self
, newargtup
, 0) < 0;
2253 Py_DECREF(newargtup
);
2257 /* Add NEWOBJ opcode. */
2258 if (self
->write_func(self
, &newobj
, 1) < 0)
2262 /* Not using NEWOBJ. */
2263 if (save(self
, callable
, 0) < 0 ||
2264 save(self
, argtup
, 0) < 0 ||
2265 self
->write_func(self
, &reduce
, 1) < 0)
2270 /* XXX How can ob be NULL? */
2272 if (state
&& !PyDict_Check(state
)) {
2273 if (put2(self
, ob
) < 0)
2276 else if (put(self
, ob
) < 0)
2281 if (listitems
&& batch_list(self
, listitems
) < 0)
2284 if (dictitems
&& batch_dict(self
, dictitems
) < 0)
2288 if (save(self
, state
, 0) < 0 ||
2289 self
->write_func(self
, &build
, 1) < 0)
2297 save(Picklerobject
*self
, PyObject
*args
, int pers_save
)
2300 PyObject
*py_ob_id
= 0, *__reduce__
= 0, *t
= 0;
2305 if (self
->nesting
++ > Py_GetRecursionLimit()){
2306 PyErr_SetString(PyExc_RuntimeError
,
2307 "maximum recursion depth exceeded");
2311 if (!pers_save
&& self
->pers_func
) {
2312 if ((tmp
= save_pers(self
, args
, self
->pers_func
)) != 0) {
2318 if (args
== Py_None
) {
2319 res
= save_none(self
, args
);
2323 type
= args
->ob_type
;
2325 switch (type
->tp_name
[0]) {
2327 if (args
== Py_False
|| args
== Py_True
) {
2328 res
= save_bool(self
, args
);
2333 if (type
== &PyInt_Type
) {
2334 res
= save_int(self
, args
);
2340 if (type
== &PyLong_Type
) {
2341 res
= save_long(self
, args
);
2347 if (type
== &PyFloat_Type
) {
2348 res
= save_float(self
, args
);
2354 if (type
== &PyTuple_Type
&& PyTuple_Size(args
) == 0) {
2355 res
= save_tuple(self
, args
);
2361 if ((type
== &PyString_Type
) && (PyString_GET_SIZE(args
) < 2)) {
2362 res
= save_string(self
, args
, 0);
2366 #ifdef Py_USING_UNICODE
2368 if ((type
== &PyUnicode_Type
) && (PyString_GET_SIZE(args
) < 2)) {
2369 res
= save_unicode(self
, args
, 0);
2375 if (args
->ob_refcnt
> 1) {
2376 if (!( py_ob_id
= PyLong_FromVoidPtr(args
)))
2379 if (PyDict_GetItem(self
->memo
, py_ob_id
)) {
2380 if (get(self
, py_ob_id
) < 0)
2388 switch (type
->tp_name
[0]) {
2390 if (type
== &PyString_Type
) {
2391 res
= save_string(self
, args
, 1);
2396 #ifdef Py_USING_UNICODE
2398 if (type
== &PyUnicode_Type
) {
2399 res
= save_unicode(self
, args
, 1);
2406 if (type
== &PyTuple_Type
) {
2407 res
= save_tuple(self
, args
);
2410 if (type
== &PyType_Type
) {
2411 res
= save_global(self
, args
, NULL
);
2417 if (type
== &PyList_Type
) {
2418 res
= save_list(self
, args
);
2424 if (type
== &PyDict_Type
) {
2425 res
= save_dict(self
, args
);
2431 if (type
== &PyInstance_Type
) {
2432 res
= save_inst(self
, args
);
2438 if (type
== &PyClass_Type
) {
2439 res
= save_global(self
, args
, NULL
);
2445 if (type
== &PyFunction_Type
) {
2446 res
= save_global(self
, args
, NULL
);
2447 if (res
&& PyErr_ExceptionMatches(PickleError
)) {
2448 /* fall back to reduce */
2457 if (type
== &PyCFunction_Type
) {
2458 res
= save_global(self
, args
, NULL
);
2463 if (!pers_save
&& self
->inst_pers_func
) {
2464 if ((tmp
= save_pers(self
, args
, self
->inst_pers_func
)) != 0) {
2470 if (PyType_IsSubtype(type
, &PyType_Type
)) {
2471 res
= save_global(self
, args
, NULL
);
2475 /* Get a reduction callable, and call it. This may come from
2476 * copy_reg.dispatch_table, the object's __reduce_ex__ method,
2477 * or the object's __reduce__ method.
2479 __reduce__
= PyDict_GetItem(dispatch_table
, (PyObject
*)type
);
2480 if (__reduce__
!= NULL
) {
2481 Py_INCREF(__reduce__
);
2483 ARG_TUP(self
, args
);
2485 t
= PyObject_Call(__reduce__
, self
->arg
, NULL
);
2490 /* Check for a __reduce_ex__ method. */
2491 __reduce__
= PyObject_GetAttr(args
, __reduce_ex___str
);
2492 if (__reduce__
!= NULL
) {
2493 t
= PyInt_FromLong(self
->proto
);
2498 t
= PyObject_Call(__reduce__
,
2505 if (PyErr_ExceptionMatches(PyExc_AttributeError
))
2509 /* Check for a __reduce__ method. */
2510 __reduce__
= PyObject_GetAttr(args
, __reduce___str
);
2511 if (__reduce__
!= NULL
) {
2512 t
= PyObject_Call(__reduce__
,
2516 PyErr_SetObject(UnpickleableError
, args
);
2525 if (PyString_Check(t
)) {
2526 res
= save_global(self
, args
, t
);
2530 if (! PyTuple_Check(t
)) {
2531 cPickle_ErrFormat(PicklingError
, "Value returned by "
2532 "%s must be string or tuple",
2537 size
= PyTuple_Size(t
);
2538 if (size
< 2 || size
> 5) {
2539 cPickle_ErrFormat(PicklingError
, "tuple returned by "
2540 "%s must contain 2 through 5 elements",
2545 arg_tup
= PyTuple_GET_ITEM(t
, 1);
2546 if (!(PyTuple_Check(arg_tup
) || arg_tup
== Py_None
)) {
2547 cPickle_ErrFormat(PicklingError
, "Second element of "
2548 "tuple returned by %s must be a tuple",
2553 res
= save_reduce(self
, t
, args
);
2557 Py_XDECREF(py_ob_id
);
2558 Py_XDECREF(__reduce__
);
2566 dump(Picklerobject
*self
, PyObject
*args
)
2568 static char stop
= STOP
;
2570 if (self
->proto
>= 2) {
2574 assert(self
->proto
>= 0 && self
->proto
< 256);
2575 bytes
[1] = (char)self
->proto
;
2576 if (self
->write_func(self
, bytes
, 2) < 0)
2580 if (save(self
, args
, 0) < 0)
2583 if (self
->write_func(self
, &stop
, 1) < 0)
2586 if (self
->write_func(self
, NULL
, 0) < 0)
2593 Pickle_clear_memo(Picklerobject
*self
, PyObject
*args
)
2596 PyDict_Clear(self
->memo
);
2602 Pickle_getvalue(Picklerobject
*self
, PyObject
*args
)
2604 int l
, i
, rsize
, ssize
, clear
=1, lm
;
2607 char *s
, *p
, *have_get
;
2610 /* Can be called by Python code or C code */
2611 if (args
&& !PyArg_ParseTuple(args
, "|i:getvalue", &clear
))
2614 /* Check to make sure we are based on a list */
2615 if (! Pdata_Check(self
->file
)) {
2616 PyErr_SetString(PicklingError
,
2617 "Attempt to getvalue() a non-list-based pickler");
2621 /* flush write buffer */
2622 if (write_other(self
, NULL
, 0) < 0) return NULL
;
2624 data
=(Pdata
*)self
->file
;
2627 /* set up an array to hold get/put status */
2628 lm
= PyDict_Size(self
->memo
);
2629 if (lm
< 0) return NULL
;
2631 have_get
= malloc(lm
);
2632 if (have_get
== NULL
) return PyErr_NoMemory();
2633 memset(have_get
, 0, lm
);
2635 /* Scan for gets. */
2636 for (rsize
= 0, i
= l
; --i
>= 0; ) {
2639 if (PyString_Check(k
))
2640 rsize
+= PyString_GET_SIZE(k
);
2642 else if (PyInt_Check(k
)) { /* put */
2643 ik
= PyInt_AS_LONG((PyIntObject
*)k
);
2644 if (ik
>= lm
|| ik
== 0) {
2645 PyErr_SetString(PicklingError
,
2646 "Invalid get data");
2649 if (have_get
[ik
]) /* with matching get */
2650 rsize
+= ik
< 256 ? 2 : 5;
2653 else if (! (PyTuple_Check(k
) &&
2654 PyTuple_GET_SIZE(k
) == 2 &&
2655 PyInt_Check((k
= PyTuple_GET_ITEM(k
, 0))))
2657 PyErr_SetString(PicklingError
,
2658 "Unexpected data in internal list");
2663 ik
= PyInt_AS_LONG((PyIntObject
*)k
);
2664 if (ik
>= lm
|| ik
== 0) {
2665 PyErr_SetString(PicklingError
,
2666 "Invalid get data");
2670 rsize
+= ik
< 256 ? 2 : 5;
2674 /* Now generate the result */
2675 r
= PyString_FromStringAndSize(NULL
, rsize
);
2676 if (r
== NULL
) goto err
;
2677 s
= PyString_AS_STRING((PyStringObject
*)r
);
2679 for (i
= 0; i
< l
; i
++) {
2682 if (PyString_Check(k
)) {
2683 ssize
= PyString_GET_SIZE(k
);
2685 p
=PyString_AS_STRING((PyStringObject
*)k
);
2686 while (--ssize
>= 0)
2691 else if (PyTuple_Check(k
)) { /* get */
2692 ik
= PyInt_AS_LONG((PyIntObject
*)
2693 PyTuple_GET_ITEM(k
, 0));
2696 *s
++ = (int)(ik
& 0xff);
2700 *s
++ = (int)(ik
& 0xff);
2701 *s
++ = (int)((ik
>> 8) & 0xff);
2702 *s
++ = (int)((ik
>> 16) & 0xff);
2703 *s
++ = (int)((ik
>> 24) & 0xff);
2708 ik
= PyInt_AS_LONG((PyIntObject
*)k
);
2710 if (have_get
[ik
]) { /* with matching get */
2713 *s
++ = (int)(ik
& 0xff);
2717 *s
++ = (int)(ik
& 0xff);
2718 *s
++ = (int)((ik
>> 8) & 0xff);
2719 *s
++ = (int)((ik
>> 16) & 0xff);
2720 *s
++ = (int)((ik
>> 24) & 0xff);
2727 PyDict_Clear(self
->memo
);
2728 Pdata_clear(data
, 0);
2739 Pickler_dump(Picklerobject
*self
, PyObject
*args
)
2744 if (!( PyArg_ParseTuple(args
, "O|i:dump", &ob
, &get
)))
2747 if (dump(self
, ob
) < 0)
2750 if (get
) return Pickle_getvalue(self
, NULL
);
2752 /* XXX Why does dump() return self? */
2754 return (PyObject
*)self
;
2758 static struct PyMethodDef Pickler_methods
[] =
2760 {"dump", (PyCFunction
)Pickler_dump
, METH_VARARGS
,
2761 PyDoc_STR("dump(object) -- "
2762 "Write an object in pickle format to the object's pickle stream")},
2763 {"clear_memo", (PyCFunction
)Pickle_clear_memo
, METH_NOARGS
,
2764 PyDoc_STR("clear_memo() -- Clear the picklers memo")},
2765 {"getvalue", (PyCFunction
)Pickle_getvalue
, METH_VARARGS
,
2766 PyDoc_STR("getvalue() -- Finish picking a list-based pickle")},
2767 {NULL
, NULL
} /* sentinel */
2771 static Picklerobject
*
2772 newPicklerobject(PyObject
*file
, int proto
)
2774 Picklerobject
*self
;
2777 proto
= HIGHEST_PROTOCOL
;
2778 if (proto
> HIGHEST_PROTOCOL
) {
2779 PyErr_Format(PyExc_ValueError
, "pickle protocol %d asked for; "
2780 "the highest available protocol is %d",
2781 proto
, HIGHEST_PROTOCOL
);
2785 self
= PyObject_GC_New(Picklerobject
, &Picklertype
);
2788 self
->proto
= proto
;
2789 self
->bin
= proto
> 0;
2794 self
->pers_func
= NULL
;
2795 self
->inst_pers_func
= NULL
;
2796 self
->write_buf
= NULL
;
2799 self
->fast_container
= 0;
2800 self
->fast_memo
= NULL
;
2802 self
->dispatch_table
= NULL
;
2814 if (!( self
->memo
= PyDict_New()))
2817 if (PyFile_Check(file
)) {
2818 self
->fp
= PyFile_AsFile(file
);
2819 if (self
->fp
== NULL
) {
2820 PyErr_SetString(PyExc_ValueError
,
2821 "I/O operation on closed file");
2824 self
->write_func
= write_file
;
2826 else if (PycStringIO_OutputCheck(file
)) {
2827 self
->write_func
= write_cStringIO
;
2829 else if (file
== Py_None
) {
2830 self
->write_func
= write_none
;
2833 self
->write_func
= write_other
;
2835 if (! Pdata_Check(file
)) {
2836 self
->write
= PyObject_GetAttr(file
, write_str
);
2839 PyErr_SetString(PyExc_TypeError
,
2840 "argument must have 'write' "
2846 self
->write_buf
= (char *)PyMem_Malloc(WRITE_BUF_SIZE
);
2847 if (self
->write_buf
== NULL
) {
2853 if (PyEval_GetRestricted()) {
2854 /* Restricted execution, get private tables */
2855 PyObject
*m
= PyImport_Import(copy_reg_str
);
2859 self
->dispatch_table
= PyObject_GetAttr(m
, dispatch_table_str
);
2861 if (self
->dispatch_table
== NULL
)
2865 self
->dispatch_table
= dispatch_table
;
2866 Py_INCREF(dispatch_table
);
2868 PyObject_GC_Track(self
);
2879 get_Pickler(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
2881 static char *kwlist
[] = {"file", "protocol", NULL
};
2882 PyObject
*file
= NULL
;
2886 * The documented signature is Pickler(file, protocol=0), but this
2887 * accepts Pickler() and Pickler(integer) too. The meaning then
2888 * is clear as mud, undocumented, and not supported by pickle.py.
2889 * I'm told Zope uses this, but I haven't traced into this code
2890 * far enough to figure out what it means.
2892 if (!PyArg_ParseTuple(args
, "|i:Pickler", &proto
)) {
2895 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "O|i:Pickler",
2896 kwlist
, &file
, &proto
))
2899 return (PyObject
*)newPicklerobject(file
, proto
);
2904 Pickler_dealloc(Picklerobject
*self
)
2906 PyObject_GC_UnTrack(self
);
2907 Py_XDECREF(self
->write
);
2908 Py_XDECREF(self
->memo
);
2909 Py_XDECREF(self
->fast_memo
);
2910 Py_XDECREF(self
->arg
);
2911 Py_XDECREF(self
->file
);
2912 Py_XDECREF(self
->pers_func
);
2913 Py_XDECREF(self
->inst_pers_func
);
2914 Py_XDECREF(self
->dispatch_table
);
2915 PyMem_Free(self
->write_buf
);
2916 self
->ob_type
->tp_free((PyObject
*)self
);
2920 Pickler_traverse(Picklerobject
*self
, visitproc visit
, void *arg
)
2922 Py_VISIT(self
->write
);
2923 Py_VISIT(self
->memo
);
2924 Py_VISIT(self
->fast_memo
);
2925 Py_VISIT(self
->arg
);
2926 Py_VISIT(self
->file
);
2927 Py_VISIT(self
->pers_func
);
2928 Py_VISIT(self
->inst_pers_func
);
2929 Py_VISIT(self
->dispatch_table
);
2934 Pickler_clear(Picklerobject
*self
)
2936 Py_CLEAR(self
->write
);
2937 Py_CLEAR(self
->memo
);
2938 Py_CLEAR(self
->fast_memo
);
2939 Py_CLEAR(self
->arg
);
2940 Py_CLEAR(self
->file
);
2941 Py_CLEAR(self
->pers_func
);
2942 Py_CLEAR(self
->inst_pers_func
);
2943 Py_CLEAR(self
->dispatch_table
);
2948 Pickler_get_pers_func(Picklerobject
*p
)
2950 if (p
->pers_func
== NULL
)
2951 PyErr_SetString(PyExc_AttributeError
, "persistent_id");
2953 Py_INCREF(p
->pers_func
);
2954 return p
->pers_func
;
2958 Pickler_set_pers_func(Picklerobject
*p
, PyObject
*v
)
2961 PyErr_SetString(PyExc_TypeError
,
2962 "attribute deletion is not supported");
2965 Py_XDECREF(p
->pers_func
);
2972 Pickler_set_inst_pers_func(Picklerobject
*p
, PyObject
*v
)
2975 PyErr_SetString(PyExc_TypeError
,
2976 "attribute deletion is not supported");
2979 Py_XDECREF(p
->inst_pers_func
);
2981 p
->inst_pers_func
= v
;
2986 Pickler_get_memo(Picklerobject
*p
)
2988 if (p
->memo
== NULL
)
2989 PyErr_SetString(PyExc_AttributeError
, "memo");
2996 Pickler_set_memo(Picklerobject
*p
, PyObject
*v
)
2999 PyErr_SetString(PyExc_TypeError
,
3000 "attribute deletion is not supported");
3003 if (!PyDict_Check(v
)) {
3004 PyErr_SetString(PyExc_TypeError
, "memo must be a dictionary");
3007 Py_XDECREF(p
->memo
);
3014 Pickler_get_error(Picklerobject
*p
)
3016 /* why is this an attribute on the Pickler? */
3017 Py_INCREF(PicklingError
);
3018 return PicklingError
;
3021 static PyMemberDef Pickler_members
[] = {
3022 {"binary", T_INT
, offsetof(Picklerobject
, bin
)},
3023 {"fast", T_INT
, offsetof(Picklerobject
, fast
)},
3027 static PyGetSetDef Pickler_getsets
[] = {
3028 {"persistent_id", (getter
)Pickler_get_pers_func
,
3029 (setter
)Pickler_set_pers_func
},
3030 {"inst_persistent_id", NULL
, (setter
)Pickler_set_inst_pers_func
},
3031 {"memo", (getter
)Pickler_get_memo
, (setter
)Pickler_set_memo
},
3032 {"PicklingError", (getter
)Pickler_get_error
, NULL
},
3036 PyDoc_STRVAR(Picklertype__doc__
,
3037 "Objects that know how to pickle objects\n");
3039 static PyTypeObject Picklertype
= {
3040 PyObject_HEAD_INIT(NULL
)
3042 "cPickle.Pickler", /*tp_name*/
3043 sizeof(Picklerobject
), /*tp_basicsize*/
3045 (destructor
)Pickler_dealloc
, /* tp_dealloc */
3051 0, /* tp_as_number */
3052 0, /* tp_as_sequence */
3053 0, /* tp_as_mapping */
3057 PyObject_GenericGetAttr
, /* tp_getattro */
3058 PyObject_GenericSetAttr
, /* tp_setattro */
3059 0, /* tp_as_buffer */
3060 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
| Py_TPFLAGS_HAVE_GC
,
3061 Picklertype__doc__
, /* tp_doc */
3062 (traverseproc
)Pickler_traverse
, /* tp_traverse */
3063 (inquiry
)Pickler_clear
, /* tp_clear */
3064 0, /* tp_richcompare */
3065 0, /* tp_weaklistoffset */
3067 0, /* tp_iternext */
3068 Pickler_methods
, /* tp_methods */
3069 Pickler_members
, /* tp_members */
3070 Pickler_getsets
, /* tp_getset */
3074 find_class(PyObject
*py_module_name
, PyObject
*py_global_name
, PyObject
*fc
)
3076 PyObject
*global
= 0, *module
;
3080 PyErr_SetString(UnpicklingError
, "Global and instance "
3081 "pickles are not supported.");
3084 return PyObject_CallFunctionObjArgs(fc
, py_module_name
,
3085 py_global_name
, NULL
);
3088 module
= PySys_GetObject("modules");
3092 module
= PyDict_GetItem(module
, py_module_name
);
3093 if (module
== NULL
) {
3094 module
= PyImport_Import(py_module_name
);
3097 global
= PyObject_GetAttr(module
, py_global_name
);
3101 global
= PyObject_GetAttr(module
, py_global_name
);
3106 marker(Unpicklerobject
*self
)
3108 if (self
->num_marks
< 1) {
3109 PyErr_SetString(UnpicklingError
, "could not find MARK");
3113 return self
->marks
[--self
->num_marks
];
3118 load_none(Unpicklerobject
*self
)
3120 PDATA_APPEND(self
->stack
, Py_None
, -1);
3127 PyErr_SetString(UnpicklingError
, "pickle data was truncated");
3132 load_int(Unpicklerobject
*self
)
3134 PyObject
*py_int
= 0;
3139 if ((len
= self
->readline_func(self
, &s
)) < 0) return -1;
3140 if (len
< 2) return bad_readline();
3141 if (!( s
=pystrndup(s
,len
))) return -1;
3144 l
= strtol(s
, &endptr
, 0);
3146 if (errno
|| (*endptr
!= '\n') || (endptr
[1] != '\0')) {
3147 /* Hm, maybe we've got something long. Let's try reading
3148 it as a Python long object. */
3150 py_int
= PyLong_FromString(s
, NULL
, 0);
3151 if (py_int
== NULL
) {
3152 PyErr_SetString(PyExc_ValueError
,
3153 "could not convert string to int");
3158 if (len
== 3 && (l
== 0 || l
== 1)) {
3159 if (!( py_int
= PyBool_FromLong(l
))) goto finally
;
3162 if (!( py_int
= PyInt_FromLong(l
))) goto finally
;
3167 PDATA_PUSH(self
->stack
, py_int
, -1);
3177 load_bool(Unpicklerobject
*self
, PyObject
*boolean
)
3179 assert(boolean
== Py_True
|| boolean
== Py_False
);
3180 PDATA_APPEND(self
->stack
, boolean
, -1);
3184 /* s contains x bytes of a little-endian integer. Return its value as a
3185 * C int. Obscure: when x is 1 or 2, this is an unsigned little-endian
3186 * int, but when x is 4 it's a signed one. This is an historical source
3187 * of x-platform bugs.
3190 calc_binint(char *s
, int x
)
3196 for (i
= 0, l
= 0L; i
< x
; i
++) {
3197 c
= (unsigned char)s
[i
];
3198 l
|= (long)c
<< (i
* 8);
3201 /* Unlike BININT1 and BININT2, BININT (more accurately BININT4)
3202 * is signed, so on a box with longs bigger than 4 bytes we need
3203 * to extend a BININT's sign bit to the full width.
3205 if (x
== 4 && l
& (1L << 31))
3213 load_binintx(Unpicklerobject
*self
, char *s
, int x
)
3215 PyObject
*py_int
= 0;
3218 l
= calc_binint(s
, x
);
3220 if (!( py_int
= PyInt_FromLong(l
)))
3223 PDATA_PUSH(self
->stack
, py_int
, -1);
3229 load_binint(Unpicklerobject
*self
)
3233 if (self
->read_func(self
, &s
, 4) < 0)
3236 return load_binintx(self
, s
, 4);
3241 load_binint1(Unpicklerobject
*self
)
3245 if (self
->read_func(self
, &s
, 1) < 0)
3248 return load_binintx(self
, s
, 1);
3253 load_binint2(Unpicklerobject
*self
)
3257 if (self
->read_func(self
, &s
, 2) < 0)
3260 return load_binintx(self
, s
, 2);
3264 load_long(Unpicklerobject
*self
)
3270 if ((len
= self
->readline_func(self
, &s
)) < 0) return -1;
3271 if (len
< 2) return bad_readline();
3272 if (!( s
=pystrndup(s
,len
))) return -1;
3274 if (!( l
= PyLong_FromString(s
, &end
, 0)))
3278 PDATA_PUSH(self
->stack
, l
, -1);
3287 /* 'size' bytes contain the # of bytes of little-endian 256's-complement
3291 load_counted_long(Unpicklerobject
*self
, int size
)
3295 unsigned char *pdata
;
3298 assert(size
== 1 || size
== 4);
3299 i
= self
->read_func(self
, &nbytes
, size
);
3300 if (i
< 0) return -1;
3302 size
= calc_binint(nbytes
, size
);
3304 /* Corrupt or hostile pickle -- we never write one like
3307 PyErr_SetString(UnpicklingError
, "LONG pickle has negative "
3313 along
= PyLong_FromLong(0L);
3315 /* Read the raw little-endian bytes & convert. */
3316 i
= self
->read_func(self
, (char **)&pdata
, size
);
3317 if (i
< 0) return -1;
3318 along
= _PyLong_FromByteArray(pdata
, (size_t)size
,
3319 1 /* little endian */, 1 /* signed */);
3323 PDATA_PUSH(self
->stack
, along
, -1);
3328 load_float(Unpicklerobject
*self
)
3330 PyObject
*py_float
= 0;
3335 if ((len
= self
->readline_func(self
, &s
)) < 0) return -1;
3336 if (len
< 2) return bad_readline();
3337 if (!( s
=pystrndup(s
,len
))) return -1;
3340 d
= PyOS_ascii_strtod(s
, &endptr
);
3342 if (errno
|| (endptr
[0] != '\n') || (endptr
[1] != '\0')) {
3343 PyErr_SetString(PyExc_ValueError
,
3344 "could not convert string to float");
3348 if (!( py_float
= PyFloat_FromDouble(d
)))
3352 PDATA_PUSH(self
->stack
, py_float
, -1);
3362 load_binfloat(Unpicklerobject
*self
)
3368 if (self
->read_func(self
, &p
, 8) < 0)
3371 x
= _PyFloat_Unpack8((unsigned char *)p
, 0);
3372 if (x
== -1.0 && PyErr_Occurred())
3375 py_float
= PyFloat_FromDouble(x
);
3376 if (py_float
== NULL
)
3379 PDATA_PUSH(self
->stack
, py_float
, -1);
3384 load_string(Unpicklerobject
*self
)
3390 if ((len
= self
->readline_func(self
, &s
)) < 0) return -1;
3391 if (len
< 2) return bad_readline();
3392 if (!( s
=pystrndup(s
,len
))) return -1;
3395 /* Strip outermost quotes */
3396 while (s
[len
-1] <= ' ')
3398 if(s
[0]=='"' && s
[len
-1]=='"'){
3402 } else if(s
[0]=='\'' && s
[len
-1]=='\''){
3408 /********************************************/
3410 str
= PyString_DecodeEscape(p
, len
, NULL
, 0, NULL
);
3413 PDATA_PUSH(self
->stack
, str
, -1);
3420 PyErr_SetString(PyExc_ValueError
,"insecure string pickle");
3426 load_binstring(Unpicklerobject
*self
)
3428 PyObject
*py_string
= 0;
3432 if (self
->read_func(self
, &s
, 4) < 0) return -1;
3434 l
= calc_binint(s
, 4);
3436 if (self
->read_func(self
, &s
, l
) < 0)
3439 if (!( py_string
= PyString_FromStringAndSize(s
, l
)))
3442 PDATA_PUSH(self
->stack
, py_string
, -1);
3448 load_short_binstring(Unpicklerobject
*self
)
3450 PyObject
*py_string
= 0;
3454 if (self
->read_func(self
, &s
, 1) < 0)
3457 l
= (unsigned char)s
[0];
3459 if (self
->read_func(self
, &s
, l
) < 0) return -1;
3461 if (!( py_string
= PyString_FromStringAndSize(s
, l
))) return -1;
3463 PDATA_PUSH(self
->stack
, py_string
, -1);
3468 #ifdef Py_USING_UNICODE
3470 load_unicode(Unpicklerobject
*self
)
3476 if ((len
= self
->readline_func(self
, &s
)) < 0) return -1;
3477 if (len
< 1) return bad_readline();
3479 if (!( str
= PyUnicode_DecodeRawUnicodeEscape(s
, len
- 1, NULL
)))
3482 PDATA_PUSH(self
->stack
, str
, -1);
3491 #ifdef Py_USING_UNICODE
3493 load_binunicode(Unpicklerobject
*self
)
3499 if (self
->read_func(self
, &s
, 4) < 0) return -1;
3501 l
= calc_binint(s
, 4);
3503 if (self
->read_func(self
, &s
, l
) < 0)
3506 if (!( unicode
= PyUnicode_DecodeUTF8(s
, l
, NULL
)))
3509 PDATA_PUSH(self
->stack
, unicode
, -1);
3516 load_tuple(Unpicklerobject
*self
)
3521 if ((i
= marker(self
)) < 0) return -1;
3522 if (!( tup
=Pdata_popTuple(self
->stack
, i
))) return -1;
3523 PDATA_PUSH(self
->stack
, tup
, -1);
3528 load_counted_tuple(Unpicklerobject
*self
, int len
)
3530 PyObject
*tup
= PyTuple_New(len
);
3535 while (--len
>= 0) {
3538 PDATA_POP(self
->stack
, element
);
3539 if (element
== NULL
)
3541 PyTuple_SET_ITEM(tup
, len
, element
);
3543 PDATA_PUSH(self
->stack
, tup
, -1);
3548 load_empty_list(Unpicklerobject
*self
)
3552 if (!( list
=PyList_New(0))) return -1;
3553 PDATA_PUSH(self
->stack
, list
, -1);
3558 load_empty_dict(Unpicklerobject
*self
)
3562 if (!( dict
=PyDict_New())) return -1;
3563 PDATA_PUSH(self
->stack
, dict
, -1);
3569 load_list(Unpicklerobject
*self
)
3574 if ((i
= marker(self
)) < 0) return -1;
3575 if (!( list
=Pdata_popList(self
->stack
, i
))) return -1;
3576 PDATA_PUSH(self
->stack
, list
, -1);
3581 load_dict(Unpicklerobject
*self
)
3583 PyObject
*dict
, *key
, *value
;
3586 if ((i
= marker(self
)) < 0) return -1;
3587 j
=self
->stack
->length
;
3589 if (!( dict
= PyDict_New())) return -1;
3591 for (k
= i
+1; k
< j
; k
+= 2) {
3592 key
=self
->stack
->data
[k
-1];
3593 value
=self
->stack
->data
[k
];
3594 if (PyDict_SetItem(dict
, key
, value
) < 0) {
3599 Pdata_clear(self
->stack
, i
);
3600 PDATA_PUSH(self
->stack
, dict
, -1);
3605 Instance_New(PyObject
*cls
, PyObject
*args
)
3609 if (PyClass_Check(cls
)) {
3612 if ((l
=PyObject_Size(args
)) < 0) goto err
;
3614 PyObject
*__getinitargs__
;
3616 __getinitargs__
= PyObject_GetAttr(cls
,
3617 __getinitargs___str
);
3618 if (!__getinitargs__
) {
3619 /* We have a class with no __getinitargs__,
3620 so bypass usual construction */
3624 if (!( inst
=PyInstance_NewRaw(cls
, NULL
)))
3628 Py_DECREF(__getinitargs__
);
3631 if ((r
=PyInstance_New(cls
, args
, NULL
))) return r
;
3635 if ((r
=PyObject_CallObject(cls
, args
))) return r
;
3639 PyObject
*tp
, *v
, *tb
, *tmp_value
;
3641 PyErr_Fetch(&tp
, &v
, &tb
);
3643 /* NULL occurs when there was a KeyboardInterrupt */
3644 if (tmp_value
== NULL
)
3645 tmp_value
= Py_None
;
3646 if ((r
= PyTuple_Pack(3, tmp_value
, cls
, args
))) {
3650 PyErr_Restore(tp
,v
,tb
);
3657 load_obj(Unpicklerobject
*self
)
3659 PyObject
*class, *tup
, *obj
=0;
3662 if ((i
= marker(self
)) < 0) return -1;
3663 if (!( tup
=Pdata_popTuple(self
->stack
, i
+1))) return -1;
3664 PDATA_POP(self
->stack
, class);
3666 obj
= Instance_New(class, tup
);
3671 if (! obj
) return -1;
3672 PDATA_PUSH(self
->stack
, obj
, -1);
3678 load_inst(Unpicklerobject
*self
)
3680 PyObject
*tup
, *class=0, *obj
=0, *module_name
, *class_name
;
3684 if ((i
= marker(self
)) < 0) return -1;
3686 if ((len
= self
->readline_func(self
, &s
)) < 0) return -1;
3687 if (len
< 2) return bad_readline();
3688 module_name
= PyString_FromStringAndSize(s
, len
- 1);
3689 if (!module_name
) return -1;
3691 if ((len
= self
->readline_func(self
, &s
)) >= 0) {
3692 if (len
< 2) return bad_readline();
3693 if ((class_name
= PyString_FromStringAndSize(s
, len
- 1))) {
3694 class = find_class(module_name
, class_name
,
3696 Py_DECREF(class_name
);
3699 Py_DECREF(module_name
);
3701 if (! class) return -1;
3703 if ((tup
=Pdata_popTuple(self
->stack
, i
))) {
3704 obj
= Instance_New(class, tup
);
3709 if (! obj
) return -1;
3711 PDATA_PUSH(self
->stack
, obj
, -1);
3716 load_newobj(Unpicklerobject
*self
)
3718 PyObject
*args
= NULL
;
3719 PyObject
*clsraw
= NULL
;
3720 PyTypeObject
*cls
; /* clsraw cast to its true type */
3723 /* Stack is ... cls argtuple, and we want to call
3724 * cls.__new__(cls, *argtuple).
3726 PDATA_POP(self
->stack
, args
);
3727 if (args
== NULL
) goto Fail
;
3728 if (! PyTuple_Check(args
)) {
3729 PyErr_SetString(UnpicklingError
, "NEWOBJ expected an arg "
3734 PDATA_POP(self
->stack
, clsraw
);
3735 cls
= (PyTypeObject
*)clsraw
;
3736 if (cls
== NULL
) goto Fail
;
3737 if (! PyType_Check(cls
)) {
3738 PyErr_SetString(UnpicklingError
, "NEWOBJ class argument "
3739 "isn't a type object");
3742 if (cls
->tp_new
== NULL
) {
3743 PyErr_SetString(UnpicklingError
, "NEWOBJ class argument "
3749 obj
= cls
->tp_new(cls
, args
, NULL
);
3750 if (obj
== NULL
) goto Fail
;
3754 PDATA_PUSH(self
->stack
, obj
, -1);
3764 load_global(Unpicklerobject
*self
)
3766 PyObject
*class = 0, *module_name
= 0, *class_name
= 0;
3770 if ((len
= self
->readline_func(self
, &s
)) < 0) return -1;
3771 if (len
< 2) return bad_readline();
3772 module_name
= PyString_FromStringAndSize(s
, len
- 1);
3773 if (!module_name
) return -1;
3775 if ((len
= self
->readline_func(self
, &s
)) >= 0) {
3777 Py_DECREF(module_name
);
3778 return bad_readline();
3780 if ((class_name
= PyString_FromStringAndSize(s
, len
- 1))) {
3781 class = find_class(module_name
, class_name
,
3783 Py_DECREF(class_name
);
3786 Py_DECREF(module_name
);
3788 if (! class) return -1;
3789 PDATA_PUSH(self
->stack
, class, -1);
3795 load_persid(Unpicklerobject
*self
)
3801 if (self
->pers_func
) {
3802 if ((len
= self
->readline_func(self
, &s
)) < 0) return -1;
3803 if (len
< 2) return bad_readline();
3805 pid
= PyString_FromStringAndSize(s
, len
- 1);
3806 if (!pid
) return -1;
3808 if (PyList_Check(self
->pers_func
)) {
3809 if (PyList_Append(self
->pers_func
, pid
) < 0) {
3817 pid
= PyObject_Call(self
->pers_func
, self
->arg
,
3823 if (! pid
) return -1;
3825 PDATA_PUSH(self
->stack
, pid
, -1);
3829 PyErr_SetString(UnpicklingError
,
3830 "A load persistent id instruction was encountered,\n"
3831 "but no persistent_load function was specified.");
3837 load_binpersid(Unpicklerobject
*self
)
3841 if (self
->pers_func
) {
3842 PDATA_POP(self
->stack
, pid
);
3843 if (! pid
) return -1;
3845 if (PyList_Check(self
->pers_func
)) {
3846 if (PyList_Append(self
->pers_func
, pid
) < 0) {
3854 pid
= PyObject_Call(self
->pers_func
, self
->arg
,
3858 if (! pid
) return -1;
3861 PDATA_PUSH(self
->stack
, pid
, -1);
3865 PyErr_SetString(UnpicklingError
,
3866 "A load persistent id instruction was encountered,\n"
3867 "but no persistent_load function was specified.");
3874 load_pop(Unpicklerobject
*self
)
3878 if (!( (len
=self
->stack
->length
) > 0 )) return stackUnderflow();
3880 /* Note that we split the (pickle.py) stack into two stacks,
3881 an object stack and a mark stack. We have to be clever and
3882 pop the right one. We do this by looking at the top of the
3886 if ((self
->num_marks
> 0) &&
3887 (self
->marks
[self
->num_marks
- 1] == len
))
3891 Py_DECREF(self
->stack
->data
[len
]);
3892 self
->stack
->length
=len
;
3900 load_pop_mark(Unpicklerobject
*self
)
3904 if ((i
= marker(self
)) < 0)
3907 Pdata_clear(self
->stack
, i
);
3914 load_dup(Unpicklerobject
*self
)
3919 if ((len
= self
->stack
->length
) <= 0) return stackUnderflow();
3920 last
=self
->stack
->data
[len
-1];
3922 PDATA_PUSH(self
->stack
, last
, -1);
3928 load_get(Unpicklerobject
*self
)
3930 PyObject
*py_str
= 0, *value
= 0;
3935 if ((len
= self
->readline_func(self
, &s
)) < 0) return -1;
3936 if (len
< 2) return bad_readline();
3938 if (!( py_str
= PyString_FromStringAndSize(s
, len
- 1))) return -1;
3940 value
= PyDict_GetItem(self
->memo
, py_str
);
3942 PyErr_SetObject(BadPickleGet
, py_str
);
3946 PDATA_APPEND(self
->stack
, value
, -1);
3956 load_binget(Unpicklerobject
*self
)
3958 PyObject
*py_key
= 0, *value
= 0;
3963 if (self
->read_func(self
, &s
, 1) < 0) return -1;
3965 key
= (unsigned char)s
[0];
3966 if (!( py_key
= PyInt_FromLong((long)key
))) return -1;
3968 value
= PyDict_GetItem(self
->memo
, py_key
);
3970 PyErr_SetObject(BadPickleGet
, py_key
);
3974 PDATA_APPEND(self
->stack
, value
, -1);
3984 load_long_binget(Unpicklerobject
*self
)
3986 PyObject
*py_key
= 0, *value
= 0;
3992 if (self
->read_func(self
, &s
, 4) < 0) return -1;
3994 c
= (unsigned char)s
[0];
3996 c
= (unsigned char)s
[1];
3997 key
|= (long)c
<< 8;
3998 c
= (unsigned char)s
[2];
3999 key
|= (long)c
<< 16;
4000 c
= (unsigned char)s
[3];
4001 key
|= (long)c
<< 24;
4003 if (!( py_key
= PyInt_FromLong((long)key
))) return -1;
4005 value
= PyDict_GetItem(self
->memo
, py_key
);
4007 PyErr_SetObject(BadPickleGet
, py_key
);
4011 PDATA_APPEND(self
->stack
, value
, -1);
4019 /* Push an object from the extension registry (EXT[124]). nbytes is
4020 * the number of bytes following the opcode, holding the index (code) value.
4023 load_extension(Unpicklerobject
*self
, int nbytes
)
4025 char *codebytes
; /* the nbytes bytes after the opcode */
4026 long code
; /* calc_binint returns long */
4027 PyObject
*py_code
; /* code as a Python int */
4028 PyObject
*obj
; /* the object to push */
4029 PyObject
*pair
; /* (module_name, class_name) */
4030 PyObject
*module_name
, *class_name
;
4032 assert(nbytes
== 1 || nbytes
== 2 || nbytes
== 4);
4033 if (self
->read_func(self
, &codebytes
, nbytes
) < 0) return -1;
4034 code
= calc_binint(codebytes
, nbytes
);
4035 if (code
<= 0) { /* note that 0 is forbidden */
4036 /* Corrupt or hostile pickle. */
4037 PyErr_SetString(UnpicklingError
, "EXT specifies code <= 0");
4041 /* Look for the code in the cache. */
4042 py_code
= PyInt_FromLong(code
);
4043 if (py_code
== NULL
) return -1;
4044 obj
= PyDict_GetItem(extension_cache
, py_code
);
4048 PDATA_APPEND(self
->stack
, obj
, -1);
4052 /* Look up the (module_name, class_name) pair. */
4053 pair
= PyDict_GetItem(inverted_registry
, py_code
);
4056 PyErr_Format(PyExc_ValueError
, "unregistered extension "
4060 /* Since the extension registry is manipulable via Python code,
4061 * confirm that pair is really a 2-tuple of strings.
4063 if (!PyTuple_Check(pair
) || PyTuple_Size(pair
) != 2 ||
4064 !PyString_Check(module_name
= PyTuple_GET_ITEM(pair
, 0)) ||
4065 !PyString_Check(class_name
= PyTuple_GET_ITEM(pair
, 1))) {
4067 PyErr_Format(PyExc_ValueError
, "_inverted_registry[%ld] "
4068 "isn't a 2-tuple of strings", code
);
4071 /* Load the object. */
4072 obj
= find_class(module_name
, class_name
, self
->find_class
);
4077 /* Cache code -> obj. */
4078 code
= PyDict_SetItem(extension_cache
, py_code
, obj
);
4084 PDATA_PUSH(self
->stack
, obj
, -1);
4089 load_put(Unpicklerobject
*self
)
4091 PyObject
*py_str
= 0, *value
= 0;
4095 if ((l
= self
->readline_func(self
, &s
)) < 0) return -1;
4096 if (l
< 2) return bad_readline();
4097 if (!( len
=self
->stack
->length
)) return stackUnderflow();
4098 if (!( py_str
= PyString_FromStringAndSize(s
, l
- 1))) return -1;
4099 value
=self
->stack
->data
[len
-1];
4100 l
=PyDict_SetItem(self
->memo
, py_str
, value
);
4107 load_binput(Unpicklerobject
*self
)
4109 PyObject
*py_key
= 0, *value
= 0;
4114 if (self
->read_func(self
, &s
, 1) < 0) return -1;
4115 if (!( (len
=self
->stack
->length
) > 0 )) return stackUnderflow();
4117 key
= (unsigned char)s
[0];
4119 if (!( py_key
= PyInt_FromLong((long)key
))) return -1;
4120 value
=self
->stack
->data
[len
-1];
4121 len
=PyDict_SetItem(self
->memo
, py_key
, value
);
4128 load_long_binput(Unpicklerobject
*self
)
4130 PyObject
*py_key
= 0, *value
= 0;
4136 if (self
->read_func(self
, &s
, 4) < 0) return -1;
4137 if (!( len
=self
->stack
->length
)) return stackUnderflow();
4139 c
= (unsigned char)s
[0];
4141 c
= (unsigned char)s
[1];
4142 key
|= (long)c
<< 8;
4143 c
= (unsigned char)s
[2];
4144 key
|= (long)c
<< 16;
4145 c
= (unsigned char)s
[3];
4146 key
|= (long)c
<< 24;
4148 if (!( py_key
= PyInt_FromLong(key
))) return -1;
4149 value
=self
->stack
->data
[len
-1];
4150 len
=PyDict_SetItem(self
->memo
, py_key
, value
);
4157 do_append(Unpicklerobject
*self
, int x
)
4159 PyObject
*value
= 0, *list
= 0, *append_method
= 0;
4162 len
=self
->stack
->length
;
4163 if (!( len
>= x
&& x
> 0 )) return stackUnderflow();
4165 if (len
==x
) return 0;
4167 list
=self
->stack
->data
[x
-1];
4169 if (PyList_Check(list
)) {
4173 slice
=Pdata_popList(self
->stack
, x
);
4174 if (! slice
) return -1;
4175 list_len
= PyList_GET_SIZE(list
);
4176 i
=PyList_SetSlice(list
, list_len
, list_len
, slice
);
4182 if (!( append_method
= PyObject_GetAttr(list
, append_str
)))
4185 for (i
= x
; i
< len
; i
++) {
4188 value
=self
->stack
->data
[i
];
4190 ARG_TUP(self
, value
);
4192 junk
= PyObject_Call(append_method
, self
->arg
,
4197 Pdata_clear(self
->stack
, i
+1);
4198 self
->stack
->length
=x
;
4199 Py_DECREF(append_method
);
4204 self
->stack
->length
=x
;
4205 Py_DECREF(append_method
);
4213 load_append(Unpicklerobject
*self
)
4215 return do_append(self
, self
->stack
->length
- 1);
4220 load_appends(Unpicklerobject
*self
)
4222 return do_append(self
, marker(self
));
4227 do_setitems(Unpicklerobject
*self
, int x
)
4229 PyObject
*value
= 0, *key
= 0, *dict
= 0;
4232 if (!( (len
=self
->stack
->length
) >= x
4233 && x
> 0 )) return stackUnderflow();
4235 dict
=self
->stack
->data
[x
-1];
4237 for (i
= x
+1; i
< len
; i
+= 2) {
4238 key
=self
->stack
->data
[i
-1];
4239 value
=self
->stack
->data
[i
];
4240 if (PyObject_SetItem(dict
, key
, value
) < 0) {
4246 Pdata_clear(self
->stack
, x
);
4253 load_setitem(Unpicklerobject
*self
)
4255 return do_setitems(self
, self
->stack
->length
- 2);
4259 load_setitems(Unpicklerobject
*self
)
4261 return do_setitems(self
, marker(self
));
4266 load_build(Unpicklerobject
*self
)
4268 PyObject
*state
, *inst
, *slotstate
;
4269 PyObject
*__setstate__
;
4270 PyObject
*d_key
, *d_value
;
4274 /* Stack is ... instance, state. We want to leave instance at
4275 * the stack top, possibly mutated via instance.__setstate__(state).
4277 if (self
->stack
->length
< 2)
4278 return stackUnderflow();
4279 PDATA_POP(self
->stack
, state
);
4282 inst
= self
->stack
->data
[self
->stack
->length
- 1];
4284 __setstate__
= PyObject_GetAttr(inst
, __setstate___str
);
4285 if (__setstate__
!= NULL
) {
4286 PyObject
*junk
= NULL
;
4288 /* The explicit __setstate__ is responsible for everything. */
4289 ARG_TUP(self
, state
);
4291 junk
= PyObject_Call(__setstate__
, self
->arg
, NULL
);
4294 Py_DECREF(__setstate__
);
4300 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
4304 /* A default __setstate__. First see whether state embeds a
4305 * slot state dict too (a proto 2 addition).
4307 if (PyTuple_Check(state
) && PyTuple_Size(state
) == 2) {
4308 PyObject
*temp
= state
;
4309 state
= PyTuple_GET_ITEM(temp
, 0);
4310 slotstate
= PyTuple_GET_ITEM(temp
, 1);
4312 Py_INCREF(slotstate
);
4318 /* Set inst.__dict__ from the state dict (if any). */
4319 if (state
!= Py_None
) {
4321 if (! PyDict_Check(state
)) {
4322 PyErr_SetString(UnpicklingError
, "state is not a "
4326 dict
= PyObject_GetAttr(inst
, __dict___str
);
4331 while (PyDict_Next(state
, &i
, &d_key
, &d_value
)) {
4332 if (PyObject_SetItem(dict
, d_key
, d_value
) < 0)
4338 /* Also set instance attributes from the slotstate dict (if any). */
4339 if (slotstate
!= NULL
) {
4340 if (! PyDict_Check(slotstate
)) {
4341 PyErr_SetString(UnpicklingError
, "slot state is not "
4346 while (PyDict_Next(slotstate
, &i
, &d_key
, &d_value
)) {
4347 if (PyObject_SetAttr(inst
, d_key
, d_value
) < 0)
4355 Py_XDECREF(slotstate
);
4361 load_mark(Unpicklerobject
*self
)
4365 /* Note that we split the (pickle.py) stack into two stacks, an
4366 object stack and a mark stack. Here we push a mark onto the
4370 if ((self
->num_marks
+ 1) >= self
->marks_size
) {
4372 s
=self
->marks_size
+20;
4373 if (s
<= self
->num_marks
) s
=self
->num_marks
+ 1;
4374 if (self
->marks
== NULL
)
4375 marks
=(int *)malloc(s
* sizeof(int));
4377 marks
=(int *)realloc(self
->marks
,
4383 self
->marks
= marks
;
4384 self
->marks_size
= s
;
4387 self
->marks
[self
->num_marks
++] = self
->stack
->length
;
4393 load_reduce(Unpicklerobject
*self
)
4395 PyObject
*callable
= 0, *arg_tup
= 0, *ob
= 0;
4397 PDATA_POP(self
->stack
, arg_tup
);
4398 if (! arg_tup
) return -1;
4399 PDATA_POP(self
->stack
, callable
);
4401 ob
= Instance_New(callable
, arg_tup
);
4402 Py_DECREF(callable
);
4406 if (! ob
) return -1;
4408 PDATA_PUSH(self
->stack
, ob
, -1);
4412 /* Just raises an error if we don't know the protocol specified. PROTO
4413 * is the first opcode for protocols >= 2.
4416 load_proto(Unpicklerobject
*self
)
4421 i
= self
->read_func(self
, &protobyte
, 1);
4425 i
= calc_binint(protobyte
, 1);
4426 /* No point checking for < 0, since calc_binint returns an unsigned
4427 * int when chewing on 1 byte.
4430 if (i
<= HIGHEST_PROTOCOL
)
4433 PyErr_Format(PyExc_ValueError
, "unsupported pickle protocol: %d", i
);
4438 load(Unpicklerobject
*self
)
4440 PyObject
*err
= 0, *val
= 0;
4443 self
->num_marks
= 0;
4444 if (self
->stack
->length
) Pdata_clear(self
->stack
, 0);
4447 if (self
->read_func(self
, &s
, 1) < 0)
4452 if (load_none(self
) < 0)
4457 if (load_binint(self
) < 0)
4462 if (load_binint1(self
) < 0)
4467 if (load_binint2(self
) < 0)
4472 if (load_int(self
) < 0)
4477 if (load_long(self
) < 0)
4482 if (load_counted_long(self
, 1) < 0)
4487 if (load_counted_long(self
, 4) < 0)
4492 if (load_float(self
) < 0)
4497 if (load_binfloat(self
) < 0)
4502 if (load_binstring(self
) < 0)
4506 case SHORT_BINSTRING
:
4507 if (load_short_binstring(self
) < 0)
4512 if (load_string(self
) < 0)
4516 #ifdef Py_USING_UNICODE
4518 if (load_unicode(self
) < 0)
4523 if (load_binunicode(self
) < 0)
4529 if (load_counted_tuple(self
, 0) < 0)
4534 if (load_counted_tuple(self
, 1) < 0)
4539 if (load_counted_tuple(self
, 2) < 0)
4544 if (load_counted_tuple(self
, 3) < 0)
4549 if (load_tuple(self
) < 0)
4554 if (load_empty_list(self
) < 0)
4559 if (load_list(self
) < 0)
4564 if (load_empty_dict(self
) < 0)
4569 if (load_dict(self
) < 0)
4574 if (load_obj(self
) < 0)
4579 if (load_inst(self
) < 0)
4584 if (load_newobj(self
) < 0)
4589 if (load_global(self
) < 0)
4594 if (load_append(self
) < 0)
4599 if (load_appends(self
) < 0)
4604 if (load_build(self
) < 0)
4609 if (load_dup(self
) < 0)
4614 if (load_binget(self
) < 0)
4619 if (load_long_binget(self
) < 0)
4624 if (load_get(self
) < 0)
4629 if (load_extension(self
, 1) < 0)
4634 if (load_extension(self
, 2) < 0)
4639 if (load_extension(self
, 4) < 0)
4643 if (load_mark(self
) < 0)
4648 if (load_binput(self
) < 0)
4653 if (load_long_binput(self
) < 0)
4658 if (load_put(self
) < 0)
4663 if (load_pop(self
) < 0)
4668 if (load_pop_mark(self
) < 0)
4673 if (load_setitem(self
) < 0)
4678 if (load_setitems(self
) < 0)
4686 if (load_persid(self
) < 0)
4691 if (load_binpersid(self
) < 0)
4696 if (load_reduce(self
) < 0)
4701 if (load_proto(self
) < 0)
4706 if (load_bool(self
, Py_True
) < 0)
4711 if (load_bool(self
, Py_False
) < 0)
4717 PyErr_SetNone(PyExc_EOFError
);
4721 cPickle_ErrFormat(UnpicklingError
,
4722 "invalid load key, '%s'.",
4730 if ((err
= PyErr_Occurred())) {
4731 if (err
== PyExc_EOFError
) {
4732 PyErr_SetNone(PyExc_EOFError
);
4737 PDATA_POP(self
->stack
, val
);
4742 /* No-load functions to support noload, which is used to
4743 find persistent references. */
4746 noload_obj(Unpicklerobject
*self
)
4750 if ((i
= marker(self
)) < 0) return -1;
4751 return Pdata_clear(self
->stack
, i
+1);
4756 noload_inst(Unpicklerobject
*self
)
4761 if ((i
= marker(self
)) < 0) return -1;
4762 Pdata_clear(self
->stack
, i
);
4763 if (self
->readline_func(self
, &s
) < 0) return -1;
4764 if (self
->readline_func(self
, &s
) < 0) return -1;
4765 PDATA_APPEND(self
->stack
, Py_None
, -1);
4770 noload_newobj(Unpicklerobject
*self
)
4774 PDATA_POP(self
->stack
, obj
); /* pop argtuple */
4775 if (obj
== NULL
) return -1;
4778 PDATA_POP(self
->stack
, obj
); /* pop cls */
4779 if (obj
== NULL
) return -1;
4782 PDATA_APPEND(self
->stack
, Py_None
, -1);
4787 noload_global(Unpicklerobject
*self
)
4791 if (self
->readline_func(self
, &s
) < 0) return -1;
4792 if (self
->readline_func(self
, &s
) < 0) return -1;
4793 PDATA_APPEND(self
->stack
, Py_None
,-1);
4798 noload_reduce(Unpicklerobject
*self
)
4801 if (self
->stack
->length
< 2) return stackUnderflow();
4802 Pdata_clear(self
->stack
, self
->stack
->length
-2);
4803 PDATA_APPEND(self
->stack
, Py_None
,-1);
4808 noload_build(Unpicklerobject
*self
) {
4810 if (self
->stack
->length
< 1) return stackUnderflow();
4811 Pdata_clear(self
->stack
, self
->stack
->length
-1);
4816 noload_extension(Unpicklerobject
*self
, int nbytes
)
4820 assert(nbytes
== 1 || nbytes
== 2 || nbytes
== 4);
4821 if (self
->read_func(self
, &codebytes
, nbytes
) < 0) return -1;
4822 PDATA_APPEND(self
->stack
, Py_None
, -1);
4828 noload(Unpicklerobject
*self
)
4830 PyObject
*err
= 0, *val
= 0;
4833 self
->num_marks
= 0;
4834 Pdata_clear(self
->stack
, 0);
4837 if (self
->read_func(self
, &s
, 1) < 0)
4842 if (load_none(self
) < 0)
4847 if (load_binint(self
) < 0)
4852 if (load_binint1(self
) < 0)
4857 if (load_binint2(self
) < 0)
4862 if (load_int(self
) < 0)
4867 if (load_long(self
) < 0)
4872 if (load_counted_long(self
, 1) < 0)
4877 if (load_counted_long(self
, 4) < 0)
4882 if (load_float(self
) < 0)
4887 if (load_binfloat(self
) < 0)
4892 if (load_binstring(self
) < 0)
4896 case SHORT_BINSTRING
:
4897 if (load_short_binstring(self
) < 0)
4902 if (load_string(self
) < 0)
4906 #ifdef Py_USING_UNICODE
4908 if (load_unicode(self
) < 0)
4913 if (load_binunicode(self
) < 0)
4919 if (load_counted_tuple(self
, 0) < 0)
4924 if (load_counted_tuple(self
, 1) < 0)
4929 if (load_counted_tuple(self
, 2) < 0)
4934 if (load_counted_tuple(self
, 3) < 0)
4939 if (load_tuple(self
) < 0)
4944 if (load_empty_list(self
) < 0)
4949 if (load_list(self
) < 0)
4954 if (load_empty_dict(self
) < 0)
4959 if (load_dict(self
) < 0)
4964 if (noload_obj(self
) < 0)
4969 if (noload_inst(self
) < 0)
4974 if (noload_newobj(self
) < 0)
4979 if (noload_global(self
) < 0)
4984 if (load_append(self
) < 0)
4989 if (load_appends(self
) < 0)
4994 if (noload_build(self
) < 0)
4999 if (load_dup(self
) < 0)
5004 if (load_binget(self
) < 0)
5009 if (load_long_binget(self
) < 0)
5014 if (load_get(self
) < 0)
5019 if (noload_extension(self
, 1) < 0)
5024 if (noload_extension(self
, 2) < 0)
5029 if (noload_extension(self
, 4) < 0)
5034 if (load_mark(self
) < 0)
5039 if (load_binput(self
) < 0)
5044 if (load_long_binput(self
) < 0)
5049 if (load_put(self
) < 0)
5054 if (load_pop(self
) < 0)
5059 if (load_pop_mark(self
) < 0)
5064 if (load_setitem(self
) < 0)
5069 if (load_setitems(self
) < 0)
5077 if (load_persid(self
) < 0)
5082 if (load_binpersid(self
) < 0)
5087 if (noload_reduce(self
) < 0)
5092 if (load_proto(self
) < 0)
5097 if (load_bool(self
, Py_True
) < 0)
5102 if (load_bool(self
, Py_False
) < 0)
5106 cPickle_ErrFormat(UnpicklingError
,
5107 "invalid load key, '%s'.",
5115 if ((err
= PyErr_Occurred())) {
5116 if (err
== PyExc_EOFError
) {
5117 PyErr_SetNone(PyExc_EOFError
);
5122 PDATA_POP(self
->stack
, val
);
5128 Unpickler_load(Unpicklerobject
*self
, PyObject
*unused
)
5134 Unpickler_noload(Unpicklerobject
*self
, PyObject
*unused
)
5136 return noload(self
);
5140 static struct PyMethodDef Unpickler_methods
[] = {
5141 {"load", (PyCFunction
)Unpickler_load
, METH_NOARGS
,
5142 PyDoc_STR("load() -- Load a pickle")
5144 {"noload", (PyCFunction
)Unpickler_noload
, METH_NOARGS
,
5146 "noload() -- not load a pickle, but go through most of the motions\n"
5148 "This function can be used to read past a pickle without instantiating\n"
5149 "any objects or importing any modules. It can also be used to find all\n"
5150 "persistent references without instantiating any objects or importing\n"
5153 {NULL
, NULL
} /* sentinel */
5157 static Unpicklerobject
*
5158 newUnpicklerobject(PyObject
*f
)
5160 Unpicklerobject
*self
;
5162 if (!( self
= PyObject_GC_New(Unpicklerobject
, &Unpicklertype
)))
5167 self
->stack
= (Pdata
*)Pdata_New();
5168 self
->pers_func
= NULL
;
5169 self
->last_string
= NULL
;
5171 self
->num_marks
= 0;
5172 self
->marks_size
= 0;
5175 self
->readline
= NULL
;
5176 self
->find_class
= NULL
;
5178 if (!( self
->memo
= PyDict_New()))
5187 /* Set read, readline based on type of f */
5188 if (PyFile_Check(f
)) {
5189 self
->fp
= PyFile_AsFile(f
);
5190 if (self
->fp
== NULL
) {
5191 PyErr_SetString(PyExc_ValueError
,
5192 "I/O operation on closed file");
5195 self
->read_func
= read_file
;
5196 self
->readline_func
= readline_file
;
5198 else if (PycStringIO_InputCheck(f
)) {
5200 self
->read_func
= read_cStringIO
;
5201 self
->readline_func
= readline_cStringIO
;
5206 self
->read_func
= read_other
;
5207 self
->readline_func
= readline_other
;
5209 if (!( (self
->readline
= PyObject_GetAttr(f
, readline_str
)) &&
5210 (self
->read
= PyObject_GetAttr(f
, read_str
)))) {
5212 PyErr_SetString( PyExc_TypeError
,
5213 "argument must have 'read' and "
5214 "'readline' attributes" );
5218 PyObject_GC_Track(self
);
5223 Py_DECREF((PyObject
*)self
);
5229 get_Unpickler(PyObject
*self
, PyObject
*file
)
5231 return (PyObject
*)newUnpicklerobject(file
);
5236 Unpickler_dealloc(Unpicklerobject
*self
)
5238 PyObject_GC_UnTrack((PyObject
*)self
);
5239 Py_XDECREF(self
->readline
);
5240 Py_XDECREF(self
->read
);
5241 Py_XDECREF(self
->file
);
5242 Py_XDECREF(self
->memo
);
5243 Py_XDECREF(self
->stack
);
5244 Py_XDECREF(self
->pers_func
);
5245 Py_XDECREF(self
->arg
);
5246 Py_XDECREF(self
->last_string
);
5247 Py_XDECREF(self
->find_class
);
5253 if (self
->buf_size
) {
5257 self
->ob_type
->tp_free((PyObject
*)self
);
5261 Unpickler_traverse(Unpicklerobject
*self
, visitproc visit
, void *arg
)
5263 Py_VISIT(self
->readline
);
5264 Py_VISIT(self
->read
);
5265 Py_VISIT(self
->file
);
5266 Py_VISIT(self
->memo
);
5267 Py_VISIT(self
->stack
);
5268 Py_VISIT(self
->pers_func
);
5269 Py_VISIT(self
->arg
);
5270 Py_VISIT(self
->last_string
);
5271 Py_VISIT(self
->find_class
);
5276 Unpickler_clear(Unpicklerobject
*self
)
5278 Py_CLEAR(self
->readline
);
5279 Py_CLEAR(self
->read
);
5280 Py_CLEAR(self
->file
);
5281 Py_CLEAR(self
->memo
);
5282 Py_CLEAR(self
->stack
);
5283 Py_CLEAR(self
->pers_func
);
5284 Py_CLEAR(self
->arg
);
5285 Py_CLEAR(self
->last_string
);
5286 Py_CLEAR(self
->find_class
);
5291 Unpickler_getattr(Unpicklerobject
*self
, char *name
)
5293 if (!strcmp(name
, "persistent_load")) {
5294 if (!self
->pers_func
) {
5295 PyErr_SetString(PyExc_AttributeError
, name
);
5299 Py_INCREF(self
->pers_func
);
5300 return self
->pers_func
;
5303 if (!strcmp(name
, "find_global")) {
5304 if (!self
->find_class
) {
5305 PyErr_SetString(PyExc_AttributeError
, name
);
5309 Py_INCREF(self
->find_class
);
5310 return self
->find_class
;
5313 if (!strcmp(name
, "memo")) {
5315 PyErr_SetString(PyExc_AttributeError
, name
);
5319 Py_INCREF(self
->memo
);
5323 if (!strcmp(name
, "UnpicklingError")) {
5324 Py_INCREF(UnpicklingError
);
5325 return UnpicklingError
;
5328 return Py_FindMethod(Unpickler_methods
, (PyObject
*)self
, name
);
5333 Unpickler_setattr(Unpicklerobject
*self
, char *name
, PyObject
*value
)
5336 if (!strcmp(name
, "persistent_load")) {
5337 Py_XDECREF(self
->pers_func
);
5338 self
->pers_func
= value
;
5343 if (!strcmp(name
, "find_global")) {
5344 Py_XDECREF(self
->find_class
);
5345 self
->find_class
= value
;
5351 PyErr_SetString(PyExc_TypeError
,
5352 "attribute deletion is not supported");
5356 if (strcmp(name
, "memo") == 0) {
5357 if (!PyDict_Check(value
)) {
5358 PyErr_SetString(PyExc_TypeError
,
5359 "memo must be a dictionary");
5362 Py_XDECREF(self
->memo
);
5368 PyErr_SetString(PyExc_AttributeError
, name
);
5372 /* ---------------------------------------------------------------------------
5373 * Module-level functions.
5376 /* dump(obj, file, protocol=0). */
5378 cpm_dump(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
5380 static char *kwlist
[] = {"obj", "file", "protocol", NULL
};
5381 PyObject
*ob
, *file
, *res
= NULL
;
5382 Picklerobject
*pickler
= 0;
5385 if (!( PyArg_ParseTupleAndKeywords(args
, kwds
, "OO|i", kwlist
,
5386 &ob
, &file
, &proto
)))
5389 if (!( pickler
= newPicklerobject(file
, proto
)))
5392 if (dump(pickler
, ob
) < 0)
5399 Py_XDECREF(pickler
);
5405 /* dumps(obj, protocol=0). */
5407 cpm_dumps(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
5409 static char *kwlist
[] = {"obj", "protocol", NULL
};
5410 PyObject
*ob
, *file
= 0, *res
= NULL
;
5411 Picklerobject
*pickler
= 0;
5414 if (!( PyArg_ParseTupleAndKeywords(args
, kwds
, "O|i:dumps", kwlist
,
5418 if (!( file
= PycStringIO
->NewOutput(128)))
5421 if (!( pickler
= newPicklerobject(file
, proto
)))
5424 if (dump(pickler
, ob
) < 0)
5427 res
= PycStringIO
->cgetvalue(file
);
5430 Py_XDECREF(pickler
);
5437 /* load(fileobj). */
5439 cpm_load(PyObject
*self
, PyObject
*ob
)
5441 Unpicklerobject
*unpickler
= 0;
5442 PyObject
*res
= NULL
;
5444 if (!( unpickler
= newUnpicklerobject(ob
)))
5447 res
= load(unpickler
);
5450 Py_XDECREF(unpickler
);
5458 cpm_loads(PyObject
*self
, PyObject
*args
)
5460 PyObject
*ob
, *file
= 0, *res
= NULL
;
5461 Unpicklerobject
*unpickler
= 0;
5463 if (!( PyArg_ParseTuple(args
, "S:loads", &ob
)))
5466 if (!( file
= PycStringIO
->NewInput(ob
)))
5469 if (!( unpickler
= newUnpicklerobject(file
)))
5472 res
= load(unpickler
);
5476 Py_XDECREF(unpickler
);
5482 PyDoc_STRVAR(Unpicklertype__doc__
,
5483 "Objects that know how to unpickle");
5485 static PyTypeObject Unpicklertype
= {
5486 PyObject_HEAD_INIT(NULL
)
5488 "cPickle.Unpickler", /*tp_name*/
5489 sizeof(Unpicklerobject
), /*tp_basicsize*/
5491 (destructor
)Unpickler_dealloc
, /* tp_dealloc */
5493 (getattrfunc
)Unpickler_getattr
, /* tp_getattr */
5494 (setattrfunc
)Unpickler_setattr
, /* tp_setattr */
5497 0, /* tp_as_number */
5498 0, /* tp_as_sequence */
5499 0, /* tp_as_mapping */
5503 0, /* tp_getattro */
5504 0, /* tp_setattro */
5505 0, /* tp_as_buffer */
5506 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
| Py_TPFLAGS_HAVE_GC
,
5507 Unpicklertype__doc__
, /* tp_doc */
5508 (traverseproc
)Unpickler_traverse
, /* tp_traverse */
5509 (inquiry
)Unpickler_clear
, /* tp_clear */
5512 static struct PyMethodDef cPickle_methods
[] = {
5513 {"dump", (PyCFunction
)cpm_dump
, METH_VARARGS
| METH_KEYWORDS
,
5514 PyDoc_STR("dump(obj, file, protocol=0) -- "
5515 "Write an object in pickle format to the given file.\n"
5517 "See the Pickler docstring for the meaning of optional argument proto.")
5520 {"dumps", (PyCFunction
)cpm_dumps
, METH_VARARGS
| METH_KEYWORDS
,
5521 PyDoc_STR("dumps(obj, protocol=0) -- "
5522 "Return a string containing an object in pickle format.\n"
5524 "See the Pickler docstring for the meaning of optional argument proto.")
5527 {"load", (PyCFunction
)cpm_load
, METH_O
,
5528 PyDoc_STR("load(file) -- Load a pickle from the given file")},
5530 {"loads", (PyCFunction
)cpm_loads
, METH_VARARGS
,
5531 PyDoc_STR("loads(string) -- Load a pickle from the given string")},
5533 {"Pickler", (PyCFunction
)get_Pickler
, METH_VARARGS
| METH_KEYWORDS
,
5534 PyDoc_STR("Pickler(file, protocol=0) -- Create a pickler.\n"
5536 "This takes a file-like object for writing a pickle data stream.\n"
5537 "The optional proto argument tells the pickler to use the given\n"
5538 "protocol; supported protocols are 0, 1, 2. The default\n"
5539 "protocol is 0, to be backwards compatible. (Protocol 0 is the\n"
5540 "only protocol that can be written to a file opened in text\n"
5541 "mode and read back successfully. When using a protocol higher\n"
5542 "than 0, make sure the file is opened in binary mode, both when\n"
5543 "pickling and unpickling.)\n"
5545 "Protocol 1 is more efficient than protocol 0; protocol 2 is\n"
5546 "more efficient than protocol 1.\n"
5548 "Specifying a negative protocol version selects the highest\n"
5549 "protocol version supported. The higher the protocol used, the\n"
5550 "more recent the version of Python needed to read the pickle\n"
5553 "The file parameter must have a write() method that accepts a single\n"
5554 "string argument. It can thus be an open file object, a StringIO\n"
5555 "object, or any other custom object that meets this interface.\n")
5558 {"Unpickler", (PyCFunction
)get_Unpickler
, METH_O
,
5559 PyDoc_STR("Unpickler(file) -- Create an unpickler.")},
5565 init_stuff(PyObject
*module_dict
)
5567 PyObject
*copy_reg
, *t
, *r
;
5569 #define INIT_STR(S) if (!( S ## _str=PyString_InternFromString(#S))) return -1;
5571 if (PyType_Ready(&Unpicklertype
) < 0)
5573 if (PyType_Ready(&Picklertype
) < 0)
5576 INIT_STR(__class__
);
5577 INIT_STR(__getinitargs__
);
5579 INIT_STR(__getstate__
);
5580 INIT_STR(__setstate__
);
5583 INIT_STR(__reduce__
);
5584 INIT_STR(__reduce_ex__
);
5590 INIT_STR(dispatch_table
);
5592 if (!( copy_reg
= PyImport_ImportModule("copy_reg")))
5595 /* This is special because we want to use a different
5596 one in restricted mode. */
5597 dispatch_table
= PyObject_GetAttr(copy_reg
, dispatch_table_str
);
5598 if (!dispatch_table
) return -1;
5600 extension_registry
= PyObject_GetAttrString(copy_reg
,
5601 "_extension_registry");
5602 if (!extension_registry
) return -1;
5604 inverted_registry
= PyObject_GetAttrString(copy_reg
,
5605 "_inverted_registry");
5606 if (!inverted_registry
) return -1;
5608 extension_cache
= PyObject_GetAttrString(copy_reg
,
5609 "_extension_cache");
5610 if (!extension_cache
) return -1;
5612 Py_DECREF(copy_reg
);
5614 if (!(empty_tuple
= PyTuple_New(0)))
5617 two_tuple
= PyTuple_New(2);
5618 if (two_tuple
== NULL
)
5620 /* We use this temp container with no regard to refcounts, or to
5621 * keeping containees alive. Exempt from GC, because we don't
5622 * want anything looking at two_tuple() by magic.
5624 PyObject_GC_UnTrack(two_tuple
);
5627 if (!( t
=PyImport_ImportModule("__builtin__"))) return -1;
5628 if (PyDict_SetItemString(module_dict
, "__builtins__", t
) < 0)
5631 if (!( t
=PyDict_New())) return -1;
5632 if (!( r
=PyRun_String(
5633 "def __str__(self):\n"
5634 " return self.args and ('%s' % self.args[0]) or '(what)'\n",
5636 module_dict
, t
) )) return -1;
5639 PickleError
= PyErr_NewException("cPickle.PickleError", NULL
, t
);
5645 PicklingError
= PyErr_NewException("cPickle.PicklingError",
5650 if (!( t
=PyDict_New())) return -1;
5651 if (!( r
=PyRun_String(
5652 "def __str__(self):\n"
5654 " a=a and type(a[0]) or '(what)'\n"
5655 " return 'Cannot pickle %s objects' % a\n"
5657 module_dict
, t
) )) return -1;
5660 if (!( UnpickleableError
= PyErr_NewException(
5661 "cPickle.UnpickleableError", PicklingError
, t
)))
5666 if (!( UnpicklingError
= PyErr_NewException("cPickle.UnpicklingError",
5667 PickleError
, NULL
)))
5670 if (!( BadPickleGet
= PyErr_NewException("cPickle.BadPickleGet",
5671 UnpicklingError
, NULL
)))
5674 if (PyDict_SetItemString(module_dict
, "PickleError",
5678 if (PyDict_SetItemString(module_dict
, "PicklingError",
5682 if (PyDict_SetItemString(module_dict
, "UnpicklingError",
5683 UnpicklingError
) < 0)
5686 if (PyDict_SetItemString(module_dict
, "UnpickleableError",
5687 UnpickleableError
) < 0)
5690 if (PyDict_SetItemString(module_dict
, "BadPickleGet",
5699 #ifndef PyMODINIT_FUNC /* declarations for DLL import/export */
5700 #define PyMODINIT_FUNC void
5705 PyObject
*m
, *d
, *di
, *v
, *k
;
5707 char *rev
= "1.71"; /* XXX when does this change? */
5708 PyObject
*format_version
;
5709 PyObject
*compatible_formats
;
5711 Picklertype
.ob_type
= &PyType_Type
;
5712 Unpicklertype
.ob_type
= &PyType_Type
;
5713 PdataType
.ob_type
= &PyType_Type
;
5715 /* Initialize some pieces. We need to do this before module creation,
5716 * so we're forced to use a temporary dictionary. :(
5720 if (init_stuff(di
) < 0) return;
5722 /* Create the module and add the functions */
5723 m
= Py_InitModule4("cPickle", cPickle_methods
,
5724 cPickle_module_documentation
,
5725 (PyObject
*)NULL
,PYTHON_API_VERSION
);
5729 /* Add some symbolic constants to the module */
5730 d
= PyModule_GetDict(m
);
5731 v
= PyString_FromString(rev
);
5732 PyDict_SetItemString(d
, "__version__", v
);
5735 /* Copy data from di. Waaa. */
5736 for (i
=0; PyDict_Next(di
, &i
, &k
, &v
); ) {
5737 if (PyObject_SetItem(d
, k
, v
) < 0) {
5744 i
= PyModule_AddIntConstant(m
, "HIGHEST_PROTOCOL", HIGHEST_PROTOCOL
);
5748 /* These are purely informational; no code uses them. */
5749 /* File format version we write. */
5750 format_version
= PyString_FromString("2.0");
5751 /* Format versions we can read. */
5752 compatible_formats
= Py_BuildValue("[sssss]",
5753 "1.0", /* Original protocol 0 */
5754 "1.1", /* Protocol 0 + INST */
5755 "1.2", /* Original protocol 1 */
5756 "1.3", /* Protocol 1 + BINFLOAT */
5757 "2.0"); /* Original protocol 2 */
5758 PyDict_SetItemString(d
, "format_version", format_version
);
5759 PyDict_SetItemString(d
, "compatible_formats", compatible_formats
);
5760 Py_XDECREF(format_version
);
5761 Py_XDECREF(compatible_formats
);