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 *copyreg_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 PyVarObject_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) (Py_TYPE(O) == &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 (Py_REFCNT(self->arg) > 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 */
342 int (*write_func
)(struct Picklerobject
*, const char *, Py_ssize_t
);
345 PyObject
*dispatch_table
;
346 int fast_container
; /* count nested container dumps */
350 #ifndef PY_CPICKLE_FAST_LIMIT
351 #define PY_CPICKLE_FAST_LIMIT 50
354 static PyTypeObject Picklertype
;
356 typedef struct Unpicklerobject
{
367 PyObject
*last_string
;
371 Py_ssize_t (*read_func
)(struct Unpicklerobject
*, char **, Py_ssize_t
);
372 Py_ssize_t (*readline_func
)(struct Unpicklerobject
*, char **);
375 PyObject
*find_class
;
378 static PyTypeObject Unpicklertype
;
380 /* Forward decls that need the above structs */
381 static int save(Picklerobject
*, PyObject
*, int);
382 static int put2(Picklerobject
*, PyObject
*);
386 cPickle_ErrFormat(PyObject
*ErrType
, char *stringformat
, char *format
, ...)
389 PyObject
*args
=0, *retval
=0;
390 va_start(va
, format
);
392 if (format
) args
= Py_VaBuildValue(format
, va
);
394 if (format
&& ! args
) return NULL
;
395 if (stringformat
&& !(retval
=PyString_FromString(stringformat
)))
401 v
=PyString_Format(retval
, args
);
404 if (! v
) return NULL
;
409 if (args
) retval
=args
;
411 PyErr_SetObject(ErrType
,Py_None
);
414 PyErr_SetObject(ErrType
,retval
);
420 write_file(Picklerobject
*self
, const char *s
, Py_ssize_t n
)
422 size_t nbyteswritten
;
429 /* String too large */
433 PyFile_IncUseCount((PyFileObject
*)self
->file
);
434 Py_BEGIN_ALLOW_THREADS
435 nbyteswritten
= fwrite(s
, sizeof(char), n
, self
->fp
);
437 PyFile_DecUseCount((PyFileObject
*)self
->file
);
438 if (nbyteswritten
!= (size_t)n
) {
439 PyErr_SetFromErrno(PyExc_IOError
);
447 write_cStringIO(Picklerobject
*self
, const char *s
, Py_ssize_t n
)
453 if (PycStringIO
->cwrite((PyObject
*)self
->file
, s
, n
) != n
) {
461 write_none(Picklerobject
*self
, const char *s
, Py_ssize_t n
)
463 if (s
== NULL
) return 0;
464 if (n
> INT_MAX
) return -1;
469 write_other(Picklerobject
*self
, const char *s
, Py_ssize_t _n
)
471 PyObject
*py_str
= 0, *junk
= 0;
478 if (!( self
->buf_size
)) return 0;
479 py_str
= PyString_FromStringAndSize(self
->write_buf
,
485 if (self
->buf_size
&& (n
+ self
->buf_size
) > WRITE_BUF_SIZE
) {
486 if (write_other(self
, NULL
, 0) < 0)
490 if (n
> WRITE_BUF_SIZE
) {
492 PyString_FromStringAndSize(s
, n
)))
496 memcpy(self
->write_buf
+ self
->buf_size
, s
, n
);
503 /* object with write method */
504 ARG_TUP(self
, py_str
);
506 junk
= PyObject_Call(self
->write
, self
->arg
, NULL
);
509 if (junk
) Py_DECREF(junk
);
513 PDATA_PUSH(self
->file
, py_str
, -1);
521 read_file(Unpicklerobject
*self
, char **s
, Py_ssize_t n
)
525 if (self
->buf_size
== 0) {
528 size
= ((n
< 32) ? 32 : n
);
529 if (!( self
->buf
= (char *)malloc(size
))) {
534 self
->buf_size
= size
;
536 else if (n
> self
->buf_size
) {
537 char *newbuf
= (char *)realloc(self
->buf
, n
);
546 PyFile_IncUseCount((PyFileObject
*)self
->file
);
547 Py_BEGIN_ALLOW_THREADS
548 nbytesread
= fread(self
->buf
, sizeof(char), n
, self
->fp
);
550 PyFile_DecUseCount((PyFileObject
*)self
->file
);
551 if (nbytesread
!= (size_t)n
) {
552 if (feof(self
->fp
)) {
553 PyErr_SetNone(PyExc_EOFError
);
557 PyErr_SetFromErrno(PyExc_IOError
);
568 readline_file(Unpicklerobject
*self
, char **s
)
572 if (self
->buf_size
== 0) {
573 if (!( self
->buf
= (char *)malloc(40))) {
584 for (; i
< (self
->buf_size
- 1); i
++) {
585 if (feof(self
->fp
) ||
586 (self
->buf
[i
] = getc(self
->fp
)) == '\n') {
587 self
->buf
[i
+ 1] = '\0';
592 bigger
= self
->buf_size
<< 1;
593 if (bigger
<= 0) { /* overflow */
597 newbuf
= (char *)realloc(self
->buf
, bigger
);
603 self
->buf_size
= bigger
;
609 read_cStringIO(Unpicklerobject
*self
, char **s
, Py_ssize_t n
)
613 if (PycStringIO
->cread((PyObject
*)self
->file
, &ptr
, n
) != n
) {
614 PyErr_SetNone(PyExc_EOFError
);
625 readline_cStringIO(Unpicklerobject
*self
, char **s
)
630 if ((n
= PycStringIO
->creadline((PyObject
*)self
->file
, &ptr
)) < 0) {
641 read_other(Unpicklerobject
*self
, char **s
, Py_ssize_t n
)
643 PyObject
*bytes
, *str
=0;
645 if (!( bytes
= PyInt_FromSsize_t(n
))) return -1;
647 ARG_TUP(self
, bytes
);
649 str
= PyObject_Call(self
->read
, self
->arg
, NULL
);
652 if (! str
) return -1;
654 Py_XDECREF(self
->last_string
);
655 self
->last_string
= str
;
657 if (! (*s
= PyString_AsString(str
))) return -1;
663 readline_other(Unpicklerobject
*self
, char **s
)
668 if (!( str
= PyObject_CallObject(self
->readline
, empty_tuple
))) {
672 if ((str_size
= PyString_Size(str
)) < 0)
675 Py_XDECREF(self
->last_string
);
676 self
->last_string
= str
;
678 if (! (*s
= PyString_AsString(str
)))
684 /* Copy the first n bytes from s into newly malloc'ed memory, plus a
685 * trailing 0 byte. Return a pointer to that, or NULL if out of memory.
686 * The caller is responsible for free()'ing the return value.
689 pystrndup(const char *s
, int n
)
691 char *r
= (char *)malloc(n
+1);
693 return (char*)PyErr_NoMemory();
701 get(Picklerobject
*self
, PyObject
*id
)
703 PyObject
*value
, *mv
;
708 if (!( mv
= PyDict_GetItem(self
->memo
, id
))) {
709 PyErr_SetObject(PyExc_KeyError
, id
);
713 if (!( value
= PyTuple_GetItem(mv
, 0)))
716 if (!( PyInt_Check(value
))) {
717 PyErr_SetString(PicklingError
, "no int where int expected in memo");
720 c_value
= PyInt_AS_LONG((PyIntObject
*)value
);
724 PyOS_snprintf(s
+ 1, sizeof(s
) - 1, "%ld\n", c_value
);
727 else if (Pdata_Check(self
->file
)) {
728 if (write_other(self
, NULL
, 0) < 0) return -1;
729 PDATA_APPEND(self
->file
, mv
, -1);
735 s
[1] = (int)(c_value
& 0xff);
740 s
[1] = (int)(c_value
& 0xff);
741 s
[2] = (int)((c_value
>> 8) & 0xff);
742 s
[3] = (int)((c_value
>> 16) & 0xff);
743 s
[4] = (int)((c_value
>> 24) & 0xff);
748 if (self
->write_func(self
, s
, len
) < 0)
756 put(Picklerobject
*self
, PyObject
*ob
)
758 if (Py_REFCNT(ob
) < 2 || self
->fast
)
761 return put2(self
, ob
);
766 put2(Picklerobject
*self
, PyObject
*ob
)
772 PyObject
*py_ob_id
= 0, *memo_len
= 0, *t
= 0;
777 if ((p
= PyDict_Size(self
->memo
)) < 0)
780 /* Make sure memo keys are positive! */
782 * XXX And does "positive" really mean non-negative?
783 * XXX pickle.py starts with PUT index 0, not 1. This makes for
784 * XXX gratuitous differences between the pickling modules.
788 if (!( py_ob_id
= PyLong_FromVoidPtr(ob
)))
791 if (!( memo_len
= PyInt_FromLong(p
)))
794 if (!( t
= PyTuple_New(2)))
797 PyTuple_SET_ITEM(t
, 0, memo_len
);
799 PyTuple_SET_ITEM(t
, 1, ob
);
802 if (PyDict_SetItem(self
->memo
, py_ob_id
, t
) < 0)
807 PyOS_snprintf(c_str
+ 1, sizeof(c_str
) - 1, "%d\n", p
);
810 else if (Pdata_Check(self
->file
)) {
811 if (write_other(self
, NULL
, 0) < 0) return -1;
812 PDATA_APPEND(self
->file
, memo_len
, -1);
813 res
=0; /* Job well done ;) */
818 c_str
[0] = LONG_BINPUT
;
819 c_str
[1] = (int)(p
& 0xff);
820 c_str
[2] = (int)((p
>> 8) & 0xff);
821 c_str
[3] = (int)((p
>> 16) & 0xff);
822 c_str
[4] = (int)((p
>> 24) & 0xff);
832 if (self
->write_func(self
, c_str
, len
) < 0)
838 Py_XDECREF(py_ob_id
);
839 Py_XDECREF(memo_len
);
846 whichmodule(PyObject
*global
, PyObject
*global_name
)
849 PyObject
*module
= 0, *modules_dict
= 0,
850 *global_name_attr
= 0, *name
= 0;
852 module
= PyObject_GetAttrString(global
, "__module__");
855 if (PyErr_ExceptionMatches(PyExc_AttributeError
))
860 if (!( modules_dict
= PySys_GetObject("modules")))
864 while ((j
= PyDict_Next(modules_dict
, &i
, &name
, &module
))) {
866 if (PyObject_Compare(name
, __main___str
)==0) continue;
868 global_name_attr
= PyObject_GetAttr(module
, global_name
);
869 if (!global_name_attr
) {
870 if (PyErr_ExceptionMatches(PyExc_AttributeError
))
877 if (global_name_attr
!= global
) {
878 Py_DECREF(global_name_attr
);
882 Py_DECREF(global_name_attr
);
887 /* The following implements the rule in pickle.py added in 1.5
888 that used __main__ if no module is found. I don't actually
902 fast_save_enter(Picklerobject
*self
, PyObject
*obj
)
904 /* if fast_container < 0, we're doing an error exit. */
905 if (++self
->fast_container
>= PY_CPICKLE_FAST_LIMIT
) {
906 PyObject
*key
= NULL
;
907 if (self
->fast_memo
== NULL
) {
908 self
->fast_memo
= PyDict_New();
909 if (self
->fast_memo
== NULL
) {
910 self
->fast_container
= -1;
914 key
= PyLong_FromVoidPtr(obj
);
917 if (PyDict_GetItem(self
->fast_memo
, key
)) {
919 PyErr_Format(PyExc_ValueError
,
920 "fast mode: can't pickle cyclic objects "
921 "including object type %s at %p",
922 Py_TYPE(obj
)->tp_name
, obj
);
923 self
->fast_container
= -1;
926 if (PyDict_SetItem(self
->fast_memo
, key
, Py_None
) < 0) {
928 self
->fast_container
= -1;
937 fast_save_leave(Picklerobject
*self
, PyObject
*obj
)
939 if (self
->fast_container
-- >= PY_CPICKLE_FAST_LIMIT
) {
940 PyObject
*key
= PyLong_FromVoidPtr(obj
);
943 if (PyDict_DelItem(self
->fast_memo
, key
) < 0) {
953 save_none(Picklerobject
*self
, PyObject
*args
)
955 static char none
= NONE
;
956 if (self
->write_func(self
, &none
, 1) < 0)
963 save_bool(Picklerobject
*self
, PyObject
*args
)
965 static const char *buf
[2] = {FALSE
, TRUE
};
966 static char len
[2] = {sizeof(FALSE
)-1, sizeof(TRUE
)-1};
967 long l
= PyInt_AS_LONG((PyIntObject
*)args
);
969 if (self
->proto
>= 2) {
970 char opcode
= l
? NEWTRUE
: NEWFALSE
;
971 if (self
->write_func(self
, &opcode
, 1) < 0)
974 else if (self
->write_func(self
, buf
[l
], len
[l
]) < 0)
980 save_int(Picklerobject
*self
, PyObject
*args
)
983 long l
= PyInt_AS_LONG((PyIntObject
*)args
);
992 /* Text-mode pickle, or long too big to fit in the 4-byte
993 * signed BININT format: store as a string.
996 PyOS_snprintf(c_str
+ 1, sizeof(c_str
) - 1, "%ld\n", l
);
997 if (self
->write_func(self
, c_str
, strlen(c_str
)) < 0)
1001 /* Binary pickle and l fits in a signed 4-byte int. */
1002 c_str
[1] = (int)( l
& 0xff);
1003 c_str
[2] = (int)((l
>> 8) & 0xff);
1004 c_str
[3] = (int)((l
>> 16) & 0xff);
1005 c_str
[4] = (int)((l
>> 24) & 0xff);
1007 if ((c_str
[4] == 0) && (c_str
[3] == 0)) {
1008 if (c_str
[2] == 0) {
1022 if (self
->write_func(self
, c_str
, len
) < 0)
1031 save_long(Picklerobject
*self
, PyObject
*args
)
1035 PyObject
*repr
= NULL
;
1037 static char l
= LONG
;
1039 if (self
->proto
>= 2) {
1040 /* Linear-time pickling. */
1043 unsigned char *pdata
;
1046 int sign
= _PyLong_Sign(args
);
1049 /* It's 0 -- an empty bytestring. */
1052 i
= self
->write_func(self
, c_str
, 2);
1053 if (i
< 0) goto finally
;
1057 nbits
= _PyLong_NumBits(args
);
1058 if (nbits
== (size_t)-1 && PyErr_Occurred())
1060 /* How many bytes do we need? There are nbits >> 3 full
1061 * bytes of data, and nbits & 7 leftover bits. If there
1062 * are any leftover bits, then we clearly need another
1063 * byte. Wnat's not so obvious is that we *probably*
1064 * need another byte even if there aren't any leftovers:
1065 * the most-significant bit of the most-significant byte
1066 * acts like a sign bit, and it's usually got a sense
1067 * opposite of the one we need. The exception is longs
1068 * of the form -(2**(8*j-1)) for j > 0. Such a long is
1069 * its own 256's-complement, so has the right sign bit
1070 * even without the extra byte. That's a pain to check
1071 * for in advance, though, so we always grab an extra
1072 * byte at the start, and cut it back later if possible.
1074 nbytes
= (nbits
>> 3) + 1;
1075 if (nbytes
> INT_MAX
) {
1076 PyErr_SetString(PyExc_OverflowError
, "long too large "
1080 repr
= PyString_FromStringAndSize(NULL
, (int)nbytes
);
1081 if (repr
== NULL
) goto finally
;
1082 pdata
= (unsigned char *)PyString_AS_STRING(repr
);
1083 i
= _PyLong_AsByteArray((PyLongObject
*)args
,
1085 1 /* little endian */, 1 /* signed */);
1086 if (i
< 0) goto finally
;
1087 /* If the long is negative, this may be a byte more than
1088 * needed. This is so iff the MSB is all redundant sign
1091 if (sign
< 0 && nbytes
> 1 && pdata
[nbytes
- 1] == 0xff &&
1092 (pdata
[nbytes
- 2] & 0x80) != 0)
1097 c_str
[1] = (char)nbytes
;
1103 for (i
= 1; i
< 5; i
++) {
1104 c_str
[i
] = (char)(size
& 0xff);
1109 i
= self
->write_func(self
, c_str
, size
);
1110 if (i
< 0) goto finally
;
1111 i
= self
->write_func(self
, (char *)pdata
, (int)nbytes
);
1112 if (i
< 0) goto finally
;
1117 /* proto < 2: write the repr and newline. This is quadratic-time
1118 * (in the number of digits), in both directions.
1120 if (!( repr
= PyObject_Repr(args
)))
1123 if ((size
= PyString_Size(repr
)) < 0)
1126 if (self
->write_func(self
, &l
, 1) < 0)
1129 if (self
->write_func(self
,
1130 PyString_AS_STRING((PyStringObject
*)repr
),
1134 if (self
->write_func(self
, "\n", 1) < 0)
1146 save_float(Picklerobject
*self
, PyObject
*args
)
1148 double x
= PyFloat_AS_DOUBLE((PyFloatObject
*)args
);
1153 if (_PyFloat_Pack8(x
, (unsigned char *)&str
[1], 0) < 0)
1155 if (self
->write_func(self
, str
, 9) < 0)
1161 PyOS_ascii_formatd(c_str
+ 1, sizeof(c_str
) - 2, "%.17g", x
);
1162 /* Extend the formatted string with a newline character */
1163 strcat(c_str
, "\n");
1165 if (self
->write_func(self
, c_str
, strlen(c_str
)) < 0)
1174 save_string(Picklerobject
*self
, PyObject
*args
, int doput
)
1179 if ((size
= PyString_Size(args
)) < 0)
1185 static char string
= STRING
;
1187 if (!( repr
= PyObject_Repr(args
)))
1190 if ((len
= PyString_Size(repr
)) < 0)
1192 repr_str
= PyString_AS_STRING((PyStringObject
*)repr
);
1194 if (self
->write_func(self
, &string
, 1) < 0)
1197 if (self
->write_func(self
, repr_str
, len
) < 0)
1200 if (self
->write_func(self
, "\n", 1) < 0)
1209 if ((size
= PyString_Size(args
)) < 0)
1213 c_str
[0] = SHORT_BINSTRING
;
1217 else if (size
<= INT_MAX
) {
1218 c_str
[0] = BINSTRING
;
1219 for (i
= 1; i
< 5; i
++)
1220 c_str
[i
] = (int)(size
>> ((i
- 1) * 8));
1224 return -1; /* string too large */
1226 if (self
->write_func(self
, c_str
, len
) < 0)
1229 if (size
> 128 && Pdata_Check(self
->file
)) {
1230 if (write_other(self
, NULL
, 0) < 0) return -1;
1231 PDATA_APPEND(self
->file
, args
, -1);
1234 if (self
->write_func(self
,
1236 (PyStringObject
*)args
),
1243 if (put(self
, args
) < 0)
1254 #ifdef Py_USING_UNICODE
1255 /* A copy of PyUnicode_EncodeRawUnicodeEscape() that also translates
1256 backslash and newline characters to \uXXXX escapes. */
1258 modified_EncodeRawUnicodeEscape(const Py_UNICODE
*s
, int size
)
1264 static const char *hexdigit
= "0123456789ABCDEF";
1266 repr
= PyString_FromStringAndSize(NULL
, 6 * size
);
1272 p
= q
= PyString_AS_STRING(repr
);
1273 while (size
-- > 0) {
1274 Py_UNICODE ch
= *s
++;
1275 /* Map 16-bit characters to '\uxxxx' */
1276 if (ch
>= 256 || ch
== '\\' || ch
== '\n') {
1279 *p
++ = hexdigit
[(ch
>> 12) & 0xf];
1280 *p
++ = hexdigit
[(ch
>> 8) & 0xf];
1281 *p
++ = hexdigit
[(ch
>> 4) & 0xf];
1282 *p
++ = hexdigit
[ch
& 15];
1284 /* Copy everything else as-is */
1289 _PyString_Resize(&repr
, p
- q
);
1295 save_unicode(Picklerobject
*self
, PyObject
*args
, int doput
)
1297 Py_ssize_t size
, len
;
1300 if (!PyUnicode_Check(args
))
1305 static char string
= UNICODE
;
1307 repr
= modified_EncodeRawUnicodeEscape(
1308 PyUnicode_AS_UNICODE(args
), PyUnicode_GET_SIZE(args
));
1312 if ((len
= PyString_Size(repr
)) < 0)
1314 repr_str
= PyString_AS_STRING((PyStringObject
*)repr
);
1316 if (self
->write_func(self
, &string
, 1) < 0)
1319 if (self
->write_func(self
, repr_str
, len
) < 0)
1322 if (self
->write_func(self
, "\n", 1) < 0)
1331 if (!( repr
= PyUnicode_AsUTF8String(args
)))
1334 if ((size
= PyString_Size(repr
)) < 0)
1337 return -1; /* string too large */
1339 c_str
[0] = BINUNICODE
;
1340 for (i
= 1; i
< 5; i
++)
1341 c_str
[i
] = (int)(size
>> ((i
- 1) * 8));
1344 if (self
->write_func(self
, c_str
, len
) < 0)
1347 if (size
> 128 && Pdata_Check(self
->file
)) {
1348 if (write_other(self
, NULL
, 0) < 0)
1350 PDATA_APPEND(self
->file
, repr
, -1);
1353 if (self
->write_func(self
, PyString_AS_STRING(repr
),
1362 if (put(self
, args
) < 0)
1373 /* A helper for save_tuple. Push the len elements in tuple t on the stack. */
1375 store_tuple_elements(Picklerobject
*self
, PyObject
*t
, int len
)
1378 int res
= -1; /* guilty until proved innocent */
1380 assert(PyTuple_Size(t
) == len
);
1382 for (i
= 0; i
< len
; i
++) {
1383 PyObject
*element
= PyTuple_GET_ITEM(t
, i
);
1385 if (element
== NULL
)
1387 if (save(self
, element
, 0) < 0)
1396 /* Tuples are ubiquitous in the pickle protocols, so many techniques are
1397 * used across protocols to minimize the space needed to pickle them.
1398 * Tuples are also the only builtin immutable type that can be recursive
1399 * (a tuple can be reached from itself), and that requires some subtle
1400 * magic so that it works in all cases. IOW, this is a long routine.
1403 save_tuple(Picklerobject
*self
, PyObject
*args
)
1405 PyObject
*py_tuple_id
= NULL
;
1409 static char tuple
= TUPLE
;
1410 static char pop
= POP
;
1411 static char pop_mark
= POP_MARK
;
1412 static char len2opcode
[] = {EMPTY_TUPLE
, TUPLE1
, TUPLE2
, TUPLE3
};
1414 if ((len
= PyTuple_Size(args
)) < 0)
1421 c_str
[0] = EMPTY_TUPLE
;
1429 if (self
->write_func(self
, c_str
, len
) >= 0)
1431 /* Don't memoize an empty tuple. */
1435 /* A non-empty tuple. */
1437 /* id(tuple) isn't in the memo now. If it shows up there after
1438 * saving the tuple elements, the tuple must be recursive, in
1439 * which case we'll pop everything we put on the stack, and fetch
1440 * its value from the memo.
1442 py_tuple_id
= PyLong_FromVoidPtr(args
);
1443 if (py_tuple_id
== NULL
)
1446 if (len
<= 3 && self
->proto
>= 2) {
1447 /* Use TUPLE{1,2,3} opcodes. */
1448 if (store_tuple_elements(self
, args
, len
) < 0)
1450 if (PyDict_GetItem(self
->memo
, py_tuple_id
)) {
1451 /* pop the len elements */
1452 for (i
= 0; i
< len
; ++i
)
1453 if (self
->write_func(self
, &pop
, 1) < 0)
1455 /* fetch from memo */
1456 if (get(self
, py_tuple_id
) < 0)
1461 /* Not recursive. */
1462 if (self
->write_func(self
, len2opcode
+ len
, 1) < 0)
1467 /* proto < 2 and len > 0, or proto >= 2 and len > 3.
1468 * Generate MARK elt1 elt2 ... TUPLE
1470 if (self
->write_func(self
, &MARKv
, 1) < 0)
1473 if (store_tuple_elements(self
, args
, len
) < 0)
1476 if (PyDict_GetItem(self
->memo
, py_tuple_id
)) {
1477 /* pop the stack stuff we pushed */
1479 if (self
->write_func(self
, &pop_mark
, 1) < 0)
1483 /* Note that we pop one more than len, to remove
1486 for (i
= 0; i
<= len
; i
++)
1487 if (self
->write_func(self
, &pop
, 1) < 0)
1490 /* fetch from memo */
1491 if (get(self
, py_tuple_id
) >= 0)
1496 /* Not recursive. */
1497 if (self
->write_func(self
, &tuple
, 1) < 0)
1501 if (put(self
, args
) >= 0)
1505 Py_XDECREF(py_tuple_id
);
1509 /* iter is an iterator giving items, and we batch up chunks of
1510 * MARK item item ... item APPENDS
1511 * opcode sequences. Calling code should have arranged to first create an
1512 * empty list, or list-like object, for the APPENDS to operate on.
1513 * Returns 0 on success, <0 on error.
1516 batch_list(Picklerobject
*self
, PyObject
*iter
)
1519 PyObject
*slice
[BATCHSIZE
];
1522 static char append
= APPEND
;
1523 static char appends
= APPENDS
;
1525 assert(iter
!= NULL
);
1527 if (self
->proto
== 0) {
1528 /* APPENDS isn't available; do one at a time. */
1530 obj
= PyIter_Next(iter
);
1532 if (PyErr_Occurred())
1536 i
= save(self
, obj
, 0);
1540 if (self
->write_func(self
, &append
, 1) < 0)
1546 /* proto > 0: write in batches of BATCHSIZE. */
1548 /* Get next group of (no more than) BATCHSIZE elements. */
1549 for (n
= 0; n
< BATCHSIZE
; ++n
) {
1550 obj
= PyIter_Next(iter
);
1552 if (PyErr_Occurred())
1560 /* Pump out MARK, slice[0:n], APPENDS. */
1561 if (self
->write_func(self
, &MARKv
, 1) < 0)
1563 for (i
= 0; i
< n
; ++i
) {
1564 if (save(self
, slice
[i
], 0) < 0)
1567 if (self
->write_func(self
, &appends
, 1) < 0)
1571 if (save(self
, slice
[0], 0) < 0)
1573 if (self
->write_func(self
, &append
, 1) < 0)
1577 for (i
= 0; i
< n
; ++i
) {
1578 Py_DECREF(slice
[i
]);
1580 } while (n
== BATCHSIZE
);
1585 Py_DECREF(slice
[n
]);
1591 save_list(Picklerobject
*self
, PyObject
*args
)
1598 if (self
->fast
&& !fast_save_enter(self
, args
))
1601 /* Create an empty list. */
1612 if (self
->write_func(self
, s
, len
) < 0)
1615 /* Get list length, and bow out early if empty. */
1616 if ((len
= PyList_Size(args
)) < 0)
1621 if (put(self
, args
) >= 0)
1625 if (put2(self
, args
) < 0)
1628 /* Materialize the list elements. */
1629 iter
= PyObject_GetIter(args
);
1633 if (Py_EnterRecursiveCall(" while pickling an object") == 0)
1635 res
= batch_list(self
, iter
);
1636 Py_LeaveRecursiveCall();
1641 if (self
->fast
&& !fast_save_leave(self
, args
))
1648 /* iter is an iterator giving (key, value) pairs, and we batch up chunks of
1649 * MARK key value ... key value SETITEMS
1650 * opcode sequences. Calling code should have arranged to first create an
1651 * empty dict, or dict-like object, for the SETITEMS to operate on.
1652 * Returns 0 on success, <0 on error.
1654 * This is very much like batch_list(). The difference between saving
1655 * elements directly, and picking apart two-tuples, is so long-winded at
1656 * the C level, though, that attempts to combine these routines were too
1660 batch_dict(Picklerobject
*self
, PyObject
*iter
)
1663 PyObject
*slice
[BATCHSIZE
];
1666 static char setitem
= SETITEM
;
1667 static char setitems
= SETITEMS
;
1669 assert(iter
!= NULL
);
1671 if (self
->proto
== 0) {
1672 /* SETITEMS isn't available; do one at a time. */
1674 p
= PyIter_Next(iter
);
1676 if (PyErr_Occurred())
1680 if (!PyTuple_Check(p
) || PyTuple_Size(p
) != 2) {
1681 PyErr_SetString(PyExc_TypeError
, "dict items "
1682 "iterator must return 2-tuples");
1685 i
= save(self
, PyTuple_GET_ITEM(p
, 0), 0);
1687 i
= save(self
, PyTuple_GET_ITEM(p
, 1), 0);
1691 if (self
->write_func(self
, &setitem
, 1) < 0)
1697 /* proto > 0: write in batches of BATCHSIZE. */
1699 /* Get next group of (no more than) BATCHSIZE elements. */
1700 for (n
= 0; n
< BATCHSIZE
; ++n
) {
1701 p
= PyIter_Next(iter
);
1703 if (PyErr_Occurred())
1707 if (!PyTuple_Check(p
) || PyTuple_Size(p
) != 2) {
1708 PyErr_SetString(PyExc_TypeError
, "dict items "
1709 "iterator must return 2-tuples");
1716 /* Pump out MARK, slice[0:n], SETITEMS. */
1717 if (self
->write_func(self
, &MARKv
, 1) < 0)
1719 for (i
= 0; i
< n
; ++i
) {
1721 if (save(self
, PyTuple_GET_ITEM(p
, 0), 0) < 0)
1723 if (save(self
, PyTuple_GET_ITEM(p
, 1), 0) < 0)
1726 if (self
->write_func(self
, &setitems
, 1) < 0)
1731 if (save(self
, PyTuple_GET_ITEM(p
, 0), 0) < 0)
1733 if (save(self
, PyTuple_GET_ITEM(p
, 1), 0) < 0)
1735 if (self
->write_func(self
, &setitem
, 1) < 0)
1739 for (i
= 0; i
< n
; ++i
) {
1740 Py_DECREF(slice
[i
]);
1742 } while (n
== BATCHSIZE
);
1747 Py_DECREF(slice
[n
]);
1753 save_dict(Picklerobject
*self
, PyObject
*args
)
1760 if (self
->fast
&& !fast_save_enter(self
, args
))
1763 /* Create an empty dict. */
1774 if (self
->write_func(self
, s
, len
) < 0)
1777 /* Get dict size, and bow out early if empty. */
1778 if ((len
= PyDict_Size(args
)) < 0)
1782 if (put(self
, args
) >= 0)
1786 if (put2(self
, args
) < 0)
1789 /* Materialize the dict items. */
1790 iter
= PyObject_CallMethod(args
, "iteritems", "()");
1793 if (Py_EnterRecursiveCall(" while pickling an object") == 0)
1795 res
= batch_dict(self
, iter
);
1796 Py_LeaveRecursiveCall();
1801 if (self
->fast
&& !fast_save_leave(self
, args
))
1809 save_inst(Picklerobject
*self
, PyObject
*args
)
1811 PyObject
*class = 0, *module
= 0, *name
= 0, *state
= 0,
1812 *getinitargs_func
= 0, *getstate_func
= 0, *class_args
= 0;
1813 char *module_str
, *name_str
;
1814 int module_size
, name_size
, res
= -1;
1816 static char inst
= INST
, obj
= OBJ
, build
= BUILD
;
1818 if (self
->fast
&& !fast_save_enter(self
, args
))
1821 if (self
->write_func(self
, &MARKv
, 1) < 0)
1824 if (!( class = PyObject_GetAttr(args
, __class___str
)))
1828 if (save(self
, class, 0) < 0)
1832 if ((getinitargs_func
= PyObject_GetAttr(args
, __getinitargs___str
))) {
1833 PyObject
*element
= 0;
1837 PyObject_Call(getinitargs_func
, empty_tuple
, NULL
)))
1840 if ((len
= PyObject_Size(class_args
)) < 0)
1843 for (i
= 0; i
< len
; i
++) {
1844 if (!( element
= PySequence_GetItem(class_args
, i
)))
1847 if (save(self
, element
, 0) < 0) {
1856 if (PyErr_ExceptionMatches(PyExc_AttributeError
))
1863 if (!( name
= ((PyClassObject
*)class)->cl_name
)) {
1864 PyErr_SetString(PicklingError
, "class has no name");
1868 if (!( module
= whichmodule(class, name
)))
1872 if ((module_size
= PyString_Size(module
)) < 0 ||
1873 (name_size
= PyString_Size(name
)) < 0)
1876 module_str
= PyString_AS_STRING((PyStringObject
*)module
);
1877 name_str
= PyString_AS_STRING((PyStringObject
*)name
);
1879 if (self
->write_func(self
, &inst
, 1) < 0)
1882 if (self
->write_func(self
, module_str
, module_size
) < 0)
1885 if (self
->write_func(self
, "\n", 1) < 0)
1888 if (self
->write_func(self
, name_str
, name_size
) < 0)
1891 if (self
->write_func(self
, "\n", 1) < 0)
1894 else if (self
->write_func(self
, &obj
, 1) < 0) {
1898 if ((getstate_func
= PyObject_GetAttr(args
, __getstate___str
))) {
1899 state
= PyObject_Call(getstate_func
, empty_tuple
, NULL
);
1904 if (PyErr_ExceptionMatches(PyExc_AttributeError
))
1909 if (!( state
= PyObject_GetAttr(args
, __dict___str
))) {
1910 if (PyErr_ExceptionMatches(PyExc_AttributeError
))
1919 if (!PyDict_Check(state
)) {
1920 if (put2(self
, args
) < 0)
1924 if (put(self
, args
) < 0)
1928 if (save(self
, state
, 0) < 0)
1931 if (self
->write_func(self
, &build
, 1) < 0)
1937 if (self
->fast
&& !fast_save_leave(self
, args
))
1943 Py_XDECREF(getinitargs_func
);
1944 Py_XDECREF(getstate_func
);
1945 Py_XDECREF(class_args
);
1952 save_global(Picklerobject
*self
, PyObject
*args
, PyObject
*name
)
1954 PyObject
*global_name
= 0, *module
= 0, *mod
= 0, *klass
= 0;
1955 char *name_str
, *module_str
;
1956 int module_size
, name_size
, res
= -1;
1958 static char global
= GLOBAL
;
1962 Py_INCREF(global_name
);
1965 if (!( global_name
= PyObject_GetAttr(args
, __name___str
)))
1969 if (!( module
= whichmodule(args
, global_name
)))
1972 if ((module_size
= PyString_Size(module
)) < 0 ||
1973 (name_size
= PyString_Size(global_name
)) < 0)
1976 module_str
= PyString_AS_STRING((PyStringObject
*)module
);
1977 name_str
= PyString_AS_STRING((PyStringObject
*)global_name
);
1979 /* XXX This can be doing a relative import. Clearly it shouldn't,
1980 but I don't know how to stop it. :-( */
1981 mod
= PyImport_ImportModule(module_str
);
1983 cPickle_ErrFormat(PicklingError
,
1984 "Can't pickle %s: import of module %s "
1986 "OS", args
, module
);
1989 klass
= PyObject_GetAttrString(mod
, name_str
);
1990 if (klass
== NULL
) {
1991 cPickle_ErrFormat(PicklingError
,
1992 "Can't pickle %s: attribute lookup %s.%s "
1994 "OSS", args
, module
, global_name
);
1997 if (klass
!= args
) {
1999 cPickle_ErrFormat(PicklingError
,
2000 "Can't pickle %s: it's not the same object "
2002 "OSS", args
, module
, global_name
);
2007 if (self
->proto
>= 2) {
2008 /* See whether this is in the extension registry, and if
2009 * so generate an EXT opcode.
2011 PyObject
*py_code
; /* extension code as Python object */
2012 long code
; /* extension code as C value */
2016 PyTuple_SET_ITEM(two_tuple
, 0, module
);
2017 PyTuple_SET_ITEM(two_tuple
, 1, global_name
);
2018 py_code
= PyDict_GetItem(extension_registry
, two_tuple
);
2019 if (py_code
== NULL
)
2020 goto gen_global
; /* not registered */
2022 /* Verify py_code has the right type and value. */
2023 if (!PyInt_Check(py_code
)) {
2024 cPickle_ErrFormat(PicklingError
, "Can't pickle %s: "
2025 "extension code %s isn't an integer",
2026 "OO", args
, py_code
);
2029 code
= PyInt_AS_LONG(py_code
);
2030 if (code
<= 0 || code
> 0x7fffffffL
) {
2031 cPickle_ErrFormat(PicklingError
, "Can't pickle %s: "
2032 "extension code %ld is out of range",
2037 /* Generate an EXT opcode. */
2040 c_str
[1] = (char)code
;
2043 else if (code
<= 0xffff) {
2045 c_str
[1] = (char)(code
& 0xff);
2046 c_str
[2] = (char)((code
>> 8) & 0xff);
2051 c_str
[1] = (char)(code
& 0xff);
2052 c_str
[2] = (char)((code
>> 8) & 0xff);
2053 c_str
[3] = (char)((code
>> 16) & 0xff);
2054 c_str
[4] = (char)((code
>> 24) & 0xff);
2058 if (self
->write_func(self
, c_str
, n
) >= 0)
2060 goto finally
; /* and don't memoize */
2064 if (self
->write_func(self
, &global
, 1) < 0)
2067 if (self
->write_func(self
, module_str
, module_size
) < 0)
2070 if (self
->write_func(self
, "\n", 1) < 0)
2073 if (self
->write_func(self
, name_str
, name_size
) < 0)
2076 if (self
->write_func(self
, "\n", 1) < 0)
2079 if (put(self
, args
) < 0)
2086 Py_XDECREF(global_name
);
2093 save_pers(Picklerobject
*self
, PyObject
*args
, PyObject
*f
)
2098 static char persid
= PERSID
, binpersid
= BINPERSID
;
2101 ARG_TUP(self
, args
);
2103 pid
= PyObject_Call(f
, self
->arg
, NULL
);
2106 if (! pid
) return -1;
2108 if (pid
!= Py_None
) {
2110 if (!PyString_Check(pid
)) {
2111 PyErr_SetString(PicklingError
,
2112 "persistent id must be string");
2116 if (self
->write_func(self
, &persid
, 1) < 0)
2119 if ((size
= PyString_Size(pid
)) < 0)
2122 if (self
->write_func(self
,
2124 (PyStringObject
*)pid
),
2128 if (self
->write_func(self
, "\n", 1) < 0)
2134 else if (save(self
, pid
, 1) >= 0) {
2135 if (self
->write_func(self
, &binpersid
, 1) < 0)
2152 /* We're saving ob, and args is the 2-thru-5 tuple returned by the
2153 * appropriate __reduce__ method for ob.
2156 save_reduce(Picklerobject
*self
, PyObject
*args
, PyObject
*ob
)
2160 PyObject
*state
= NULL
;
2161 PyObject
*listitems
= NULL
;
2162 PyObject
*dictitems
= NULL
;
2164 int use_newobj
= self
->proto
>= 2;
2166 static char reduce
= REDUCE
;
2167 static char build
= BUILD
;
2168 static char newobj
= NEWOBJ
;
2170 if (! PyArg_UnpackTuple(args
, "save_reduce", 2, 5,
2178 if (!PyTuple_Check(argtup
)) {
2179 PyErr_SetString(PicklingError
,
2180 "args from reduce() should be a tuple");
2184 if (state
== Py_None
)
2186 if (listitems
== Py_None
)
2188 if (dictitems
== Py_None
)
2191 /* Protocol 2 special case: if callable's name is __newobj__, use
2192 * NEWOBJ. This consumes a lot of code.
2195 PyObject
*temp
= PyObject_GetAttr(callable
, __name___str
);
2198 if (PyErr_ExceptionMatches(PyExc_AttributeError
))
2205 use_newobj
= PyString_Check(temp
) &&
2206 strcmp(PyString_AS_STRING(temp
),
2213 PyObject
*newargtup
;
2216 /* Sanity checks. */
2217 n
= PyTuple_Size(argtup
);
2219 PyErr_SetString(PicklingError
, "__newobj__ arglist "
2224 cls
= PyTuple_GET_ITEM(argtup
, 0);
2225 if (! PyObject_HasAttrString(cls
, "__new__")) {
2226 PyErr_SetString(PicklingError
, "args[0] from "
2227 "__newobj__ args has no __new__");
2231 /* XXX How could ob be NULL? */
2233 PyObject
*ob_dot_class
;
2235 ob_dot_class
= PyObject_GetAttr(ob
, __class___str
);
2236 if (ob_dot_class
== NULL
) {
2237 if (PyErr_ExceptionMatches(
2238 PyExc_AttributeError
))
2243 i
= ob_dot_class
!= cls
; /* true iff a problem */
2244 Py_XDECREF(ob_dot_class
);
2246 PyErr_SetString(PicklingError
, "args[0] from "
2247 "__newobj__ args has the wrong class");
2252 /* Save the class and its __new__ arguments. */
2253 if (save(self
, cls
, 0) < 0)
2256 newargtup
= PyTuple_New(n
-1); /* argtup[1:] */
2257 if (newargtup
== NULL
)
2259 for (i
= 1; i
< n
; ++i
) {
2260 PyObject
*temp
= PyTuple_GET_ITEM(argtup
, i
);
2262 PyTuple_SET_ITEM(newargtup
, i
-1, temp
);
2264 i
= save(self
, newargtup
, 0);
2265 Py_DECREF(newargtup
);
2269 /* Add NEWOBJ opcode. */
2270 if (self
->write_func(self
, &newobj
, 1) < 0)
2274 /* Not using NEWOBJ. */
2275 if (save(self
, callable
, 0) < 0 ||
2276 save(self
, argtup
, 0) < 0 ||
2277 self
->write_func(self
, &reduce
, 1) < 0)
2282 /* XXX How can ob be NULL? */
2284 if (state
&& !PyDict_Check(state
)) {
2285 if (put2(self
, ob
) < 0)
2288 else if (put(self
, ob
) < 0)
2293 if (listitems
&& batch_list(self
, listitems
) < 0)
2296 if (dictitems
&& batch_dict(self
, dictitems
) < 0)
2300 if (save(self
, state
, 0) < 0 ||
2301 self
->write_func(self
, &build
, 1) < 0)
2309 save(Picklerobject
*self
, PyObject
*args
, int pers_save
)
2312 PyObject
*py_ob_id
= 0, *__reduce__
= 0, *t
= 0;
2317 if (Py_EnterRecursiveCall(" while pickling an object"))
2320 if (!pers_save
&& self
->pers_func
) {
2321 if ((tmp
= save_pers(self
, args
, self
->pers_func
)) != 0) {
2327 if (args
== Py_None
) {
2328 res
= save_none(self
, args
);
2332 type
= Py_TYPE(args
);
2334 switch (type
->tp_name
[0]) {
2336 if (args
== Py_False
|| args
== Py_True
) {
2337 res
= save_bool(self
, args
);
2342 if (type
== &PyInt_Type
) {
2343 res
= save_int(self
, args
);
2349 if (type
== &PyLong_Type
) {
2350 res
= save_long(self
, args
);
2356 if (type
== &PyFloat_Type
) {
2357 res
= save_float(self
, args
);
2363 if (type
== &PyTuple_Type
&& PyTuple_Size(args
) == 0) {
2364 res
= save_tuple(self
, args
);
2370 if ((type
== &PyString_Type
) && (PyString_GET_SIZE(args
) < 2)) {
2371 res
= save_string(self
, args
, 0);
2376 #ifdef Py_USING_UNICODE
2378 if ((type
== &PyUnicode_Type
) && (PyString_GET_SIZE(args
) < 2)) {
2379 res
= save_unicode(self
, args
, 0);
2386 if (Py_REFCNT(args
) > 1) {
2387 if (!( py_ob_id
= PyLong_FromVoidPtr(args
)))
2390 if (PyDict_GetItem(self
->memo
, py_ob_id
)) {
2391 if (get(self
, py_ob_id
) < 0)
2399 switch (type
->tp_name
[0]) {
2401 if (type
== &PyString_Type
) {
2402 res
= save_string(self
, args
, 1);
2407 #ifdef Py_USING_UNICODE
2409 if (type
== &PyUnicode_Type
) {
2410 res
= save_unicode(self
, args
, 1);
2417 if (type
== &PyTuple_Type
) {
2418 res
= save_tuple(self
, args
);
2421 if (type
== &PyType_Type
) {
2422 res
= save_global(self
, args
, NULL
);
2428 if (type
== &PyList_Type
) {
2429 res
= save_list(self
, args
);
2435 if (type
== &PyDict_Type
) {
2436 res
= save_dict(self
, args
);
2442 if (type
== &PyInstance_Type
) {
2443 res
= save_inst(self
, args
);
2449 if (type
== &PyClass_Type
) {
2450 res
= save_global(self
, args
, NULL
);
2456 if (type
== &PyFunction_Type
) {
2457 res
= save_global(self
, args
, NULL
);
2458 if (res
&& PyErr_ExceptionMatches(PickleError
)) {
2459 /* fall back to reduce */
2468 if (type
== &PyCFunction_Type
) {
2469 res
= save_global(self
, args
, NULL
);
2474 if (!pers_save
&& self
->inst_pers_func
) {
2475 if ((tmp
= save_pers(self
, args
, self
->inst_pers_func
)) != 0) {
2481 if (PyType_IsSubtype(type
, &PyType_Type
)) {
2482 res
= save_global(self
, args
, NULL
);
2486 /* Get a reduction callable, and call it. This may come from
2487 * copy_reg.dispatch_table, the object's __reduce_ex__ method,
2488 * or the object's __reduce__ method.
2490 __reduce__
= PyDict_GetItem(dispatch_table
, (PyObject
*)type
);
2491 if (__reduce__
!= NULL
) {
2492 Py_INCREF(__reduce__
);
2494 ARG_TUP(self
, args
);
2496 t
= PyObject_Call(__reduce__
, self
->arg
, NULL
);
2501 /* Check for a __reduce_ex__ method. */
2502 __reduce__
= PyObject_GetAttr(args
, __reduce_ex___str
);
2503 if (__reduce__
!= NULL
) {
2504 t
= PyInt_FromLong(self
->proto
);
2509 t
= PyObject_Call(__reduce__
,
2516 if (PyErr_ExceptionMatches(PyExc_AttributeError
))
2520 /* Check for a __reduce__ method. */
2521 __reduce__
= PyObject_GetAttr(args
, __reduce___str
);
2522 if (__reduce__
!= NULL
) {
2523 t
= PyObject_Call(__reduce__
,
2527 PyErr_SetObject(UnpickleableError
, args
);
2536 if (PyString_Check(t
)) {
2537 res
= save_global(self
, args
, t
);
2541 if (! PyTuple_Check(t
)) {
2542 cPickle_ErrFormat(PicklingError
, "Value returned by "
2543 "%s must be string or tuple",
2548 size
= PyTuple_Size(t
);
2549 if (size
< 2 || size
> 5) {
2550 cPickle_ErrFormat(PicklingError
, "tuple returned by "
2551 "%s must contain 2 through 5 elements",
2556 arg_tup
= PyTuple_GET_ITEM(t
, 1);
2557 if (!(PyTuple_Check(arg_tup
) || arg_tup
== Py_None
)) {
2558 cPickle_ErrFormat(PicklingError
, "Second element of "
2559 "tuple returned by %s must be a tuple",
2564 res
= save_reduce(self
, t
, args
);
2567 Py_LeaveRecursiveCall();
2568 Py_XDECREF(py_ob_id
);
2569 Py_XDECREF(__reduce__
);
2577 dump(Picklerobject
*self
, PyObject
*args
)
2579 static char stop
= STOP
;
2581 if (self
->proto
>= 2) {
2585 assert(self
->proto
>= 0 && self
->proto
< 256);
2586 bytes
[1] = (char)self
->proto
;
2587 if (self
->write_func(self
, bytes
, 2) < 0)
2591 if (save(self
, args
, 0) < 0)
2594 if (self
->write_func(self
, &stop
, 1) < 0)
2597 if (self
->write_func(self
, NULL
, 0) < 0)
2604 Pickle_clear_memo(Picklerobject
*self
, PyObject
*args
)
2607 PyDict_Clear(self
->memo
);
2613 Pickle_getvalue(Picklerobject
*self
, PyObject
*args
)
2615 int l
, i
, rsize
, ssize
, clear
=1, lm
;
2618 char *s
, *p
, *have_get
;
2621 /* Can be called by Python code or C code */
2622 if (args
&& !PyArg_ParseTuple(args
, "|i:getvalue", &clear
))
2625 /* Check to make sure we are based on a list */
2626 if (! Pdata_Check(self
->file
)) {
2627 PyErr_SetString(PicklingError
,
2628 "Attempt to getvalue() a non-list-based pickler");
2632 /* flush write buffer */
2633 if (write_other(self
, NULL
, 0) < 0) return NULL
;
2635 data
=(Pdata
*)self
->file
;
2638 /* set up an array to hold get/put status */
2639 lm
= PyDict_Size(self
->memo
);
2640 if (lm
< 0) return NULL
;
2642 have_get
= malloc(lm
);
2643 if (have_get
== NULL
) return PyErr_NoMemory();
2644 memset(have_get
, 0, lm
);
2646 /* Scan for gets. */
2647 for (rsize
= 0, i
= l
; --i
>= 0; ) {
2650 if (PyString_Check(k
))
2651 rsize
+= PyString_GET_SIZE(k
);
2653 else if (PyInt_Check(k
)) { /* put */
2654 ik
= PyInt_AS_LONG((PyIntObject
*)k
);
2655 if (ik
>= lm
|| ik
== 0) {
2656 PyErr_SetString(PicklingError
,
2657 "Invalid get data");
2660 if (have_get
[ik
]) /* with matching get */
2661 rsize
+= ik
< 256 ? 2 : 5;
2664 else if (! (PyTuple_Check(k
) &&
2665 PyTuple_GET_SIZE(k
) == 2 &&
2666 PyInt_Check((k
= PyTuple_GET_ITEM(k
, 0))))
2668 PyErr_SetString(PicklingError
,
2669 "Unexpected data in internal list");
2674 ik
= PyInt_AS_LONG((PyIntObject
*)k
);
2675 if (ik
>= lm
|| ik
== 0) {
2676 PyErr_SetString(PicklingError
,
2677 "Invalid get data");
2681 rsize
+= ik
< 256 ? 2 : 5;
2685 /* Now generate the result */
2686 r
= PyString_FromStringAndSize(NULL
, rsize
);
2687 if (r
== NULL
) goto err
;
2688 s
= PyString_AS_STRING((PyStringObject
*)r
);
2690 for (i
= 0; i
< l
; i
++) {
2693 if (PyString_Check(k
)) {
2694 ssize
= PyString_GET_SIZE(k
);
2696 p
=PyString_AS_STRING((PyStringObject
*)k
);
2697 while (--ssize
>= 0)
2702 else if (PyTuple_Check(k
)) { /* get */
2703 ik
= PyInt_AS_LONG((PyIntObject
*)
2704 PyTuple_GET_ITEM(k
, 0));
2707 *s
++ = (int)(ik
& 0xff);
2711 *s
++ = (int)(ik
& 0xff);
2712 *s
++ = (int)((ik
>> 8) & 0xff);
2713 *s
++ = (int)((ik
>> 16) & 0xff);
2714 *s
++ = (int)((ik
>> 24) & 0xff);
2719 ik
= PyInt_AS_LONG((PyIntObject
*)k
);
2721 if (have_get
[ik
]) { /* with matching get */
2724 *s
++ = (int)(ik
& 0xff);
2728 *s
++ = (int)(ik
& 0xff);
2729 *s
++ = (int)((ik
>> 8) & 0xff);
2730 *s
++ = (int)((ik
>> 16) & 0xff);
2731 *s
++ = (int)((ik
>> 24) & 0xff);
2738 PyDict_Clear(self
->memo
);
2739 Pdata_clear(data
, 0);
2750 Pickler_dump(Picklerobject
*self
, PyObject
*args
)
2755 if (!( PyArg_ParseTuple(args
, "O|i:dump", &ob
, &get
)))
2758 if (dump(self
, ob
) < 0)
2761 if (get
) return Pickle_getvalue(self
, NULL
);
2763 /* XXX Why does dump() return self? */
2765 return (PyObject
*)self
;
2769 static struct PyMethodDef Pickler_methods
[] =
2771 {"dump", (PyCFunction
)Pickler_dump
, METH_VARARGS
,
2772 PyDoc_STR("dump(object) -- "
2773 "Write an object in pickle format to the object's pickle stream")},
2774 {"clear_memo", (PyCFunction
)Pickle_clear_memo
, METH_NOARGS
,
2775 PyDoc_STR("clear_memo() -- Clear the picklers memo")},
2776 {"getvalue", (PyCFunction
)Pickle_getvalue
, METH_VARARGS
,
2777 PyDoc_STR("getvalue() -- Finish picking a list-based pickle")},
2778 {NULL
, NULL
} /* sentinel */
2782 static Picklerobject
*
2783 newPicklerobject(PyObject
*file
, int proto
)
2785 Picklerobject
*self
;
2788 proto
= HIGHEST_PROTOCOL
;
2789 if (proto
> HIGHEST_PROTOCOL
) {
2790 PyErr_Format(PyExc_ValueError
, "pickle protocol %d asked for; "
2791 "the highest available protocol is %d",
2792 proto
, HIGHEST_PROTOCOL
);
2796 self
= PyObject_GC_New(Picklerobject
, &Picklertype
);
2799 self
->proto
= proto
;
2800 self
->bin
= proto
> 0;
2805 self
->pers_func
= NULL
;
2806 self
->inst_pers_func
= NULL
;
2807 self
->write_buf
= NULL
;
2809 self
->fast_container
= 0;
2810 self
->fast_memo
= NULL
;
2812 self
->dispatch_table
= NULL
;
2824 if (!( self
->memo
= PyDict_New()))
2827 if (PyFile_Check(file
)) {
2828 self
->fp
= PyFile_AsFile(file
);
2829 if (self
->fp
== NULL
) {
2830 PyErr_SetString(PyExc_ValueError
,
2831 "I/O operation on closed file");
2834 self
->write_func
= write_file
;
2836 else if (PycStringIO_OutputCheck(file
)) {
2837 self
->write_func
= write_cStringIO
;
2839 else if (file
== Py_None
) {
2840 self
->write_func
= write_none
;
2843 self
->write_func
= write_other
;
2845 if (! Pdata_Check(file
)) {
2846 self
->write
= PyObject_GetAttr(file
, write_str
);
2849 PyErr_SetString(PyExc_TypeError
,
2850 "argument must have 'write' "
2856 self
->write_buf
= (char *)PyMem_Malloc(WRITE_BUF_SIZE
);
2857 if (self
->write_buf
== NULL
) {
2863 if (PyEval_GetRestricted()) {
2864 /* Restricted execution, get private tables */
2865 PyObject
*m
= PyImport_Import(copyreg_str
);
2869 self
->dispatch_table
= PyObject_GetAttr(m
, dispatch_table_str
);
2871 if (self
->dispatch_table
== NULL
)
2875 self
->dispatch_table
= dispatch_table
;
2876 Py_INCREF(dispatch_table
);
2878 PyObject_GC_Track(self
);
2889 get_Pickler(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
2891 static char *kwlist
[] = {"file", "protocol", NULL
};
2892 PyObject
*file
= NULL
;
2896 * The documented signature is Pickler(file, protocol=0), but this
2897 * accepts Pickler() and Pickler(integer) too. The meaning then
2898 * is clear as mud, undocumented, and not supported by pickle.py.
2899 * I'm told Zope uses this, but I haven't traced into this code
2900 * far enough to figure out what it means.
2902 if (!PyArg_ParseTuple(args
, "|i:Pickler", &proto
)) {
2905 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "O|i:Pickler",
2906 kwlist
, &file
, &proto
))
2909 return (PyObject
*)newPicklerobject(file
, proto
);
2914 Pickler_dealloc(Picklerobject
*self
)
2916 PyObject_GC_UnTrack(self
);
2917 Py_XDECREF(self
->write
);
2918 Py_XDECREF(self
->memo
);
2919 Py_XDECREF(self
->fast_memo
);
2920 Py_XDECREF(self
->arg
);
2921 Py_XDECREF(self
->file
);
2922 Py_XDECREF(self
->pers_func
);
2923 Py_XDECREF(self
->inst_pers_func
);
2924 Py_XDECREF(self
->dispatch_table
);
2925 PyMem_Free(self
->write_buf
);
2926 Py_TYPE(self
)->tp_free((PyObject
*)self
);
2930 Pickler_traverse(Picklerobject
*self
, visitproc visit
, void *arg
)
2932 Py_VISIT(self
->write
);
2933 Py_VISIT(self
->memo
);
2934 Py_VISIT(self
->fast_memo
);
2935 Py_VISIT(self
->arg
);
2936 Py_VISIT(self
->file
);
2937 Py_VISIT(self
->pers_func
);
2938 Py_VISIT(self
->inst_pers_func
);
2939 Py_VISIT(self
->dispatch_table
);
2944 Pickler_clear(Picklerobject
*self
)
2946 Py_CLEAR(self
->write
);
2947 Py_CLEAR(self
->memo
);
2948 Py_CLEAR(self
->fast_memo
);
2949 Py_CLEAR(self
->arg
);
2950 Py_CLEAR(self
->file
);
2951 Py_CLEAR(self
->pers_func
);
2952 Py_CLEAR(self
->inst_pers_func
);
2953 Py_CLEAR(self
->dispatch_table
);
2958 Pickler_get_pers_func(Picklerobject
*p
)
2960 if (p
->pers_func
== NULL
)
2961 PyErr_SetString(PyExc_AttributeError
, "persistent_id");
2963 Py_INCREF(p
->pers_func
);
2964 return p
->pers_func
;
2968 Pickler_set_pers_func(Picklerobject
*p
, PyObject
*v
)
2971 PyErr_SetString(PyExc_TypeError
,
2972 "attribute deletion is not supported");
2975 Py_XDECREF(p
->pers_func
);
2982 Pickler_set_inst_pers_func(Picklerobject
*p
, PyObject
*v
)
2985 PyErr_SetString(PyExc_TypeError
,
2986 "attribute deletion is not supported");
2989 Py_XDECREF(p
->inst_pers_func
);
2991 p
->inst_pers_func
= v
;
2996 Pickler_get_memo(Picklerobject
*p
)
2998 if (p
->memo
== NULL
)
2999 PyErr_SetString(PyExc_AttributeError
, "memo");
3006 Pickler_set_memo(Picklerobject
*p
, PyObject
*v
)
3009 PyErr_SetString(PyExc_TypeError
,
3010 "attribute deletion is not supported");
3013 if (!PyDict_Check(v
)) {
3014 PyErr_SetString(PyExc_TypeError
, "memo must be a dictionary");
3017 Py_XDECREF(p
->memo
);
3024 Pickler_get_error(Picklerobject
*p
)
3026 /* why is this an attribute on the Pickler? */
3027 Py_INCREF(PicklingError
);
3028 return PicklingError
;
3031 static PyMemberDef Pickler_members
[] = {
3032 {"binary", T_INT
, offsetof(Picklerobject
, bin
)},
3033 {"fast", T_INT
, offsetof(Picklerobject
, fast
)},
3037 static PyGetSetDef Pickler_getsets
[] = {
3038 {"persistent_id", (getter
)Pickler_get_pers_func
,
3039 (setter
)Pickler_set_pers_func
},
3040 {"inst_persistent_id", NULL
, (setter
)Pickler_set_inst_pers_func
},
3041 {"memo", (getter
)Pickler_get_memo
, (setter
)Pickler_set_memo
},
3042 {"PicklingError", (getter
)Pickler_get_error
, NULL
},
3046 PyDoc_STRVAR(Picklertype__doc__
,
3047 "Objects that know how to pickle objects\n");
3049 static PyTypeObject Picklertype
= {
3050 PyVarObject_HEAD_INIT(NULL
, 0)
3051 "cPickle.Pickler", /*tp_name*/
3052 sizeof(Picklerobject
), /*tp_basicsize*/
3054 (destructor
)Pickler_dealloc
, /* tp_dealloc */
3060 0, /* tp_as_number */
3061 0, /* tp_as_sequence */
3062 0, /* tp_as_mapping */
3066 PyObject_GenericGetAttr
, /* tp_getattro */
3067 PyObject_GenericSetAttr
, /* tp_setattro */
3068 0, /* tp_as_buffer */
3069 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
| Py_TPFLAGS_HAVE_GC
,
3070 Picklertype__doc__
, /* tp_doc */
3071 (traverseproc
)Pickler_traverse
, /* tp_traverse */
3072 (inquiry
)Pickler_clear
, /* tp_clear */
3073 0, /* tp_richcompare */
3074 0, /* tp_weaklistoffset */
3076 0, /* tp_iternext */
3077 Pickler_methods
, /* tp_methods */
3078 Pickler_members
, /* tp_members */
3079 Pickler_getsets
, /* tp_getset */
3083 find_class(PyObject
*py_module_name
, PyObject
*py_global_name
, PyObject
*fc
)
3085 PyObject
*global
= 0, *module
;
3089 PyErr_SetString(UnpicklingError
, "Global and instance "
3090 "pickles are not supported.");
3093 return PyObject_CallFunctionObjArgs(fc
, py_module_name
,
3094 py_global_name
, NULL
);
3097 module
= PySys_GetObject("modules");
3101 module
= PyDict_GetItem(module
, py_module_name
);
3102 if (module
== NULL
) {
3103 module
= PyImport_Import(py_module_name
);
3106 global
= PyObject_GetAttr(module
, py_global_name
);
3110 global
= PyObject_GetAttr(module
, py_global_name
);
3115 marker(Unpicklerobject
*self
)
3117 if (self
->num_marks
< 1) {
3118 PyErr_SetString(UnpicklingError
, "could not find MARK");
3122 return self
->marks
[--self
->num_marks
];
3127 load_none(Unpicklerobject
*self
)
3129 PDATA_APPEND(self
->stack
, Py_None
, -1);
3136 PyErr_SetString(UnpicklingError
, "pickle data was truncated");
3141 load_int(Unpicklerobject
*self
)
3143 PyObject
*py_int
= 0;
3148 if ((len
= self
->readline_func(self
, &s
)) < 0) return -1;
3149 if (len
< 2) return bad_readline();
3150 if (!( s
=pystrndup(s
,len
))) return -1;
3153 l
= strtol(s
, &endptr
, 0);
3155 if (errno
|| (*endptr
!= '\n') || (endptr
[1] != '\0')) {
3156 /* Hm, maybe we've got something long. Let's try reading
3157 it as a Python long object. */
3159 py_int
= PyLong_FromString(s
, NULL
, 0);
3160 if (py_int
== NULL
) {
3161 PyErr_SetString(PyExc_ValueError
,
3162 "could not convert string to int");
3167 if (len
== 3 && (l
== 0 || l
== 1)) {
3168 if (!( py_int
= PyBool_FromLong(l
))) goto finally
;
3171 if (!( py_int
= PyInt_FromLong(l
))) goto finally
;
3176 PDATA_PUSH(self
->stack
, py_int
, -1);
3186 load_bool(Unpicklerobject
*self
, PyObject
*boolean
)
3188 assert(boolean
== Py_True
|| boolean
== Py_False
);
3189 PDATA_APPEND(self
->stack
, boolean
, -1);
3193 /* s contains x bytes of a little-endian integer. Return its value as a
3194 * C int. Obscure: when x is 1 or 2, this is an unsigned little-endian
3195 * int, but when x is 4 it's a signed one. This is an historical source
3196 * of x-platform bugs.
3199 calc_binint(char *s
, int x
)
3205 for (i
= 0, l
= 0L; i
< x
; i
++) {
3206 c
= (unsigned char)s
[i
];
3207 l
|= (long)c
<< (i
* 8);
3210 /* Unlike BININT1 and BININT2, BININT (more accurately BININT4)
3211 * is signed, so on a box with longs bigger than 4 bytes we need
3212 * to extend a BININT's sign bit to the full width.
3214 if (x
== 4 && l
& (1L << 31))
3222 load_binintx(Unpicklerobject
*self
, char *s
, int x
)
3224 PyObject
*py_int
= 0;
3227 l
= calc_binint(s
, x
);
3229 if (!( py_int
= PyInt_FromLong(l
)))
3232 PDATA_PUSH(self
->stack
, py_int
, -1);
3238 load_binint(Unpicklerobject
*self
)
3242 if (self
->read_func(self
, &s
, 4) < 0)
3245 return load_binintx(self
, s
, 4);
3250 load_binint1(Unpicklerobject
*self
)
3254 if (self
->read_func(self
, &s
, 1) < 0)
3257 return load_binintx(self
, s
, 1);
3262 load_binint2(Unpicklerobject
*self
)
3266 if (self
->read_func(self
, &s
, 2) < 0)
3269 return load_binintx(self
, s
, 2);
3273 load_long(Unpicklerobject
*self
)
3279 if ((len
= self
->readline_func(self
, &s
)) < 0) return -1;
3280 if (len
< 2) return bad_readline();
3281 if (!( s
=pystrndup(s
,len
))) return -1;
3283 if (!( l
= PyLong_FromString(s
, &end
, 0)))
3287 PDATA_PUSH(self
->stack
, l
, -1);
3296 /* 'size' bytes contain the # of bytes of little-endian 256's-complement
3300 load_counted_long(Unpicklerobject
*self
, int size
)
3304 unsigned char *pdata
;
3307 assert(size
== 1 || size
== 4);
3308 i
= self
->read_func(self
, &nbytes
, size
);
3309 if (i
< 0) return -1;
3311 size
= calc_binint(nbytes
, size
);
3313 /* Corrupt or hostile pickle -- we never write one like
3316 PyErr_SetString(UnpicklingError
, "LONG pickle has negative "
3322 along
= PyLong_FromLong(0L);
3324 /* Read the raw little-endian bytes & convert. */
3325 i
= self
->read_func(self
, (char **)&pdata
, size
);
3326 if (i
< 0) return -1;
3327 along
= _PyLong_FromByteArray(pdata
, (size_t)size
,
3328 1 /* little endian */, 1 /* signed */);
3332 PDATA_PUSH(self
->stack
, along
, -1);
3337 load_float(Unpicklerobject
*self
)
3339 PyObject
*py_float
= 0;
3344 if ((len
= self
->readline_func(self
, &s
)) < 0) return -1;
3345 if (len
< 2) return bad_readline();
3346 if (!( s
=pystrndup(s
,len
))) return -1;
3349 d
= PyOS_ascii_strtod(s
, &endptr
);
3351 if (errno
|| (endptr
[0] != '\n') || (endptr
[1] != '\0')) {
3352 PyErr_SetString(PyExc_ValueError
,
3353 "could not convert string to float");
3357 if (!( py_float
= PyFloat_FromDouble(d
)))
3361 PDATA_PUSH(self
->stack
, py_float
, -1);
3371 load_binfloat(Unpicklerobject
*self
)
3377 if (self
->read_func(self
, &p
, 8) < 0)
3380 x
= _PyFloat_Unpack8((unsigned char *)p
, 0);
3381 if (x
== -1.0 && PyErr_Occurred())
3384 py_float
= PyFloat_FromDouble(x
);
3385 if (py_float
== NULL
)
3388 PDATA_PUSH(self
->stack
, py_float
, -1);
3393 load_string(Unpicklerobject
*self
)
3399 if ((len
= self
->readline_func(self
, &s
)) < 0) return -1;
3400 if (len
< 2) return bad_readline();
3401 if (!( s
=pystrndup(s
,len
))) return -1;
3404 /* Strip outermost quotes */
3405 while (s
[len
-1] <= ' ')
3407 if(s
[0]=='"' && s
[len
-1]=='"'){
3411 } else if(s
[0]=='\'' && s
[len
-1]=='\''){
3417 /********************************************/
3419 str
= PyString_DecodeEscape(p
, len
, NULL
, 0, NULL
);
3422 PDATA_PUSH(self
->stack
, str
, -1);
3429 PyErr_SetString(PyExc_ValueError
,"insecure string pickle");
3435 load_binstring(Unpicklerobject
*self
)
3437 PyObject
*py_string
= 0;
3441 if (self
->read_func(self
, &s
, 4) < 0) return -1;
3443 l
= calc_binint(s
, 4);
3445 /* Corrupt or hostile pickle -- we never write one like
3448 PyErr_SetString(UnpicklingError
,
3449 "BINSTRING pickle has negative byte count");
3453 if (self
->read_func(self
, &s
, l
) < 0)
3456 if (!( py_string
= PyString_FromStringAndSize(s
, l
)))
3459 PDATA_PUSH(self
->stack
, py_string
, -1);
3465 load_short_binstring(Unpicklerobject
*self
)
3467 PyObject
*py_string
= 0;
3471 if (self
->read_func(self
, &s
, 1) < 0)
3474 l
= (unsigned char)s
[0];
3476 if (self
->read_func(self
, &s
, l
) < 0) return -1;
3478 if (!( py_string
= PyString_FromStringAndSize(s
, l
))) return -1;
3480 PDATA_PUSH(self
->stack
, py_string
, -1);
3485 #ifdef Py_USING_UNICODE
3487 load_unicode(Unpicklerobject
*self
)
3493 if ((len
= self
->readline_func(self
, &s
)) < 0) return -1;
3494 if (len
< 1) return bad_readline();
3496 if (!( str
= PyUnicode_DecodeRawUnicodeEscape(s
, len
- 1, NULL
)))
3499 PDATA_PUSH(self
->stack
, str
, -1);
3508 #ifdef Py_USING_UNICODE
3510 load_binunicode(Unpicklerobject
*self
)
3516 if (self
->read_func(self
, &s
, 4) < 0) return -1;
3518 l
= calc_binint(s
, 4);
3520 /* Corrupt or hostile pickle -- we never write one like
3523 PyErr_SetString(UnpicklingError
,
3524 "BINUNICODE pickle has negative byte count");
3528 if (self
->read_func(self
, &s
, l
) < 0)
3531 if (!( unicode
= PyUnicode_DecodeUTF8(s
, l
, NULL
)))
3534 PDATA_PUSH(self
->stack
, unicode
, -1);
3541 load_tuple(Unpicklerobject
*self
)
3546 if ((i
= marker(self
)) < 0) return -1;
3547 if (!( tup
=Pdata_popTuple(self
->stack
, i
))) return -1;
3548 PDATA_PUSH(self
->stack
, tup
, -1);
3553 load_counted_tuple(Unpicklerobject
*self
, int len
)
3555 PyObject
*tup
= PyTuple_New(len
);
3560 while (--len
>= 0) {
3563 PDATA_POP(self
->stack
, element
);
3564 if (element
== NULL
)
3566 PyTuple_SET_ITEM(tup
, len
, element
);
3568 PDATA_PUSH(self
->stack
, tup
, -1);
3573 load_empty_list(Unpicklerobject
*self
)
3577 if (!( list
=PyList_New(0))) return -1;
3578 PDATA_PUSH(self
->stack
, list
, -1);
3583 load_empty_dict(Unpicklerobject
*self
)
3587 if (!( dict
=PyDict_New())) return -1;
3588 PDATA_PUSH(self
->stack
, dict
, -1);
3594 load_list(Unpicklerobject
*self
)
3599 if ((i
= marker(self
)) < 0) return -1;
3600 if (!( list
=Pdata_popList(self
->stack
, i
))) return -1;
3601 PDATA_PUSH(self
->stack
, list
, -1);
3606 load_dict(Unpicklerobject
*self
)
3608 PyObject
*dict
, *key
, *value
;
3611 if ((i
= marker(self
)) < 0) return -1;
3612 j
=self
->stack
->length
;
3614 if (!( dict
= PyDict_New())) return -1;
3616 for (k
= i
+1; k
< j
; k
+= 2) {
3617 key
=self
->stack
->data
[k
-1];
3618 value
=self
->stack
->data
[k
];
3619 if (PyDict_SetItem(dict
, key
, value
) < 0) {
3624 Pdata_clear(self
->stack
, i
);
3625 PDATA_PUSH(self
->stack
, dict
, -1);
3630 Instance_New(PyObject
*cls
, PyObject
*args
)
3634 if (PyClass_Check(cls
)) {
3637 if ((l
=PyObject_Size(args
)) < 0) goto err
;
3639 PyObject
*__getinitargs__
;
3641 __getinitargs__
= PyObject_GetAttr(cls
,
3642 __getinitargs___str
);
3643 if (!__getinitargs__
) {
3644 /* We have a class with no __getinitargs__,
3645 so bypass usual construction */
3649 if (!( inst
=PyInstance_NewRaw(cls
, NULL
)))
3653 Py_DECREF(__getinitargs__
);
3656 if ((r
=PyInstance_New(cls
, args
, NULL
))) return r
;
3660 if ((r
=PyObject_CallObject(cls
, args
))) return r
;
3664 PyObject
*tp
, *v
, *tb
, *tmp_value
;
3666 PyErr_Fetch(&tp
, &v
, &tb
);
3668 /* NULL occurs when there was a KeyboardInterrupt */
3669 if (tmp_value
== NULL
)
3670 tmp_value
= Py_None
;
3671 if ((r
= PyTuple_Pack(3, tmp_value
, cls
, args
))) {
3675 PyErr_Restore(tp
,v
,tb
);
3682 load_obj(Unpicklerobject
*self
)
3684 PyObject
*class, *tup
, *obj
=0;
3687 if ((i
= marker(self
)) < 0) return -1;
3688 if (!( tup
=Pdata_popTuple(self
->stack
, i
+1))) return -1;
3689 PDATA_POP(self
->stack
, class);
3691 obj
= Instance_New(class, tup
);
3696 if (! obj
) return -1;
3697 PDATA_PUSH(self
->stack
, obj
, -1);
3703 load_inst(Unpicklerobject
*self
)
3705 PyObject
*tup
, *class=0, *obj
=0, *module_name
, *class_name
;
3709 if ((i
= marker(self
)) < 0) return -1;
3711 if ((len
= self
->readline_func(self
, &s
)) < 0) return -1;
3712 if (len
< 2) return bad_readline();
3713 module_name
= PyString_FromStringAndSize(s
, len
- 1);
3714 if (!module_name
) return -1;
3716 if ((len
= self
->readline_func(self
, &s
)) >= 0) {
3717 if (len
< 2) return bad_readline();
3718 if ((class_name
= PyString_FromStringAndSize(s
, len
- 1))) {
3719 class = find_class(module_name
, class_name
,
3721 Py_DECREF(class_name
);
3724 Py_DECREF(module_name
);
3726 if (! class) return -1;
3728 if ((tup
=Pdata_popTuple(self
->stack
, i
))) {
3729 obj
= Instance_New(class, tup
);
3734 if (! obj
) return -1;
3736 PDATA_PUSH(self
->stack
, obj
, -1);
3741 load_newobj(Unpicklerobject
*self
)
3743 PyObject
*args
= NULL
;
3744 PyObject
*clsraw
= NULL
;
3745 PyTypeObject
*cls
; /* clsraw cast to its true type */
3748 /* Stack is ... cls argtuple, and we want to call
3749 * cls.__new__(cls, *argtuple).
3751 PDATA_POP(self
->stack
, args
);
3752 if (args
== NULL
) goto Fail
;
3753 if (! PyTuple_Check(args
)) {
3754 PyErr_SetString(UnpicklingError
, "NEWOBJ expected an arg "
3759 PDATA_POP(self
->stack
, clsraw
);
3760 cls
= (PyTypeObject
*)clsraw
;
3761 if (cls
== NULL
) goto Fail
;
3762 if (! PyType_Check(cls
)) {
3763 PyErr_SetString(UnpicklingError
, "NEWOBJ class argument "
3764 "isn't a type object");
3767 if (cls
->tp_new
== NULL
) {
3768 PyErr_SetString(UnpicklingError
, "NEWOBJ class argument "
3774 obj
= cls
->tp_new(cls
, args
, NULL
);
3775 if (obj
== NULL
) goto Fail
;
3779 PDATA_PUSH(self
->stack
, obj
, -1);
3789 load_global(Unpicklerobject
*self
)
3791 PyObject
*class = 0, *module_name
= 0, *class_name
= 0;
3795 if ((len
= self
->readline_func(self
, &s
)) < 0) return -1;
3796 if (len
< 2) return bad_readline();
3797 module_name
= PyString_FromStringAndSize(s
, len
- 1);
3798 if (!module_name
) return -1;
3800 if ((len
= self
->readline_func(self
, &s
)) >= 0) {
3802 Py_DECREF(module_name
);
3803 return bad_readline();
3805 if ((class_name
= PyString_FromStringAndSize(s
, len
- 1))) {
3806 class = find_class(module_name
, class_name
,
3808 Py_DECREF(class_name
);
3811 Py_DECREF(module_name
);
3813 if (! class) return -1;
3814 PDATA_PUSH(self
->stack
, class, -1);
3820 load_persid(Unpicklerobject
*self
)
3826 if (self
->pers_func
) {
3827 if ((len
= self
->readline_func(self
, &s
)) < 0) return -1;
3828 if (len
< 2) return bad_readline();
3830 pid
= PyString_FromStringAndSize(s
, len
- 1);
3831 if (!pid
) return -1;
3833 if (PyList_Check(self
->pers_func
)) {
3834 if (PyList_Append(self
->pers_func
, pid
) < 0) {
3842 pid
= PyObject_Call(self
->pers_func
, self
->arg
,
3848 if (! pid
) return -1;
3850 PDATA_PUSH(self
->stack
, pid
, -1);
3854 PyErr_SetString(UnpicklingError
,
3855 "A load persistent id instruction was encountered,\n"
3856 "but no persistent_load function was specified.");
3862 load_binpersid(Unpicklerobject
*self
)
3866 if (self
->pers_func
) {
3867 PDATA_POP(self
->stack
, pid
);
3868 if (! pid
) return -1;
3870 if (PyList_Check(self
->pers_func
)) {
3871 if (PyList_Append(self
->pers_func
, pid
) < 0) {
3879 pid
= PyObject_Call(self
->pers_func
, self
->arg
,
3883 if (! pid
) return -1;
3886 PDATA_PUSH(self
->stack
, pid
, -1);
3890 PyErr_SetString(UnpicklingError
,
3891 "A load persistent id instruction was encountered,\n"
3892 "but no persistent_load function was specified.");
3899 load_pop(Unpicklerobject
*self
)
3903 if (!( (len
=self
->stack
->length
) > 0 )) return stackUnderflow();
3905 /* Note that we split the (pickle.py) stack into two stacks,
3906 an object stack and a mark stack. We have to be clever and
3907 pop the right one. We do this by looking at the top of the
3911 if ((self
->num_marks
> 0) &&
3912 (self
->marks
[self
->num_marks
- 1] == len
))
3916 Py_DECREF(self
->stack
->data
[len
]);
3917 self
->stack
->length
=len
;
3925 load_pop_mark(Unpicklerobject
*self
)
3929 if ((i
= marker(self
)) < 0)
3932 Pdata_clear(self
->stack
, i
);
3939 load_dup(Unpicklerobject
*self
)
3944 if ((len
= self
->stack
->length
) <= 0) return stackUnderflow();
3945 last
=self
->stack
->data
[len
-1];
3947 PDATA_PUSH(self
->stack
, last
, -1);
3953 load_get(Unpicklerobject
*self
)
3955 PyObject
*py_str
= 0, *value
= 0;
3960 if ((len
= self
->readline_func(self
, &s
)) < 0) return -1;
3961 if (len
< 2) return bad_readline();
3963 if (!( py_str
= PyString_FromStringAndSize(s
, len
- 1))) return -1;
3965 value
= PyDict_GetItem(self
->memo
, py_str
);
3967 PyErr_SetObject(BadPickleGet
, py_str
);
3971 PDATA_APPEND(self
->stack
, value
, -1);
3981 load_binget(Unpicklerobject
*self
)
3983 PyObject
*py_key
= 0, *value
= 0;
3988 if (self
->read_func(self
, &s
, 1) < 0) return -1;
3990 key
= (unsigned char)s
[0];
3991 if (!( py_key
= PyInt_FromLong((long)key
))) return -1;
3993 value
= PyDict_GetItem(self
->memo
, py_key
);
3995 PyErr_SetObject(BadPickleGet
, py_key
);
3999 PDATA_APPEND(self
->stack
, value
, -1);
4009 load_long_binget(Unpicklerobject
*self
)
4011 PyObject
*py_key
= 0, *value
= 0;
4017 if (self
->read_func(self
, &s
, 4) < 0) return -1;
4019 c
= (unsigned char)s
[0];
4021 c
= (unsigned char)s
[1];
4022 key
|= (long)c
<< 8;
4023 c
= (unsigned char)s
[2];
4024 key
|= (long)c
<< 16;
4025 c
= (unsigned char)s
[3];
4026 key
|= (long)c
<< 24;
4028 if (!( py_key
= PyInt_FromLong((long)key
))) return -1;
4030 value
= PyDict_GetItem(self
->memo
, py_key
);
4032 PyErr_SetObject(BadPickleGet
, py_key
);
4036 PDATA_APPEND(self
->stack
, value
, -1);
4044 /* Push an object from the extension registry (EXT[124]). nbytes is
4045 * the number of bytes following the opcode, holding the index (code) value.
4048 load_extension(Unpicklerobject
*self
, int nbytes
)
4050 char *codebytes
; /* the nbytes bytes after the opcode */
4051 long code
; /* calc_binint returns long */
4052 PyObject
*py_code
; /* code as a Python int */
4053 PyObject
*obj
; /* the object to push */
4054 PyObject
*pair
; /* (module_name, class_name) */
4055 PyObject
*module_name
, *class_name
;
4057 assert(nbytes
== 1 || nbytes
== 2 || nbytes
== 4);
4058 if (self
->read_func(self
, &codebytes
, nbytes
) < 0) return -1;
4059 code
= calc_binint(codebytes
, nbytes
);
4060 if (code
<= 0) { /* note that 0 is forbidden */
4061 /* Corrupt or hostile pickle. */
4062 PyErr_SetString(UnpicklingError
, "EXT specifies code <= 0");
4066 /* Look for the code in the cache. */
4067 py_code
= PyInt_FromLong(code
);
4068 if (py_code
== NULL
) return -1;
4069 obj
= PyDict_GetItem(extension_cache
, py_code
);
4073 PDATA_APPEND(self
->stack
, obj
, -1);
4077 /* Look up the (module_name, class_name) pair. */
4078 pair
= PyDict_GetItem(inverted_registry
, py_code
);
4081 PyErr_Format(PyExc_ValueError
, "unregistered extension "
4085 /* Since the extension registry is manipulable via Python code,
4086 * confirm that pair is really a 2-tuple of strings.
4088 if (!PyTuple_Check(pair
) || PyTuple_Size(pair
) != 2 ||
4089 !PyString_Check(module_name
= PyTuple_GET_ITEM(pair
, 0)) ||
4090 !PyString_Check(class_name
= PyTuple_GET_ITEM(pair
, 1))) {
4092 PyErr_Format(PyExc_ValueError
, "_inverted_registry[%ld] "
4093 "isn't a 2-tuple of strings", code
);
4096 /* Load the object. */
4097 obj
= find_class(module_name
, class_name
, self
->find_class
);
4102 /* Cache code -> obj. */
4103 code
= PyDict_SetItem(extension_cache
, py_code
, obj
);
4109 PDATA_PUSH(self
->stack
, obj
, -1);
4114 load_put(Unpicklerobject
*self
)
4116 PyObject
*py_str
= 0, *value
= 0;
4120 if ((l
= self
->readline_func(self
, &s
)) < 0) return -1;
4121 if (l
< 2) return bad_readline();
4122 if (!( len
=self
->stack
->length
)) return stackUnderflow();
4123 if (!( py_str
= PyString_FromStringAndSize(s
, l
- 1))) return -1;
4124 value
=self
->stack
->data
[len
-1];
4125 l
=PyDict_SetItem(self
->memo
, py_str
, value
);
4132 load_binput(Unpicklerobject
*self
)
4134 PyObject
*py_key
= 0, *value
= 0;
4139 if (self
->read_func(self
, &s
, 1) < 0) return -1;
4140 if (!( (len
=self
->stack
->length
) > 0 )) return stackUnderflow();
4142 key
= (unsigned char)s
[0];
4144 if (!( py_key
= PyInt_FromLong((long)key
))) return -1;
4145 value
=self
->stack
->data
[len
-1];
4146 len
=PyDict_SetItem(self
->memo
, py_key
, value
);
4153 load_long_binput(Unpicklerobject
*self
)
4155 PyObject
*py_key
= 0, *value
= 0;
4161 if (self
->read_func(self
, &s
, 4) < 0) return -1;
4162 if (!( len
=self
->stack
->length
)) return stackUnderflow();
4164 c
= (unsigned char)s
[0];
4166 c
= (unsigned char)s
[1];
4167 key
|= (long)c
<< 8;
4168 c
= (unsigned char)s
[2];
4169 key
|= (long)c
<< 16;
4170 c
= (unsigned char)s
[3];
4171 key
|= (long)c
<< 24;
4173 if (!( py_key
= PyInt_FromLong(key
))) return -1;
4174 value
=self
->stack
->data
[len
-1];
4175 len
=PyDict_SetItem(self
->memo
, py_key
, value
);
4182 do_append(Unpicklerobject
*self
, int x
)
4184 PyObject
*value
= 0, *list
= 0, *append_method
= 0;
4187 len
=self
->stack
->length
;
4188 if (!( len
>= x
&& x
> 0 )) return stackUnderflow();
4190 if (len
==x
) return 0;
4192 list
=self
->stack
->data
[x
-1];
4194 if (PyList_Check(list
)) {
4198 slice
=Pdata_popList(self
->stack
, x
);
4199 if (! slice
) return -1;
4200 list_len
= PyList_GET_SIZE(list
);
4201 i
=PyList_SetSlice(list
, list_len
, list_len
, slice
);
4207 if (!( append_method
= PyObject_GetAttr(list
, append_str
)))
4210 for (i
= x
; i
< len
; i
++) {
4213 value
=self
->stack
->data
[i
];
4215 ARG_TUP(self
, value
);
4217 junk
= PyObject_Call(append_method
, self
->arg
,
4222 Pdata_clear(self
->stack
, i
+1);
4223 self
->stack
->length
=x
;
4224 Py_DECREF(append_method
);
4229 self
->stack
->length
=x
;
4230 Py_DECREF(append_method
);
4238 load_append(Unpicklerobject
*self
)
4240 return do_append(self
, self
->stack
->length
- 1);
4245 load_appends(Unpicklerobject
*self
)
4247 return do_append(self
, marker(self
));
4252 do_setitems(Unpicklerobject
*self
, int x
)
4254 PyObject
*value
= 0, *key
= 0, *dict
= 0;
4257 if (!( (len
=self
->stack
->length
) >= x
4258 && x
> 0 )) return stackUnderflow();
4260 dict
=self
->stack
->data
[x
-1];
4262 for (i
= x
+1; i
< len
; i
+= 2) {
4263 key
=self
->stack
->data
[i
-1];
4264 value
=self
->stack
->data
[i
];
4265 if (PyObject_SetItem(dict
, key
, value
) < 0) {
4271 Pdata_clear(self
->stack
, x
);
4278 load_setitem(Unpicklerobject
*self
)
4280 return do_setitems(self
, self
->stack
->length
- 2);
4284 load_setitems(Unpicklerobject
*self
)
4286 return do_setitems(self
, marker(self
));
4291 load_build(Unpicklerobject
*self
)
4293 PyObject
*state
, *inst
, *slotstate
;
4294 PyObject
*__setstate__
;
4295 PyObject
*d_key
, *d_value
;
4299 /* Stack is ... instance, state. We want to leave instance at
4300 * the stack top, possibly mutated via instance.__setstate__(state).
4302 if (self
->stack
->length
< 2)
4303 return stackUnderflow();
4304 PDATA_POP(self
->stack
, state
);
4307 inst
= self
->stack
->data
[self
->stack
->length
- 1];
4309 __setstate__
= PyObject_GetAttr(inst
, __setstate___str
);
4310 if (__setstate__
!= NULL
) {
4311 PyObject
*junk
= NULL
;
4313 /* The explicit __setstate__ is responsible for everything. */
4314 ARG_TUP(self
, state
);
4316 junk
= PyObject_Call(__setstate__
, self
->arg
, NULL
);
4319 Py_DECREF(__setstate__
);
4325 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
4329 /* A default __setstate__. First see whether state embeds a
4330 * slot state dict too (a proto 2 addition).
4332 if (PyTuple_Check(state
) && PyTuple_Size(state
) == 2) {
4333 PyObject
*temp
= state
;
4334 state
= PyTuple_GET_ITEM(temp
, 0);
4335 slotstate
= PyTuple_GET_ITEM(temp
, 1);
4337 Py_INCREF(slotstate
);
4343 /* Set inst.__dict__ from the state dict (if any). */
4344 if (state
!= Py_None
) {
4346 if (! PyDict_Check(state
)) {
4347 PyErr_SetString(UnpicklingError
, "state is not a "
4351 dict
= PyObject_GetAttr(inst
, __dict___str
);
4356 while (PyDict_Next(state
, &i
, &d_key
, &d_value
)) {
4357 if (PyObject_SetItem(dict
, d_key
, d_value
) < 0)
4363 /* Also set instance attributes from the slotstate dict (if any). */
4364 if (slotstate
!= NULL
) {
4365 if (! PyDict_Check(slotstate
)) {
4366 PyErr_SetString(UnpicklingError
, "slot state is not "
4371 while (PyDict_Next(slotstate
, &i
, &d_key
, &d_value
)) {
4372 if (PyObject_SetAttr(inst
, d_key
, d_value
) < 0)
4380 Py_XDECREF(slotstate
);
4386 load_mark(Unpicklerobject
*self
)
4390 /* Note that we split the (pickle.py) stack into two stacks, an
4391 object stack and a mark stack. Here we push a mark onto the
4395 if ((self
->num_marks
+ 1) >= self
->marks_size
) {
4397 s
=self
->marks_size
+20;
4398 if (s
<= self
->num_marks
) s
=self
->num_marks
+ 1;
4399 if (self
->marks
== NULL
)
4400 marks
=(int *)malloc(s
* sizeof(int));
4402 marks
=(int *)realloc(self
->marks
,
4408 self
->marks
= marks
;
4409 self
->marks_size
= s
;
4412 self
->marks
[self
->num_marks
++] = self
->stack
->length
;
4418 load_reduce(Unpicklerobject
*self
)
4420 PyObject
*callable
= 0, *arg_tup
= 0, *ob
= 0;
4422 PDATA_POP(self
->stack
, arg_tup
);
4423 if (! arg_tup
) return -1;
4424 PDATA_POP(self
->stack
, callable
);
4426 ob
= Instance_New(callable
, arg_tup
);
4427 Py_DECREF(callable
);
4431 if (! ob
) return -1;
4433 PDATA_PUSH(self
->stack
, ob
, -1);
4437 /* Just raises an error if we don't know the protocol specified. PROTO
4438 * is the first opcode for protocols >= 2.
4441 load_proto(Unpicklerobject
*self
)
4446 i
= self
->read_func(self
, &protobyte
, 1);
4450 i
= calc_binint(protobyte
, 1);
4451 /* No point checking for < 0, since calc_binint returns an unsigned
4452 * int when chewing on 1 byte.
4455 if (i
<= HIGHEST_PROTOCOL
)
4458 PyErr_Format(PyExc_ValueError
, "unsupported pickle protocol: %d", i
);
4463 load(Unpicklerobject
*self
)
4465 PyObject
*err
= 0, *val
= 0;
4468 self
->num_marks
= 0;
4469 if (self
->stack
->length
) Pdata_clear(self
->stack
, 0);
4472 if (self
->read_func(self
, &s
, 1) < 0)
4477 if (load_none(self
) < 0)
4482 if (load_binint(self
) < 0)
4487 if (load_binint1(self
) < 0)
4492 if (load_binint2(self
) < 0)
4497 if (load_int(self
) < 0)
4502 if (load_long(self
) < 0)
4507 if (load_counted_long(self
, 1) < 0)
4512 if (load_counted_long(self
, 4) < 0)
4517 if (load_float(self
) < 0)
4522 if (load_binfloat(self
) < 0)
4527 if (load_binstring(self
) < 0)
4531 case SHORT_BINSTRING
:
4532 if (load_short_binstring(self
) < 0)
4537 if (load_string(self
) < 0)
4541 #ifdef Py_USING_UNICODE
4543 if (load_unicode(self
) < 0)
4548 if (load_binunicode(self
) < 0)
4554 if (load_counted_tuple(self
, 0) < 0)
4559 if (load_counted_tuple(self
, 1) < 0)
4564 if (load_counted_tuple(self
, 2) < 0)
4569 if (load_counted_tuple(self
, 3) < 0)
4574 if (load_tuple(self
) < 0)
4579 if (load_empty_list(self
) < 0)
4584 if (load_list(self
) < 0)
4589 if (load_empty_dict(self
) < 0)
4594 if (load_dict(self
) < 0)
4599 if (load_obj(self
) < 0)
4604 if (load_inst(self
) < 0)
4609 if (load_newobj(self
) < 0)
4614 if (load_global(self
) < 0)
4619 if (load_append(self
) < 0)
4624 if (load_appends(self
) < 0)
4629 if (load_build(self
) < 0)
4634 if (load_dup(self
) < 0)
4639 if (load_binget(self
) < 0)
4644 if (load_long_binget(self
) < 0)
4649 if (load_get(self
) < 0)
4654 if (load_extension(self
, 1) < 0)
4659 if (load_extension(self
, 2) < 0)
4664 if (load_extension(self
, 4) < 0)
4668 if (load_mark(self
) < 0)
4673 if (load_binput(self
) < 0)
4678 if (load_long_binput(self
) < 0)
4683 if (load_put(self
) < 0)
4688 if (load_pop(self
) < 0)
4693 if (load_pop_mark(self
) < 0)
4698 if (load_setitem(self
) < 0)
4703 if (load_setitems(self
) < 0)
4711 if (load_persid(self
) < 0)
4716 if (load_binpersid(self
) < 0)
4721 if (load_reduce(self
) < 0)
4726 if (load_proto(self
) < 0)
4731 if (load_bool(self
, Py_True
) < 0)
4736 if (load_bool(self
, Py_False
) < 0)
4742 PyErr_SetNone(PyExc_EOFError
);
4746 cPickle_ErrFormat(UnpicklingError
,
4747 "invalid load key, '%s'.",
4755 if ((err
= PyErr_Occurred())) {
4756 if (err
== PyExc_EOFError
) {
4757 PyErr_SetNone(PyExc_EOFError
);
4762 PDATA_POP(self
->stack
, val
);
4767 /* No-load functions to support noload, which is used to
4768 find persistent references. */
4771 noload_obj(Unpicklerobject
*self
)
4775 if ((i
= marker(self
)) < 0) return -1;
4776 return Pdata_clear(self
->stack
, i
+1);
4781 noload_inst(Unpicklerobject
*self
)
4786 if ((i
= marker(self
)) < 0) return -1;
4787 Pdata_clear(self
->stack
, i
);
4788 if (self
->readline_func(self
, &s
) < 0) return -1;
4789 if (self
->readline_func(self
, &s
) < 0) return -1;
4790 PDATA_APPEND(self
->stack
, Py_None
, -1);
4795 noload_newobj(Unpicklerobject
*self
)
4799 PDATA_POP(self
->stack
, obj
); /* pop argtuple */
4800 if (obj
== NULL
) return -1;
4803 PDATA_POP(self
->stack
, obj
); /* pop cls */
4804 if (obj
== NULL
) return -1;
4807 PDATA_APPEND(self
->stack
, Py_None
, -1);
4812 noload_global(Unpicklerobject
*self
)
4816 if (self
->readline_func(self
, &s
) < 0) return -1;
4817 if (self
->readline_func(self
, &s
) < 0) return -1;
4818 PDATA_APPEND(self
->stack
, Py_None
,-1);
4823 noload_reduce(Unpicklerobject
*self
)
4826 if (self
->stack
->length
< 2) return stackUnderflow();
4827 Pdata_clear(self
->stack
, self
->stack
->length
-2);
4828 PDATA_APPEND(self
->stack
, Py_None
,-1);
4833 noload_build(Unpicklerobject
*self
) {
4835 if (self
->stack
->length
< 1) return stackUnderflow();
4836 Pdata_clear(self
->stack
, self
->stack
->length
-1);
4841 noload_extension(Unpicklerobject
*self
, int nbytes
)
4845 assert(nbytes
== 1 || nbytes
== 2 || nbytes
== 4);
4846 if (self
->read_func(self
, &codebytes
, nbytes
) < 0) return -1;
4847 PDATA_APPEND(self
->stack
, Py_None
, -1);
4853 noload(Unpicklerobject
*self
)
4855 PyObject
*err
= 0, *val
= 0;
4858 self
->num_marks
= 0;
4859 Pdata_clear(self
->stack
, 0);
4862 if (self
->read_func(self
, &s
, 1) < 0)
4867 if (load_none(self
) < 0)
4872 if (load_binint(self
) < 0)
4877 if (load_binint1(self
) < 0)
4882 if (load_binint2(self
) < 0)
4887 if (load_int(self
) < 0)
4892 if (load_long(self
) < 0)
4897 if (load_counted_long(self
, 1) < 0)
4902 if (load_counted_long(self
, 4) < 0)
4907 if (load_float(self
) < 0)
4912 if (load_binfloat(self
) < 0)
4917 if (load_binstring(self
) < 0)
4921 case SHORT_BINSTRING
:
4922 if (load_short_binstring(self
) < 0)
4927 if (load_string(self
) < 0)
4931 #ifdef Py_USING_UNICODE
4933 if (load_unicode(self
) < 0)
4938 if (load_binunicode(self
) < 0)
4944 if (load_counted_tuple(self
, 0) < 0)
4949 if (load_counted_tuple(self
, 1) < 0)
4954 if (load_counted_tuple(self
, 2) < 0)
4959 if (load_counted_tuple(self
, 3) < 0)
4964 if (load_tuple(self
) < 0)
4969 if (load_empty_list(self
) < 0)
4974 if (load_list(self
) < 0)
4979 if (load_empty_dict(self
) < 0)
4984 if (load_dict(self
) < 0)
4989 if (noload_obj(self
) < 0)
4994 if (noload_inst(self
) < 0)
4999 if (noload_newobj(self
) < 0)
5004 if (noload_global(self
) < 0)
5009 if (load_append(self
) < 0)
5014 if (load_appends(self
) < 0)
5019 if (noload_build(self
) < 0)
5024 if (load_dup(self
) < 0)
5029 if (load_binget(self
) < 0)
5034 if (load_long_binget(self
) < 0)
5039 if (load_get(self
) < 0)
5044 if (noload_extension(self
, 1) < 0)
5049 if (noload_extension(self
, 2) < 0)
5054 if (noload_extension(self
, 4) < 0)
5059 if (load_mark(self
) < 0)
5064 if (load_binput(self
) < 0)
5069 if (load_long_binput(self
) < 0)
5074 if (load_put(self
) < 0)
5079 if (load_pop(self
) < 0)
5084 if (load_pop_mark(self
) < 0)
5089 if (load_setitem(self
) < 0)
5094 if (load_setitems(self
) < 0)
5102 if (load_persid(self
) < 0)
5107 if (load_binpersid(self
) < 0)
5112 if (noload_reduce(self
) < 0)
5117 if (load_proto(self
) < 0)
5122 if (load_bool(self
, Py_True
) < 0)
5127 if (load_bool(self
, Py_False
) < 0)
5131 cPickle_ErrFormat(UnpicklingError
,
5132 "invalid load key, '%s'.",
5140 if ((err
= PyErr_Occurred())) {
5141 if (err
== PyExc_EOFError
) {
5142 PyErr_SetNone(PyExc_EOFError
);
5147 PDATA_POP(self
->stack
, val
);
5153 Unpickler_load(Unpicklerobject
*self
, PyObject
*unused
)
5159 Unpickler_noload(Unpicklerobject
*self
, PyObject
*unused
)
5161 return noload(self
);
5165 static struct PyMethodDef Unpickler_methods
[] = {
5166 {"load", (PyCFunction
)Unpickler_load
, METH_NOARGS
,
5167 PyDoc_STR("load() -- Load a pickle")
5169 {"noload", (PyCFunction
)Unpickler_noload
, METH_NOARGS
,
5171 "noload() -- not load a pickle, but go through most of the motions\n"
5173 "This function can be used to read past a pickle without instantiating\n"
5174 "any objects or importing any modules. It can also be used to find all\n"
5175 "persistent references without instantiating any objects or importing\n"
5178 {NULL
, NULL
} /* sentinel */
5182 static Unpicklerobject
*
5183 newUnpicklerobject(PyObject
*f
)
5185 Unpicklerobject
*self
;
5187 if (!( self
= PyObject_GC_New(Unpicklerobject
, &Unpicklertype
)))
5192 self
->stack
= (Pdata
*)Pdata_New();
5193 self
->pers_func
= NULL
;
5194 self
->last_string
= NULL
;
5196 self
->num_marks
= 0;
5197 self
->marks_size
= 0;
5200 self
->readline
= NULL
;
5201 self
->find_class
= NULL
;
5203 if (!( self
->memo
= PyDict_New()))
5212 /* Set read, readline based on type of f */
5213 if (PyFile_Check(f
)) {
5214 self
->fp
= PyFile_AsFile(f
);
5215 if (self
->fp
== NULL
) {
5216 PyErr_SetString(PyExc_ValueError
,
5217 "I/O operation on closed file");
5220 self
->read_func
= read_file
;
5221 self
->readline_func
= readline_file
;
5223 else if (PycStringIO_InputCheck(f
)) {
5225 self
->read_func
= read_cStringIO
;
5226 self
->readline_func
= readline_cStringIO
;
5231 self
->read_func
= read_other
;
5232 self
->readline_func
= readline_other
;
5234 if (!( (self
->readline
= PyObject_GetAttr(f
, readline_str
)) &&
5235 (self
->read
= PyObject_GetAttr(f
, read_str
)))) {
5237 PyErr_SetString( PyExc_TypeError
,
5238 "argument must have 'read' and "
5239 "'readline' attributes" );
5243 PyObject_GC_Track(self
);
5248 Py_DECREF((PyObject
*)self
);
5254 get_Unpickler(PyObject
*self
, PyObject
*file
)
5256 return (PyObject
*)newUnpicklerobject(file
);
5261 Unpickler_dealloc(Unpicklerobject
*self
)
5263 PyObject_GC_UnTrack((PyObject
*)self
);
5264 Py_XDECREF(self
->readline
);
5265 Py_XDECREF(self
->read
);
5266 Py_XDECREF(self
->file
);
5267 Py_XDECREF(self
->memo
);
5268 Py_XDECREF(self
->stack
);
5269 Py_XDECREF(self
->pers_func
);
5270 Py_XDECREF(self
->arg
);
5271 Py_XDECREF(self
->last_string
);
5272 Py_XDECREF(self
->find_class
);
5278 if (self
->buf_size
) {
5282 Py_TYPE(self
)->tp_free((PyObject
*)self
);
5286 Unpickler_traverse(Unpicklerobject
*self
, visitproc visit
, void *arg
)
5288 Py_VISIT(self
->readline
);
5289 Py_VISIT(self
->read
);
5290 Py_VISIT(self
->file
);
5291 Py_VISIT(self
->memo
);
5292 Py_VISIT(self
->stack
);
5293 Py_VISIT(self
->pers_func
);
5294 Py_VISIT(self
->arg
);
5295 Py_VISIT(self
->last_string
);
5296 Py_VISIT(self
->find_class
);
5301 Unpickler_clear(Unpicklerobject
*self
)
5303 Py_CLEAR(self
->readline
);
5304 Py_CLEAR(self
->read
);
5305 Py_CLEAR(self
->file
);
5306 Py_CLEAR(self
->memo
);
5307 Py_CLEAR(self
->stack
);
5308 Py_CLEAR(self
->pers_func
);
5309 Py_CLEAR(self
->arg
);
5310 Py_CLEAR(self
->last_string
);
5311 Py_CLEAR(self
->find_class
);
5316 Unpickler_getattr(Unpicklerobject
*self
, char *name
)
5318 if (!strcmp(name
, "persistent_load")) {
5319 if (!self
->pers_func
) {
5320 PyErr_SetString(PyExc_AttributeError
, name
);
5324 Py_INCREF(self
->pers_func
);
5325 return self
->pers_func
;
5328 if (!strcmp(name
, "find_global")) {
5329 if (!self
->find_class
) {
5330 PyErr_SetString(PyExc_AttributeError
, name
);
5334 Py_INCREF(self
->find_class
);
5335 return self
->find_class
;
5338 if (!strcmp(name
, "memo")) {
5340 PyErr_SetString(PyExc_AttributeError
, name
);
5344 Py_INCREF(self
->memo
);
5348 if (!strcmp(name
, "UnpicklingError")) {
5349 Py_INCREF(UnpicklingError
);
5350 return UnpicklingError
;
5353 return Py_FindMethod(Unpickler_methods
, (PyObject
*)self
, name
);
5358 Unpickler_setattr(Unpicklerobject
*self
, char *name
, PyObject
*value
)
5361 if (!strcmp(name
, "persistent_load")) {
5362 Py_XDECREF(self
->pers_func
);
5363 self
->pers_func
= value
;
5368 if (!strcmp(name
, "find_global")) {
5369 Py_XDECREF(self
->find_class
);
5370 self
->find_class
= value
;
5376 PyErr_SetString(PyExc_TypeError
,
5377 "attribute deletion is not supported");
5381 if (strcmp(name
, "memo") == 0) {
5382 if (!PyDict_Check(value
)) {
5383 PyErr_SetString(PyExc_TypeError
,
5384 "memo must be a dictionary");
5387 Py_XDECREF(self
->memo
);
5393 PyErr_SetString(PyExc_AttributeError
, name
);
5397 /* ---------------------------------------------------------------------------
5398 * Module-level functions.
5401 /* dump(obj, file, protocol=0). */
5403 cpm_dump(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
5405 static char *kwlist
[] = {"obj", "file", "protocol", NULL
};
5406 PyObject
*ob
, *file
, *res
= NULL
;
5407 Picklerobject
*pickler
= 0;
5410 if (!( PyArg_ParseTupleAndKeywords(args
, kwds
, "OO|i", kwlist
,
5411 &ob
, &file
, &proto
)))
5414 if (!( pickler
= newPicklerobject(file
, proto
)))
5417 if (dump(pickler
, ob
) < 0)
5424 Py_XDECREF(pickler
);
5430 /* dumps(obj, protocol=0). */
5432 cpm_dumps(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
5434 static char *kwlist
[] = {"obj", "protocol", NULL
};
5435 PyObject
*ob
, *file
= 0, *res
= NULL
;
5436 Picklerobject
*pickler
= 0;
5439 if (!( PyArg_ParseTupleAndKeywords(args
, kwds
, "O|i:dumps", kwlist
,
5443 if (!( file
= PycStringIO
->NewOutput(128)))
5446 if (!( pickler
= newPicklerobject(file
, proto
)))
5449 if (dump(pickler
, ob
) < 0)
5452 res
= PycStringIO
->cgetvalue(file
);
5455 Py_XDECREF(pickler
);
5462 /* load(fileobj). */
5464 cpm_load(PyObject
*self
, PyObject
*ob
)
5466 Unpicklerobject
*unpickler
= 0;
5467 PyObject
*res
= NULL
;
5469 if (!( unpickler
= newUnpicklerobject(ob
)))
5472 res
= load(unpickler
);
5475 Py_XDECREF(unpickler
);
5483 cpm_loads(PyObject
*self
, PyObject
*args
)
5485 PyObject
*ob
, *file
= 0, *res
= NULL
;
5486 Unpicklerobject
*unpickler
= 0;
5488 if (!( PyArg_ParseTuple(args
, "S:loads", &ob
)))
5491 if (!( file
= PycStringIO
->NewInput(ob
)))
5494 if (!( unpickler
= newUnpicklerobject(file
)))
5497 res
= load(unpickler
);
5501 Py_XDECREF(unpickler
);
5507 PyDoc_STRVAR(Unpicklertype__doc__
,
5508 "Objects that know how to unpickle");
5510 static PyTypeObject Unpicklertype
= {
5511 PyVarObject_HEAD_INIT(NULL
, 0)
5512 "cPickle.Unpickler", /*tp_name*/
5513 sizeof(Unpicklerobject
), /*tp_basicsize*/
5515 (destructor
)Unpickler_dealloc
, /* tp_dealloc */
5517 (getattrfunc
)Unpickler_getattr
, /* tp_getattr */
5518 (setattrfunc
)Unpickler_setattr
, /* tp_setattr */
5521 0, /* tp_as_number */
5522 0, /* tp_as_sequence */
5523 0, /* tp_as_mapping */
5527 0, /* tp_getattro */
5528 0, /* tp_setattro */
5529 0, /* tp_as_buffer */
5530 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
| Py_TPFLAGS_HAVE_GC
,
5531 Unpicklertype__doc__
, /* tp_doc */
5532 (traverseproc
)Unpickler_traverse
, /* tp_traverse */
5533 (inquiry
)Unpickler_clear
, /* tp_clear */
5536 static struct PyMethodDef cPickle_methods
[] = {
5537 {"dump", (PyCFunction
)cpm_dump
, METH_VARARGS
| METH_KEYWORDS
,
5538 PyDoc_STR("dump(obj, file, protocol=0) -- "
5539 "Write an object in pickle format to the given file.\n"
5541 "See the Pickler docstring for the meaning of optional argument proto.")
5544 {"dumps", (PyCFunction
)cpm_dumps
, METH_VARARGS
| METH_KEYWORDS
,
5545 PyDoc_STR("dumps(obj, protocol=0) -- "
5546 "Return a string containing an object in pickle format.\n"
5548 "See the Pickler docstring for the meaning of optional argument proto.")
5551 {"load", (PyCFunction
)cpm_load
, METH_O
,
5552 PyDoc_STR("load(file) -- Load a pickle from the given file")},
5554 {"loads", (PyCFunction
)cpm_loads
, METH_VARARGS
,
5555 PyDoc_STR("loads(string) -- Load a pickle from the given string")},
5557 {"Pickler", (PyCFunction
)get_Pickler
, METH_VARARGS
| METH_KEYWORDS
,
5558 PyDoc_STR("Pickler(file, protocol=0) -- Create a pickler.\n"
5560 "This takes a file-like object for writing a pickle data stream.\n"
5561 "The optional proto argument tells the pickler to use the given\n"
5562 "protocol; supported protocols are 0, 1, 2. The default\n"
5563 "protocol is 0, to be backwards compatible. (Protocol 0 is the\n"
5564 "only protocol that can be written to a file opened in text\n"
5565 "mode and read back successfully. When using a protocol higher\n"
5566 "than 0, make sure the file is opened in binary mode, both when\n"
5567 "pickling and unpickling.)\n"
5569 "Protocol 1 is more efficient than protocol 0; protocol 2 is\n"
5570 "more efficient than protocol 1.\n"
5572 "Specifying a negative protocol version selects the highest\n"
5573 "protocol version supported. The higher the protocol used, the\n"
5574 "more recent the version of Python needed to read the pickle\n"
5577 "The file parameter must have a write() method that accepts a single\n"
5578 "string argument. It can thus be an open file object, a StringIO\n"
5579 "object, or any other custom object that meets this interface.\n")
5582 {"Unpickler", (PyCFunction
)get_Unpickler
, METH_O
,
5583 PyDoc_STR("Unpickler(file) -- Create an unpickler.")},
5589 init_stuff(PyObject
*module_dict
)
5591 PyObject
*copyreg
, *t
, *r
;
5593 #define INIT_STR(S) if (!( S ## _str=PyString_InternFromString(#S))) return -1;
5595 if (PyType_Ready(&Unpicklertype
) < 0)
5597 if (PyType_Ready(&Picklertype
) < 0)
5600 INIT_STR(__class__
);
5601 INIT_STR(__getinitargs__
);
5603 INIT_STR(__getstate__
);
5604 INIT_STR(__setstate__
);
5607 INIT_STR(__reduce__
);
5608 INIT_STR(__reduce_ex__
);
5614 INIT_STR(dispatch_table
);
5616 if (!( copyreg
= PyImport_ImportModule("copy_reg")))
5619 /* This is special because we want to use a different
5620 one in restricted mode. */
5621 dispatch_table
= PyObject_GetAttr(copyreg
, dispatch_table_str
);
5622 if (!dispatch_table
) return -1;
5624 extension_registry
= PyObject_GetAttrString(copyreg
,
5625 "_extension_registry");
5626 if (!extension_registry
) return -1;
5628 inverted_registry
= PyObject_GetAttrString(copyreg
,
5629 "_inverted_registry");
5630 if (!inverted_registry
) return -1;
5632 extension_cache
= PyObject_GetAttrString(copyreg
,
5633 "_extension_cache");
5634 if (!extension_cache
) return -1;
5638 if (!(empty_tuple
= PyTuple_New(0)))
5641 two_tuple
= PyTuple_New(2);
5642 if (two_tuple
== NULL
)
5644 /* We use this temp container with no regard to refcounts, or to
5645 * keeping containees alive. Exempt from GC, because we don't
5646 * want anything looking at two_tuple() by magic.
5648 PyObject_GC_UnTrack(two_tuple
);
5651 if (!( t
=PyImport_ImportModule("__builtin__"))) return -1;
5652 if (PyDict_SetItemString(module_dict
, "__builtins__", t
) < 0)
5655 if (!( t
=PyDict_New())) return -1;
5656 if (!( r
=PyRun_String(
5657 "def __str__(self):\n"
5658 " return self.args and ('%s' % self.args[0]) or '(what)'\n",
5660 module_dict
, t
) )) return -1;
5663 PickleError
= PyErr_NewException("cPickle.PickleError", NULL
, t
);
5669 PicklingError
= PyErr_NewException("cPickle.PicklingError",
5674 if (!( t
=PyDict_New())) return -1;
5675 if (!( r
=PyRun_String(
5676 "def __str__(self):\n"
5678 " a=a and type(a[0]) or '(what)'\n"
5679 " return 'Cannot pickle %s objects' % a\n"
5681 module_dict
, t
) )) return -1;
5684 if (!( UnpickleableError
= PyErr_NewException(
5685 "cPickle.UnpickleableError", PicklingError
, t
)))
5690 if (!( UnpicklingError
= PyErr_NewException("cPickle.UnpicklingError",
5691 PickleError
, NULL
)))
5694 if (!( BadPickleGet
= PyErr_NewException("cPickle.BadPickleGet",
5695 UnpicklingError
, NULL
)))
5698 if (PyDict_SetItemString(module_dict
, "PickleError",
5702 if (PyDict_SetItemString(module_dict
, "PicklingError",
5706 if (PyDict_SetItemString(module_dict
, "UnpicklingError",
5707 UnpicklingError
) < 0)
5710 if (PyDict_SetItemString(module_dict
, "UnpickleableError",
5711 UnpickleableError
) < 0)
5714 if (PyDict_SetItemString(module_dict
, "BadPickleGet",
5723 #ifndef PyMODINIT_FUNC /* declarations for DLL import/export */
5724 #define PyMODINIT_FUNC void
5729 PyObject
*m
, *d
, *di
, *v
, *k
;
5731 char *rev
= "1.71"; /* XXX when does this change? */
5732 PyObject
*format_version
;
5733 PyObject
*compatible_formats
;
5735 /* XXX: Should mention that the pickle module will include the C
5736 XXX: optimized implementation automatically. */
5737 if (PyErr_WarnPy3k("the cPickle module has been removed in "
5738 "Python 3.0", 2) < 0)
5741 Py_TYPE(&Picklertype
) = &PyType_Type
;
5742 Py_TYPE(&Unpicklertype
) = &PyType_Type
;
5743 Py_TYPE(&PdataType
) = &PyType_Type
;
5745 /* Initialize some pieces. We need to do this before module creation,
5746 * so we're forced to use a temporary dictionary. :(
5750 if (init_stuff(di
) < 0) return;
5752 /* Create the module and add the functions */
5753 m
= Py_InitModule4("cPickle", cPickle_methods
,
5754 cPickle_module_documentation
,
5755 (PyObject
*)NULL
,PYTHON_API_VERSION
);
5759 /* Add some symbolic constants to the module */
5760 d
= PyModule_GetDict(m
);
5761 v
= PyString_FromString(rev
);
5762 PyDict_SetItemString(d
, "__version__", v
);
5765 /* Copy data from di. Waaa. */
5766 for (i
=0; PyDict_Next(di
, &i
, &k
, &v
); ) {
5767 if (PyObject_SetItem(d
, k
, v
) < 0) {
5774 i
= PyModule_AddIntConstant(m
, "HIGHEST_PROTOCOL", HIGHEST_PROTOCOL
);
5778 /* These are purely informational; no code uses them. */
5779 /* File format version we write. */
5780 format_version
= PyString_FromString("2.0");
5781 /* Format versions we can read. */
5782 compatible_formats
= Py_BuildValue("[sssss]",
5783 "1.0", /* Original protocol 0 */
5784 "1.1", /* Protocol 0 + INST */
5785 "1.2", /* Original protocol 1 */
5786 "1.3", /* Protocol 1 + BINFLOAT */
5787 "2.0"); /* Original protocol 2 */
5788 PyDict_SetItemString(d
, "format_version", format_version
);
5789 PyDict_SetItemString(d
, "compatible_formats", compatible_formats
);
5790 Py_XDECREF(format_version
);
5791 Py_XDECREF(compatible_formats
);