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 * Note: The UNICODE macro controls the TCHAR meaning of the win32 API. Since
22 * all headers have already been included here, we can safely redefine it.
29 * Pickle opcodes. These must be kept in synch with pickle.py. Extensive
30 * docs are in pickletools.py.
50 #define SHORT_BINSTRING 'U'
52 #define BINUNICODE 'X'
57 #define EMPTY_DICT '}'
62 #define LONG_BINGET 'j'
64 #define EMPTY_LIST ']'
68 #define LONG_BINPUT 'r'
71 #define EMPTY_TUPLE ')'
75 #define PROTO '\x80' /* identify pickle protocol */
76 #define NEWOBJ '\x81' /* build object by applying cls.__new__ to argtuple */
77 #define EXT1 '\x82' /* push object from extension registry; 1-byte index */
78 #define EXT2 '\x83' /* ditto, but 2-byte index */
79 #define EXT4 '\x84' /* ditto, but 4-byte index */
80 #define TUPLE1 '\x85' /* build 1-tuple from stack top */
81 #define TUPLE2 '\x86' /* build 2-tuple from two topmost stack items */
82 #define TUPLE3 '\x87' /* build 3-tuple from three topmost stack items */
83 #define NEWTRUE '\x88' /* push True */
84 #define NEWFALSE '\x89' /* push False */
85 #define LONG1 '\x8a' /* push long from < 256 bytes */
86 #define LONG4 '\x8b' /* push really big long */
88 /* There aren't opcodes -- they're ways to pickle bools before protocol 2,
89 * so that unpicklers written before bools were introduced unpickle them
90 * as ints, but unpicklers after can recognize that bools were intended.
91 * Note that protocol 2 added direct ways to pickle bools.
98 /* Keep in synch with pickle.Pickler._BATCHSIZE. This is how many elements
99 * batch_list/dict() pumps out before doing APPENDS/SETITEMS. Nothing will
100 * break if this gets out of synch with pickle.py, but it's unclear that
101 * would help anything either.
103 #define BATCHSIZE 1000
105 static char MARKv
= MARK
;
107 static PyObject
*PickleError
;
108 static PyObject
*PicklingError
;
109 static PyObject
*UnpickleableError
;
110 static PyObject
*UnpicklingError
;
111 static PyObject
*BadPickleGet
;
113 /* As the name says, an empty tuple. */
114 static PyObject
*empty_tuple
;
116 /* copy_reg.dispatch_table, {type_object: pickling_function} */
117 static PyObject
*dispatch_table
;
119 /* For EXT[124] opcodes. */
120 /* copy_reg._extension_registry, {(module_name, function_name): code} */
121 static PyObject
*extension_registry
;
122 /* copy_reg._inverted_registry, {code: (module_name, function_name)} */
123 static PyObject
*inverted_registry
;
124 /* copy_reg._extension_cache, {code: object} */
125 static PyObject
*extension_cache
;
127 /* For looking up name pairs in copy_reg._extension_registry. */
128 static PyObject
*two_tuple
;
130 static PyObject
*__class___str
, *__getinitargs___str
, *__dict___str
,
131 *__getstate___str
, *__setstate___str
, *__name___str
, *__reduce___str
,
133 *write_str
, *append_str
,
134 *read_str
, *readline_str
, *__main___str
,
137 /*************************************************************************
138 Internal Data type for pickle data. */
142 int length
; /* number of initial slots in data currently used */
143 int size
; /* number of slots in data allocated */
148 Pdata_dealloc(Pdata
*self
)
153 for (i
= self
->length
, p
= self
->data
; --i
>= 0; p
++) {
161 static PyTypeObject PdataType
= {
162 PyVarObject_HEAD_INIT(NULL
, 0) "cPickle.Pdata", sizeof(Pdata
), 0,
163 (destructor
)Pdata_dealloc
,
164 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0L,0L,0L,0L, ""
167 #define Pdata_Check(O) (Py_TYPE(O) == &PdataType)
174 if (!(self
= PyObject_New(Pdata
, &PdataType
)))
178 self
->data
= malloc(self
->size
* sizeof(PyObject
*));
180 return (PyObject
*)self
;
182 return PyErr_NoMemory();
188 PyErr_SetString(UnpicklingError
, "unpickling stack underflow");
192 /* Retain only the initial clearto items. If clearto >= the current
193 * number of items, this is a (non-erroneous) NOP.
196 Pdata_clear(Pdata
*self
, int clearto
)
201 if (clearto
< 0) return stackUnderflow();
202 if (clearto
>= self
->length
) return 0;
204 for (i
= self
->length
, p
= self
->data
+ clearto
;
209 self
->length
= clearto
;
215 Pdata_grow(Pdata
*self
)
221 bigger
= self
->size
<< 1;
222 if (bigger
<= 0) /* was 0, or new value overflows */
224 if ((int)(size_t)bigger
!= bigger
)
226 nbytes
= (size_t)bigger
* sizeof(PyObject
*);
227 if (nbytes
/ sizeof(PyObject
*) != (size_t)bigger
)
229 tmp
= realloc(self
->data
, nbytes
);
241 /* D is a Pdata*. Pop the topmost element and store it into V, which
242 * must be an lvalue holding PyObject*. On stack underflow, UnpicklingError
243 * is raised and V is set to NULL. D and V may be evaluated several times.
245 #define PDATA_POP(D, V) { \
247 (V) = (D)->data[--((D)->length)]; \
249 PyErr_SetString(UnpicklingError, "bad pickle data"); \
254 /* PDATA_PUSH and PDATA_APPEND both push rvalue PyObject* O on to Pdata*
255 * D. If the Pdata stack can't be grown to hold the new value, both
256 * raise MemoryError and execute "return ER". The difference is in ownership
257 * of O after: _PUSH transfers ownership of O from the caller to the stack
258 * (no incref of O is done, and in case of error O is decrefed), while
259 * _APPEND pushes a new reference.
262 /* Push O on stack D, giving ownership of O to the stack. */
263 #define PDATA_PUSH(D, O, ER) { \
264 if (((Pdata*)(D))->length == ((Pdata*)(D))->size && \
265 Pdata_grow((Pdata*)(D)) < 0) { \
269 ((Pdata*)(D))->data[((Pdata*)(D))->length++] = (O); \
272 /* Push O on stack D, pushing a new reference. */
273 #define PDATA_APPEND(D, O, ER) { \
274 if (((Pdata*)(D))->length == ((Pdata*)(D))->size && \
275 Pdata_grow((Pdata*)(D)) < 0) \
278 ((Pdata*)(D))->data[((Pdata*)(D))->length++] = (O); \
283 Pdata_popTuple(Pdata
*self
, int start
)
288 l
= self
->length
-start
;
292 for (i
= start
, j
= 0 ; j
< l
; i
++, j
++)
293 PyTuple_SET_ITEM(r
, j
, self
->data
[i
]);
295 self
->length
= start
;
300 Pdata_popList(Pdata
*self
, int start
)
305 l
=self
->length
-start
;
306 if (!( r
=PyList_New(l
))) return NULL
;
307 for (i
=start
, j
=0 ; j
< l
; i
++, j
++)
308 PyList_SET_ITEM(r
, j
, self
->data
[i
]);
314 /*************************************************************************/
316 #define ARG_TUP(self, o) { \
317 if (self->arg || (self->arg=PyTuple_New(1))) { \
318 Py_XDECREF(PyTuple_GET_ITEM(self->arg,0)); \
319 PyTuple_SET_ITEM(self->arg,0,o); \
326 #define FREE_ARG_TUP(self) { \
327 if (Py_REFCNT(self->arg) > 1) { \
328 Py_DECREF(self->arg); \
333 typedef struct Picklerobject
{
341 PyObject
*inst_pers_func
;
343 /* pickle protocol number, >= 0 */
346 /* bool, true if proto > 0 */
349 int fast
; /* Fast mode doesn't save in memo, don't use if circ ref */
350 int (*write_func
)(struct Picklerobject
*, const char *, Py_ssize_t
);
353 PyObject
*dispatch_table
;
354 int fast_container
; /* count nested container dumps */
358 #ifndef PY_CPICKLE_FAST_LIMIT
359 #define PY_CPICKLE_FAST_LIMIT 50
362 static PyTypeObject Picklertype
;
364 typedef struct Unpicklerobject
{
375 PyObject
*last_string
;
379 Py_ssize_t (*read_func
)(struct Unpicklerobject
*, char **, Py_ssize_t
);
380 Py_ssize_t (*readline_func
)(struct Unpicklerobject
*, char **);
383 PyObject
*find_class
;
386 static PyTypeObject Unpicklertype
;
388 /* Forward decls that need the above structs */
389 static int save(Picklerobject
*, PyObject
*, int);
390 static int put2(Picklerobject
*, PyObject
*);
394 cPickle_ErrFormat(PyObject
*ErrType
, char *stringformat
, char *format
, ...)
397 PyObject
*args
=0, *retval
=0;
398 va_start(va
, format
);
400 if (format
) args
= Py_VaBuildValue(format
, va
);
402 if (format
&& ! args
) return NULL
;
403 if (stringformat
&& !(retval
=PyString_FromString(stringformat
)))
409 v
=PyString_Format(retval
, args
);
412 if (! v
) return NULL
;
417 if (args
) retval
=args
;
419 PyErr_SetObject(ErrType
,Py_None
);
422 PyErr_SetObject(ErrType
,retval
);
428 write_file(Picklerobject
*self
, const char *s
, Py_ssize_t n
)
430 size_t nbyteswritten
;
437 /* String too large */
441 PyFile_IncUseCount((PyFileObject
*)self
->file
);
442 Py_BEGIN_ALLOW_THREADS
443 nbyteswritten
= fwrite(s
, sizeof(char), n
, self
->fp
);
445 PyFile_DecUseCount((PyFileObject
*)self
->file
);
446 if (nbyteswritten
!= (size_t)n
) {
447 PyErr_SetFromErrno(PyExc_IOError
);
455 write_cStringIO(Picklerobject
*self
, const char *s
, Py_ssize_t n
)
461 if (PycStringIO
->cwrite((PyObject
*)self
->file
, s
, n
) != n
) {
469 write_none(Picklerobject
*self
, const char *s
, Py_ssize_t n
)
471 if (s
== NULL
) return 0;
472 if (n
> INT_MAX
) return -1;
477 write_other(Picklerobject
*self
, const char *s
, Py_ssize_t _n
)
479 PyObject
*py_str
= 0, *junk
= 0;
486 if (!( self
->buf_size
)) return 0;
487 py_str
= PyString_FromStringAndSize(self
->write_buf
,
493 if (self
->buf_size
&& (n
+ self
->buf_size
) > WRITE_BUF_SIZE
) {
494 if (write_other(self
, NULL
, 0) < 0)
498 if (n
> WRITE_BUF_SIZE
) {
500 PyString_FromStringAndSize(s
, n
)))
504 memcpy(self
->write_buf
+ self
->buf_size
, s
, n
);
511 /* object with write method */
512 ARG_TUP(self
, py_str
);
514 junk
= PyObject_Call(self
->write
, self
->arg
, NULL
);
517 if (junk
) Py_DECREF(junk
);
521 PDATA_PUSH(self
->file
, py_str
, -1);
529 read_file(Unpicklerobject
*self
, char **s
, Py_ssize_t n
)
533 if (self
->buf_size
== 0) {
536 size
= ((n
< 32) ? 32 : n
);
537 if (!( self
->buf
= (char *)malloc(size
))) {
542 self
->buf_size
= size
;
544 else if (n
> self
->buf_size
) {
545 char *newbuf
= (char *)realloc(self
->buf
, n
);
554 PyFile_IncUseCount((PyFileObject
*)self
->file
);
555 Py_BEGIN_ALLOW_THREADS
556 nbytesread
= fread(self
->buf
, sizeof(char), n
, self
->fp
);
558 PyFile_DecUseCount((PyFileObject
*)self
->file
);
559 if (nbytesread
!= (size_t)n
) {
560 if (feof(self
->fp
)) {
561 PyErr_SetNone(PyExc_EOFError
);
565 PyErr_SetFromErrno(PyExc_IOError
);
576 readline_file(Unpicklerobject
*self
, char **s
)
580 if (self
->buf_size
== 0) {
581 if (!( self
->buf
= (char *)malloc(40))) {
592 for (; i
< (self
->buf_size
- 1); i
++) {
593 if (feof(self
->fp
) ||
594 (self
->buf
[i
] = getc(self
->fp
)) == '\n') {
595 self
->buf
[i
+ 1] = '\0';
600 bigger
= self
->buf_size
<< 1;
601 if (bigger
<= 0) { /* overflow */
605 newbuf
= (char *)realloc(self
->buf
, bigger
);
611 self
->buf_size
= bigger
;
617 read_cStringIO(Unpicklerobject
*self
, char **s
, Py_ssize_t n
)
621 if (PycStringIO
->cread((PyObject
*)self
->file
, &ptr
, n
) != n
) {
622 PyErr_SetNone(PyExc_EOFError
);
633 readline_cStringIO(Unpicklerobject
*self
, char **s
)
638 if ((n
= PycStringIO
->creadline((PyObject
*)self
->file
, &ptr
)) < 0) {
649 read_other(Unpicklerobject
*self
, char **s
, Py_ssize_t n
)
651 PyObject
*bytes
, *str
=0;
653 if (!( bytes
= PyInt_FromSsize_t(n
))) return -1;
655 ARG_TUP(self
, bytes
);
657 str
= PyObject_Call(self
->read
, self
->arg
, NULL
);
660 if (! str
) return -1;
662 Py_XDECREF(self
->last_string
);
663 self
->last_string
= str
;
665 if (! (*s
= PyString_AsString(str
))) return -1;
667 if (PyString_GET_SIZE(str
) != n
) {
668 PyErr_SetNone(PyExc_EOFError
);
677 readline_other(Unpicklerobject
*self
, char **s
)
682 if (!( str
= PyObject_CallObject(self
->readline
, empty_tuple
))) {
686 if ((str_size
= PyString_Size(str
)) < 0)
689 Py_XDECREF(self
->last_string
);
690 self
->last_string
= str
;
692 if (! (*s
= PyString_AsString(str
)))
698 /* Copy the first n bytes from s into newly malloc'ed memory, plus a
699 * trailing 0 byte. Return a pointer to that, or NULL if out of memory.
700 * The caller is responsible for free()'ing the return value.
703 pystrndup(const char *s
, int n
)
705 char *r
= (char *)malloc(n
+1);
707 return (char*)PyErr_NoMemory();
715 get(Picklerobject
*self
, PyObject
*id
)
717 PyObject
*value
, *mv
;
722 if (!( mv
= PyDict_GetItem(self
->memo
, id
))) {
723 PyErr_SetObject(PyExc_KeyError
, id
);
727 if (!( value
= PyTuple_GetItem(mv
, 0)))
730 if (!( PyInt_Check(value
))) {
731 PyErr_SetString(PicklingError
, "no int where int expected in memo");
734 c_value
= PyInt_AS_LONG((PyIntObject
*)value
);
738 PyOS_snprintf(s
+ 1, sizeof(s
) - 1, "%ld\n", c_value
);
741 else if (Pdata_Check(self
->file
)) {
742 if (write_other(self
, NULL
, 0) < 0) return -1;
743 PDATA_APPEND(self
->file
, mv
, -1);
749 s
[1] = (int)(c_value
& 0xff);
754 s
[1] = (int)(c_value
& 0xff);
755 s
[2] = (int)((c_value
>> 8) & 0xff);
756 s
[3] = (int)((c_value
>> 16) & 0xff);
757 s
[4] = (int)((c_value
>> 24) & 0xff);
762 if (self
->write_func(self
, s
, len
) < 0)
770 put(Picklerobject
*self
, PyObject
*ob
)
772 if (Py_REFCNT(ob
) < 2 || self
->fast
)
775 return put2(self
, ob
);
780 put2(Picklerobject
*self
, PyObject
*ob
)
786 PyObject
*py_ob_id
= 0, *memo_len
= 0, *t
= 0;
791 if ((p
= PyDict_Size(self
->memo
)) < 0)
794 /* Make sure memo keys are positive! */
796 * XXX And does "positive" really mean non-negative?
797 * XXX pickle.py starts with PUT index 0, not 1. This makes for
798 * XXX gratuitous differences between the pickling modules.
802 if (!( py_ob_id
= PyLong_FromVoidPtr(ob
)))
805 if (!( memo_len
= PyInt_FromLong(p
)))
808 if (!( t
= PyTuple_New(2)))
811 PyTuple_SET_ITEM(t
, 0, memo_len
);
813 PyTuple_SET_ITEM(t
, 1, ob
);
816 if (PyDict_SetItem(self
->memo
, py_ob_id
, t
) < 0)
821 PyOS_snprintf(c_str
+ 1, sizeof(c_str
) - 1, "%d\n", p
);
824 else if (Pdata_Check(self
->file
)) {
825 if (write_other(self
, NULL
, 0) < 0) return -1;
826 PDATA_APPEND(self
->file
, memo_len
, -1);
827 res
=0; /* Job well done ;) */
832 c_str
[0] = LONG_BINPUT
;
833 c_str
[1] = (int)(p
& 0xff);
834 c_str
[2] = (int)((p
>> 8) & 0xff);
835 c_str
[3] = (int)((p
>> 16) & 0xff);
836 c_str
[4] = (int)((p
>> 24) & 0xff);
846 if (self
->write_func(self
, c_str
, len
) < 0)
852 Py_XDECREF(py_ob_id
);
853 Py_XDECREF(memo_len
);
860 whichmodule(PyObject
*global
, PyObject
*global_name
)
863 PyObject
*module
= 0, *modules_dict
= 0,
864 *global_name_attr
= 0, *name
= 0;
866 module
= PyObject_GetAttrString(global
, "__module__");
869 if (PyErr_ExceptionMatches(PyExc_AttributeError
))
874 if (!( modules_dict
= PySys_GetObject("modules")))
878 while ((j
= PyDict_Next(modules_dict
, &i
, &name
, &module
))) {
880 if (PyObject_Compare(name
, __main___str
)==0) continue;
882 global_name_attr
= PyObject_GetAttr(module
, global_name
);
883 if (!global_name_attr
) {
884 if (PyErr_ExceptionMatches(PyExc_AttributeError
))
891 if (global_name_attr
!= global
) {
892 Py_DECREF(global_name_attr
);
896 Py_DECREF(global_name_attr
);
901 /* The following implements the rule in pickle.py added in 1.5
902 that used __main__ if no module is found. I don't actually
915 fast_save_enter(Picklerobject
*self
, PyObject
*obj
)
917 /* if fast_container < 0, we're doing an error exit. */
918 if (++self
->fast_container
>= PY_CPICKLE_FAST_LIMIT
) {
919 PyObject
*key
= NULL
;
920 if (self
->fast_memo
== NULL
) {
921 self
->fast_memo
= PyDict_New();
922 if (self
->fast_memo
== NULL
) {
923 self
->fast_container
= -1;
927 key
= PyLong_FromVoidPtr(obj
);
930 if (PyDict_GetItem(self
->fast_memo
, key
)) {
932 PyErr_Format(PyExc_ValueError
,
933 "fast mode: can't pickle cyclic objects "
934 "including object type %s at %p",
935 Py_TYPE(obj
)->tp_name
, obj
);
936 self
->fast_container
= -1;
939 if (PyDict_SetItem(self
->fast_memo
, key
, Py_None
) < 0) {
941 self
->fast_container
= -1;
950 fast_save_leave(Picklerobject
*self
, PyObject
*obj
)
952 if (self
->fast_container
-- >= PY_CPICKLE_FAST_LIMIT
) {
953 PyObject
*key
= PyLong_FromVoidPtr(obj
);
956 if (PyDict_DelItem(self
->fast_memo
, key
) < 0) {
966 save_none(Picklerobject
*self
, PyObject
*args
)
968 static char none
= NONE
;
969 if (self
->write_func(self
, &none
, 1) < 0)
976 save_bool(Picklerobject
*self
, PyObject
*args
)
978 static const char *buf
[2] = {FALSE
, TRUE
};
979 static char len
[2] = {sizeof(FALSE
)-1, sizeof(TRUE
)-1};
980 long l
= PyInt_AS_LONG((PyIntObject
*)args
);
982 if (self
->proto
>= 2) {
983 char opcode
= l
? NEWTRUE
: NEWFALSE
;
984 if (self
->write_func(self
, &opcode
, 1) < 0)
987 else if (self
->write_func(self
, buf
[l
], len
[l
]) < 0)
993 save_int(Picklerobject
*self
, PyObject
*args
)
996 long l
= PyInt_AS_LONG((PyIntObject
*)args
);
1005 /* Text-mode pickle, or long too big to fit in the 4-byte
1006 * signed BININT format: store as a string.
1009 PyOS_snprintf(c_str
+ 1, sizeof(c_str
) - 1, "%ld\n", l
);
1010 if (self
->write_func(self
, c_str
, strlen(c_str
)) < 0)
1014 /* Binary pickle and l fits in a signed 4-byte int. */
1015 c_str
[1] = (int)( l
& 0xff);
1016 c_str
[2] = (int)((l
>> 8) & 0xff);
1017 c_str
[3] = (int)((l
>> 16) & 0xff);
1018 c_str
[4] = (int)((l
>> 24) & 0xff);
1020 if ((c_str
[4] == 0) && (c_str
[3] == 0)) {
1021 if (c_str
[2] == 0) {
1035 if (self
->write_func(self
, c_str
, len
) < 0)
1044 save_long(Picklerobject
*self
, PyObject
*args
)
1048 PyObject
*repr
= NULL
;
1050 static char l
= LONG
;
1052 if (self
->proto
>= 2) {
1053 /* Linear-time pickling. */
1056 unsigned char *pdata
;
1059 int sign
= _PyLong_Sign(args
);
1062 /* It's 0 -- an empty bytestring. */
1065 i
= self
->write_func(self
, c_str
, 2);
1066 if (i
< 0) goto finally
;
1070 nbits
= _PyLong_NumBits(args
);
1071 if (nbits
== (size_t)-1 && PyErr_Occurred())
1073 /* How many bytes do we need? There are nbits >> 3 full
1074 * bytes of data, and nbits & 7 leftover bits. If there
1075 * are any leftover bits, then we clearly need another
1076 * byte. Wnat's not so obvious is that we *probably*
1077 * need another byte even if there aren't any leftovers:
1078 * the most-significant bit of the most-significant byte
1079 * acts like a sign bit, and it's usually got a sense
1080 * opposite of the one we need. The exception is longs
1081 * of the form -(2**(8*j-1)) for j > 0. Such a long is
1082 * its own 256's-complement, so has the right sign bit
1083 * even without the extra byte. That's a pain to check
1084 * for in advance, though, so we always grab an extra
1085 * byte at the start, and cut it back later if possible.
1087 nbytes
= (nbits
>> 3) + 1;
1088 if (nbytes
> INT_MAX
) {
1089 PyErr_SetString(PyExc_OverflowError
, "long too large "
1093 repr
= PyString_FromStringAndSize(NULL
, (int)nbytes
);
1094 if (repr
== NULL
) goto finally
;
1095 pdata
= (unsigned char *)PyString_AS_STRING(repr
);
1096 i
= _PyLong_AsByteArray((PyLongObject
*)args
,
1098 1 /* little endian */, 1 /* signed */);
1099 if (i
< 0) goto finally
;
1100 /* If the long is negative, this may be a byte more than
1101 * needed. This is so iff the MSB is all redundant sign
1104 if (sign
< 0 && nbytes
> 1 && pdata
[nbytes
- 1] == 0xff &&
1105 (pdata
[nbytes
- 2] & 0x80) != 0)
1110 c_str
[1] = (char)nbytes
;
1116 for (i
= 1; i
< 5; i
++) {
1117 c_str
[i
] = (char)(size
& 0xff);
1122 i
= self
->write_func(self
, c_str
, size
);
1123 if (i
< 0) goto finally
;
1124 i
= self
->write_func(self
, (char *)pdata
, (int)nbytes
);
1125 if (i
< 0) goto finally
;
1130 /* proto < 2: write the repr and newline. This is quadratic-time
1131 * (in the number of digits), in both directions.
1133 if (!( repr
= PyObject_Repr(args
)))
1136 if ((size
= PyString_Size(repr
)) < 0)
1139 if (self
->write_func(self
, &l
, 1) < 0)
1142 if (self
->write_func(self
,
1143 PyString_AS_STRING((PyStringObject
*)repr
),
1147 if (self
->write_func(self
, "\n", 1) < 0)
1159 save_float(Picklerobject
*self
, PyObject
*args
)
1161 double x
= PyFloat_AS_DOUBLE((PyFloatObject
*)args
);
1166 if (_PyFloat_Pack8(x
, (unsigned char *)&str
[1], 0) < 0)
1168 if (self
->write_func(self
, str
, 9) < 0)
1176 if (self
->write_func(self
, &op
, 1) < 0)
1179 buf
= PyOS_double_to_string(x
, 'g', 17, 0, NULL
);
1185 if (self
->write_func(self
, buf
, strlen(buf
)) < 0)
1188 if (self
->write_func(self
, "\n", 1) < 0)
1202 save_string(Picklerobject
*self
, PyObject
*args
, int doput
)
1207 if ((size
= PyString_Size(args
)) < 0)
1213 static char string
= STRING
;
1215 if (!( repr
= PyObject_Repr(args
)))
1218 if ((len
= PyString_Size(repr
)) < 0)
1220 repr_str
= PyString_AS_STRING((PyStringObject
*)repr
);
1222 if (self
->write_func(self
, &string
, 1) < 0)
1225 if (self
->write_func(self
, repr_str
, len
) < 0)
1228 if (self
->write_func(self
, "\n", 1) < 0)
1238 c_str
[0] = SHORT_BINSTRING
;
1242 else if (size
<= INT_MAX
) {
1243 c_str
[0] = BINSTRING
;
1244 for (i
= 1; i
< 5; i
++)
1245 c_str
[i
] = (int)(size
>> ((i
- 1) * 8));
1249 return -1; /* string too large */
1251 if (self
->write_func(self
, c_str
, len
) < 0)
1254 if (size
> 128 && Pdata_Check(self
->file
)) {
1255 if (write_other(self
, NULL
, 0) < 0) return -1;
1256 PDATA_APPEND(self
->file
, args
, -1);
1259 if (self
->write_func(self
,
1261 (PyStringObject
*)args
),
1268 if (put(self
, args
) < 0)
1279 #ifdef Py_USING_UNICODE
1280 /* A copy of PyUnicode_EncodeRawUnicodeEscape() that also translates
1281 backslash and newline characters to \uXXXX escapes. */
1283 modified_EncodeRawUnicodeEscape(const Py_UNICODE
*s
, Py_ssize_t size
)
1289 static const char *hexdigit
= "0123456789abcdef";
1290 #ifdef Py_UNICODE_WIDE
1291 const Py_ssize_t expandsize
= 10;
1293 const Py_ssize_t expandsize
= 6;
1296 if (size
> PY_SSIZE_T_MAX
/ expandsize
)
1297 return PyErr_NoMemory();
1299 repr
= PyString_FromStringAndSize(NULL
, expandsize
* size
);
1305 p
= q
= PyString_AS_STRING(repr
);
1306 while (size
-- > 0) {
1307 Py_UNICODE ch
= *s
++;
1308 #ifdef Py_UNICODE_WIDE
1309 /* Map 32-bit characters to '\Uxxxxxxxx' */
1310 if (ch
>= 0x10000) {
1313 *p
++ = hexdigit
[(ch
>> 28) & 0xf];
1314 *p
++ = hexdigit
[(ch
>> 24) & 0xf];
1315 *p
++ = hexdigit
[(ch
>> 20) & 0xf];
1316 *p
++ = hexdigit
[(ch
>> 16) & 0xf];
1317 *p
++ = hexdigit
[(ch
>> 12) & 0xf];
1318 *p
++ = hexdigit
[(ch
>> 8) & 0xf];
1319 *p
++ = hexdigit
[(ch
>> 4) & 0xf];
1320 *p
++ = hexdigit
[ch
& 15];
1324 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
1325 if (ch
>= 0xD800 && ch
< 0xDC00) {
1331 if (ch2
>= 0xDC00 && ch2
<= 0xDFFF) {
1332 ucs
= (((ch
& 0x03FF) << 10) | (ch2
& 0x03FF)) + 0x00010000;
1335 *p
++ = hexdigit
[(ucs
>> 28) & 0xf];
1336 *p
++ = hexdigit
[(ucs
>> 24) & 0xf];
1337 *p
++ = hexdigit
[(ucs
>> 20) & 0xf];
1338 *p
++ = hexdigit
[(ucs
>> 16) & 0xf];
1339 *p
++ = hexdigit
[(ucs
>> 12) & 0xf];
1340 *p
++ = hexdigit
[(ucs
>> 8) & 0xf];
1341 *p
++ = hexdigit
[(ucs
>> 4) & 0xf];
1342 *p
++ = hexdigit
[ucs
& 0xf];
1345 /* Fall through: isolated surrogates are copied as-is */
1350 /* Map 16-bit characters to '\uxxxx' */
1351 if (ch
>= 256 || ch
== '\\' || ch
== '\n') {
1354 *p
++ = hexdigit
[(ch
>> 12) & 0xf];
1355 *p
++ = hexdigit
[(ch
>> 8) & 0xf];
1356 *p
++ = hexdigit
[(ch
>> 4) & 0xf];
1357 *p
++ = hexdigit
[ch
& 15];
1359 /* Copy everything else as-is */
1364 _PyString_Resize(&repr
, p
- q
);
1369 save_unicode(Picklerobject
*self
, PyObject
*args
, int doput
)
1371 Py_ssize_t size
, len
;
1374 if (!PyUnicode_Check(args
))
1379 static char string
= UNICODE
;
1381 repr
= modified_EncodeRawUnicodeEscape(
1382 PyUnicode_AS_UNICODE(args
), PyUnicode_GET_SIZE(args
));
1386 if ((len
= PyString_Size(repr
)) < 0)
1388 repr_str
= PyString_AS_STRING((PyStringObject
*)repr
);
1390 if (self
->write_func(self
, &string
, 1) < 0)
1393 if (self
->write_func(self
, repr_str
, len
) < 0)
1396 if (self
->write_func(self
, "\n", 1) < 0)
1405 if (!( repr
= PyUnicode_AsUTF8String(args
)))
1408 if ((size
= PyString_Size(repr
)) < 0)
1411 return -1; /* string too large */
1413 c_str
[0] = BINUNICODE
;
1414 for (i
= 1; i
< 5; i
++)
1415 c_str
[i
] = (int)(size
>> ((i
- 1) * 8));
1418 if (self
->write_func(self
, c_str
, len
) < 0)
1421 if (size
> 128 && Pdata_Check(self
->file
)) {
1422 if (write_other(self
, NULL
, 0) < 0)
1424 PDATA_APPEND(self
->file
, repr
, -1);
1427 if (self
->write_func(self
, PyString_AS_STRING(repr
),
1436 if (put(self
, args
) < 0)
1447 /* A helper for save_tuple. Push the len elements in tuple t on the stack. */
1449 store_tuple_elements(Picklerobject
*self
, PyObject
*t
, int len
)
1452 int res
= -1; /* guilty until proved innocent */
1454 assert(PyTuple_Size(t
) == len
);
1456 for (i
= 0; i
< len
; i
++) {
1457 PyObject
*element
= PyTuple_GET_ITEM(t
, i
);
1459 if (element
== NULL
)
1461 if (save(self
, element
, 0) < 0)
1470 /* Tuples are ubiquitous in the pickle protocols, so many techniques are
1471 * used across protocols to minimize the space needed to pickle them.
1472 * Tuples are also the only builtin immutable type that can be recursive
1473 * (a tuple can be reached from itself), and that requires some subtle
1474 * magic so that it works in all cases. IOW, this is a long routine.
1477 save_tuple(Picklerobject
*self
, PyObject
*args
)
1479 PyObject
*py_tuple_id
= NULL
;
1483 static char tuple
= TUPLE
;
1484 static char pop
= POP
;
1485 static char pop_mark
= POP_MARK
;
1486 static char len2opcode
[] = {EMPTY_TUPLE
, TUPLE1
, TUPLE2
, TUPLE3
};
1488 if ((len
= PyTuple_Size(args
)) < 0)
1495 c_str
[0] = EMPTY_TUPLE
;
1503 if (self
->write_func(self
, c_str
, len
) >= 0)
1505 /* Don't memoize an empty tuple. */
1509 /* A non-empty tuple. */
1511 /* id(tuple) isn't in the memo now. If it shows up there after
1512 * saving the tuple elements, the tuple must be recursive, in
1513 * which case we'll pop everything we put on the stack, and fetch
1514 * its value from the memo.
1516 py_tuple_id
= PyLong_FromVoidPtr(args
);
1517 if (py_tuple_id
== NULL
)
1520 if (len
<= 3 && self
->proto
>= 2) {
1521 /* Use TUPLE{1,2,3} opcodes. */
1522 if (store_tuple_elements(self
, args
, len
) < 0)
1524 if (PyDict_GetItem(self
->memo
, py_tuple_id
)) {
1525 /* pop the len elements */
1526 for (i
= 0; i
< len
; ++i
)
1527 if (self
->write_func(self
, &pop
, 1) < 0)
1529 /* fetch from memo */
1530 if (get(self
, py_tuple_id
) < 0)
1535 /* Not recursive. */
1536 if (self
->write_func(self
, len2opcode
+ len
, 1) < 0)
1541 /* proto < 2 and len > 0, or proto >= 2 and len > 3.
1542 * Generate MARK elt1 elt2 ... TUPLE
1544 if (self
->write_func(self
, &MARKv
, 1) < 0)
1547 if (store_tuple_elements(self
, args
, len
) < 0)
1550 if (PyDict_GetItem(self
->memo
, py_tuple_id
)) {
1551 /* pop the stack stuff we pushed */
1553 if (self
->write_func(self
, &pop_mark
, 1) < 0)
1557 /* Note that we pop one more than len, to remove
1560 for (i
= 0; i
<= len
; i
++)
1561 if (self
->write_func(self
, &pop
, 1) < 0)
1564 /* fetch from memo */
1565 if (get(self
, py_tuple_id
) >= 0)
1570 /* Not recursive. */
1571 if (self
->write_func(self
, &tuple
, 1) < 0)
1575 if (put(self
, args
) >= 0)
1579 Py_XDECREF(py_tuple_id
);
1583 /* iter is an iterator giving items, and we batch up chunks of
1584 * MARK item item ... item APPENDS
1585 * opcode sequences. Calling code should have arranged to first create an
1586 * empty list, or list-like object, for the APPENDS to operate on.
1587 * Returns 0 on success, <0 on error.
1590 batch_list(Picklerobject
*self
, PyObject
*iter
)
1592 PyObject
*obj
= NULL
;
1593 PyObject
*firstitem
= NULL
;
1596 static char append
= APPEND
;
1597 static char appends
= APPENDS
;
1599 assert(iter
!= NULL
);
1601 if (self
->proto
== 0) {
1602 /* APPENDS isn't available; do one at a time. */
1604 obj
= PyIter_Next(iter
);
1606 if (PyErr_Occurred())
1610 i
= save(self
, obj
, 0);
1614 if (self
->write_func(self
, &append
, 1) < 0)
1620 /* proto > 0: write in batches of BATCHSIZE. */
1622 /* Get first item */
1623 firstitem
= PyIter_Next(iter
);
1624 if (firstitem
== NULL
) {
1625 if (PyErr_Occurred())
1628 /* nothing more to add */
1632 /* Try to get a second item */
1633 obj
= PyIter_Next(iter
);
1635 if (PyErr_Occurred())
1638 /* Only one item to write */
1639 if (save(self
, firstitem
, 0) < 0)
1641 if (self
->write_func(self
, &append
, 1) < 0)
1643 Py_CLEAR(firstitem
);
1647 /* More than one item to write */
1649 /* Pump out MARK, items, APPENDS. */
1650 if (self
->write_func(self
, &MARKv
, 1) < 0)
1653 if (save(self
, firstitem
, 0) < 0)
1655 Py_CLEAR(firstitem
);
1658 /* Fetch and save up to BATCHSIZE items */
1660 if (save(self
, obj
, 0) < 0)
1668 obj
= PyIter_Next(iter
);
1670 if (PyErr_Occurred())
1676 if (self
->write_func(self
, &appends
, 1) < 0)
1679 } while (n
== BATCHSIZE
);
1683 Py_XDECREF(firstitem
);
1689 save_list(Picklerobject
*self
, PyObject
*args
)
1696 if (self
->fast
&& !fast_save_enter(self
, args
))
1699 /* Create an empty list. */
1710 if (self
->write_func(self
, s
, len
) < 0)
1713 /* Get list length, and bow out early if empty. */
1714 if ((len
= PyList_Size(args
)) < 0)
1719 if (put(self
, args
) >= 0)
1723 if (put2(self
, args
) < 0)
1726 /* Materialize the list elements. */
1727 iter
= PyObject_GetIter(args
);
1731 if (Py_EnterRecursiveCall(" while pickling an object") == 0)
1733 res
= batch_list(self
, iter
);
1734 Py_LeaveRecursiveCall();
1739 if (self
->fast
&& !fast_save_leave(self
, args
))
1746 /* iter is an iterator giving (key, value) pairs, and we batch up chunks of
1747 * MARK key value ... key value SETITEMS
1748 * opcode sequences. Calling code should have arranged to first create an
1749 * empty dict, or dict-like object, for the SETITEMS to operate on.
1750 * Returns 0 on success, <0 on error.
1752 * This is very much like batch_list(). The difference between saving
1753 * elements directly, and picking apart two-tuples, is so long-winded at
1754 * the C level, though, that attempts to combine these routines were too
1758 batch_dict(Picklerobject
*self
, PyObject
*iter
)
1761 PyObject
*firstitem
= NULL
;
1764 static char setitem
= SETITEM
;
1765 static char setitems
= SETITEMS
;
1767 assert(iter
!= NULL
);
1769 if (self
->proto
== 0) {
1770 /* SETITEMS isn't available; do one at a time. */
1772 p
= PyIter_Next(iter
);
1774 if (PyErr_Occurred())
1778 if (!PyTuple_Check(p
) || PyTuple_Size(p
) != 2) {
1779 PyErr_SetString(PyExc_TypeError
, "dict items "
1780 "iterator must return 2-tuples");
1783 i
= save(self
, PyTuple_GET_ITEM(p
, 0), 0);
1785 i
= save(self
, PyTuple_GET_ITEM(p
, 1), 0);
1789 if (self
->write_func(self
, &setitem
, 1) < 0)
1795 /* proto > 0: write in batches of BATCHSIZE. */
1797 /* Get first item */
1798 firstitem
= PyIter_Next(iter
);
1799 if (firstitem
== NULL
) {
1800 if (PyErr_Occurred())
1803 /* nothing more to add */
1806 if (!PyTuple_Check(firstitem
) || PyTuple_Size(firstitem
) != 2) {
1807 PyErr_SetString(PyExc_TypeError
, "dict items "
1808 "iterator must return 2-tuples");
1812 /* Try to get a second item */
1813 p
= PyIter_Next(iter
);
1815 if (PyErr_Occurred())
1818 /* Only one item to write */
1819 if (save(self
, PyTuple_GET_ITEM(firstitem
, 0), 0) < 0)
1821 if (save(self
, PyTuple_GET_ITEM(firstitem
, 1), 0) < 0)
1823 if (self
->write_func(self
, &setitem
, 1) < 0)
1825 Py_CLEAR(firstitem
);
1829 /* More than one item to write */
1831 /* Pump out MARK, items, SETITEMS. */
1832 if (self
->write_func(self
, &MARKv
, 1) < 0)
1835 if (save(self
, PyTuple_GET_ITEM(firstitem
, 0), 0) < 0)
1837 if (save(self
, PyTuple_GET_ITEM(firstitem
, 1), 0) < 0)
1839 Py_CLEAR(firstitem
);
1842 /* Fetch and save up to BATCHSIZE items */
1844 if (!PyTuple_Check(p
) || PyTuple_Size(p
) != 2) {
1845 PyErr_SetString(PyExc_TypeError
, "dict items "
1846 "iterator must return 2-tuples");
1849 if (save(self
, PyTuple_GET_ITEM(p
, 0), 0) < 0)
1851 if (save(self
, PyTuple_GET_ITEM(p
, 1), 0) < 0)
1859 p
= PyIter_Next(iter
);
1861 if (PyErr_Occurred())
1867 if (self
->write_func(self
, &setitems
, 1) < 0)
1870 } while (n
== BATCHSIZE
);
1874 Py_XDECREF(firstitem
);
1879 /* This is a variant of batch_dict() above that specializes for dicts, with no
1880 * support for dict subclasses. Like batch_dict(), we batch up chunks of
1881 * MARK key value ... key value SETITEMS
1882 * opcode sequences. Calling code should have arranged to first create an
1883 * empty dict, or dict-like object, for the SETITEMS to operate on.
1884 * Returns 0 on success, -1 on error.
1886 * Note that this currently doesn't work for protocol 0.
1889 batch_dict_exact(Picklerobject
*self
, PyObject
*obj
)
1891 PyObject
*key
= NULL
, *value
= NULL
;
1893 Py_ssize_t dict_size
, ppos
= 0;
1895 static char setitem
= SETITEM
;
1896 static char setitems
= SETITEMS
;
1898 assert(obj
!= NULL
);
1899 assert(self
->proto
> 0);
1901 dict_size
= PyDict_Size(obj
);
1903 /* Special-case len(d) == 1 to save space. */
1904 if (dict_size
== 1) {
1905 PyDict_Next(obj
, &ppos
, &key
, &value
);
1906 if (save(self
, key
, 0) < 0)
1908 if (save(self
, value
, 0) < 0)
1910 if (self
->write_func(self
, &setitem
, 1) < 0)
1915 /* Write in batches of BATCHSIZE. */
1918 if (self
->write_func(self
, &MARKv
, 1) < 0)
1920 while (PyDict_Next(obj
, &ppos
, &key
, &value
)) {
1921 if (save(self
, key
, 0) < 0)
1923 if (save(self
, value
, 0) < 0)
1925 if (++i
== BATCHSIZE
)
1928 if (self
->write_func(self
, &setitems
, 1) < 0)
1930 if (PyDict_Size(obj
) != dict_size
) {
1933 "dictionary changed size during iteration");
1937 } while (i
== BATCHSIZE
);
1942 save_dict(Picklerobject
*self
, PyObject
*args
)
1948 if (self
->fast
&& !fast_save_enter(self
, args
))
1951 /* Create an empty dict. */
1962 if (self
->write_func(self
, s
, len
) < 0)
1965 /* Get dict size, and bow out early if empty. */
1966 if ((len
= PyDict_Size(args
)) < 0)
1970 if (put(self
, args
) >= 0)
1974 if (put2(self
, args
) < 0)
1977 /* Materialize the dict items. */
1978 if (PyDict_CheckExact(args
) && self
->proto
> 0) {
1979 /* We can take certain shortcuts if we know this is a dict and
1980 not a dict subclass. */
1981 if (Py_EnterRecursiveCall(" while pickling an object") == 0) {
1982 res
= batch_dict_exact(self
, args
);
1983 Py_LeaveRecursiveCall();
1986 PyObject
*iter
= PyObject_CallMethod(args
, "iteritems", "()");
1989 if (Py_EnterRecursiveCall(" while pickling an object") == 0) {
1990 res
= batch_dict(self
, iter
);
1991 Py_LeaveRecursiveCall();
1997 if (self
->fast
&& !fast_save_leave(self
, args
))
2005 save_inst(Picklerobject
*self
, PyObject
*args
)
2007 PyObject
*class = 0, *module
= 0, *name
= 0, *state
= 0,
2008 *getinitargs_func
= 0, *getstate_func
= 0, *class_args
= 0;
2009 char *module_str
, *name_str
;
2010 int module_size
, name_size
, res
= -1;
2012 static char inst
= INST
, obj
= OBJ
, build
= BUILD
;
2014 if (self
->fast
&& !fast_save_enter(self
, args
))
2017 if (self
->write_func(self
, &MARKv
, 1) < 0)
2020 if (!( class = PyObject_GetAttr(args
, __class___str
)))
2024 if (save(self
, class, 0) < 0)
2028 if ((getinitargs_func
= PyObject_GetAttr(args
, __getinitargs___str
))) {
2029 PyObject
*element
= 0;
2033 PyObject_Call(getinitargs_func
, empty_tuple
, NULL
)))
2036 if ((len
= PyObject_Size(class_args
)) < 0)
2039 for (i
= 0; i
< len
; i
++) {
2040 if (!( element
= PySequence_GetItem(class_args
, i
)))
2043 if (save(self
, element
, 0) < 0) {
2052 if (PyErr_ExceptionMatches(PyExc_AttributeError
))
2059 if (!( name
= ((PyClassObject
*)class)->cl_name
)) {
2060 PyErr_SetString(PicklingError
, "class has no name");
2064 if (!( module
= whichmodule(class, name
)))
2068 if ((module_size
= PyString_Size(module
)) < 0 ||
2069 (name_size
= PyString_Size(name
)) < 0)
2072 module_str
= PyString_AS_STRING((PyStringObject
*)module
);
2073 name_str
= PyString_AS_STRING((PyStringObject
*)name
);
2075 if (self
->write_func(self
, &inst
, 1) < 0)
2078 if (self
->write_func(self
, module_str
, module_size
) < 0)
2081 if (self
->write_func(self
, "\n", 1) < 0)
2084 if (self
->write_func(self
, name_str
, name_size
) < 0)
2087 if (self
->write_func(self
, "\n", 1) < 0)
2090 else if (self
->write_func(self
, &obj
, 1) < 0) {
2094 if ((getstate_func
= PyObject_GetAttr(args
, __getstate___str
))) {
2095 state
= PyObject_Call(getstate_func
, empty_tuple
, NULL
);
2100 if (PyErr_ExceptionMatches(PyExc_AttributeError
))
2105 if (!( state
= PyObject_GetAttr(args
, __dict___str
))) {
2106 if (PyErr_ExceptionMatches(PyExc_AttributeError
))
2115 if (!PyDict_Check(state
)) {
2116 if (put2(self
, args
) < 0)
2120 if (put(self
, args
) < 0)
2124 if (save(self
, state
, 0) < 0)
2127 if (self
->write_func(self
, &build
, 1) < 0)
2133 if (self
->fast
&& !fast_save_leave(self
, args
))
2139 Py_XDECREF(getinitargs_func
);
2140 Py_XDECREF(getstate_func
);
2141 Py_XDECREF(class_args
);
2148 save_global(Picklerobject
*self
, PyObject
*args
, PyObject
*name
)
2150 PyObject
*global_name
= 0, *module
= 0, *mod
= 0, *klass
= 0;
2151 char *name_str
, *module_str
;
2152 int module_size
, name_size
, res
= -1;
2154 static char global
= GLOBAL
;
2158 Py_INCREF(global_name
);
2161 if (!( global_name
= PyObject_GetAttr(args
, __name___str
)))
2165 if (!( module
= whichmodule(args
, global_name
)))
2168 if ((module_size
= PyString_Size(module
)) < 0 ||
2169 (name_size
= PyString_Size(global_name
)) < 0)
2172 module_str
= PyString_AS_STRING((PyStringObject
*)module
);
2173 name_str
= PyString_AS_STRING((PyStringObject
*)global_name
);
2175 /* XXX This can be doing a relative import. Clearly it shouldn't,
2176 but I don't know how to stop it. :-( */
2177 mod
= PyImport_ImportModule(module_str
);
2179 cPickle_ErrFormat(PicklingError
,
2180 "Can't pickle %s: import of module %s "
2182 "OS", args
, module
);
2185 klass
= PyObject_GetAttrString(mod
, name_str
);
2186 if (klass
== NULL
) {
2187 cPickle_ErrFormat(PicklingError
,
2188 "Can't pickle %s: attribute lookup %s.%s "
2190 "OSS", args
, module
, global_name
);
2193 if (klass
!= args
) {
2195 cPickle_ErrFormat(PicklingError
,
2196 "Can't pickle %s: it's not the same object "
2198 "OSS", args
, module
, global_name
);
2203 if (self
->proto
>= 2) {
2204 /* See whether this is in the extension registry, and if
2205 * so generate an EXT opcode.
2207 PyObject
*py_code
; /* extension code as Python object */
2208 long code
; /* extension code as C value */
2212 PyTuple_SET_ITEM(two_tuple
, 0, module
);
2213 PyTuple_SET_ITEM(two_tuple
, 1, global_name
);
2214 py_code
= PyDict_GetItem(extension_registry
, two_tuple
);
2215 if (py_code
== NULL
)
2216 goto gen_global
; /* not registered */
2218 /* Verify py_code has the right type and value. */
2219 if (!PyInt_Check(py_code
)) {
2220 cPickle_ErrFormat(PicklingError
, "Can't pickle %s: "
2221 "extension code %s isn't an integer",
2222 "OO", args
, py_code
);
2225 code
= PyInt_AS_LONG(py_code
);
2226 if (code
<= 0 || code
> 0x7fffffffL
) {
2227 cPickle_ErrFormat(PicklingError
, "Can't pickle %s: "
2228 "extension code %ld is out of range",
2233 /* Generate an EXT opcode. */
2236 c_str
[1] = (char)code
;
2239 else if (code
<= 0xffff) {
2241 c_str
[1] = (char)(code
& 0xff);
2242 c_str
[2] = (char)((code
>> 8) & 0xff);
2247 c_str
[1] = (char)(code
& 0xff);
2248 c_str
[2] = (char)((code
>> 8) & 0xff);
2249 c_str
[3] = (char)((code
>> 16) & 0xff);
2250 c_str
[4] = (char)((code
>> 24) & 0xff);
2254 if (self
->write_func(self
, c_str
, n
) >= 0)
2256 goto finally
; /* and don't memoize */
2260 if (self
->write_func(self
, &global
, 1) < 0)
2263 if (self
->write_func(self
, module_str
, module_size
) < 0)
2266 if (self
->write_func(self
, "\n", 1) < 0)
2269 if (self
->write_func(self
, name_str
, name_size
) < 0)
2272 if (self
->write_func(self
, "\n", 1) < 0)
2275 if (put(self
, args
) < 0)
2282 Py_XDECREF(global_name
);
2289 save_pers(Picklerobject
*self
, PyObject
*args
, PyObject
*f
)
2294 static char persid
= PERSID
, binpersid
= BINPERSID
;
2297 ARG_TUP(self
, args
);
2299 pid
= PyObject_Call(f
, self
->arg
, NULL
);
2302 if (! pid
) return -1;
2304 if (pid
!= Py_None
) {
2306 if (!PyString_Check(pid
)) {
2307 PyErr_SetString(PicklingError
,
2308 "persistent id must be string");
2312 if (self
->write_func(self
, &persid
, 1) < 0)
2315 if ((size
= PyString_Size(pid
)) < 0)
2318 if (self
->write_func(self
,
2320 (PyStringObject
*)pid
),
2324 if (self
->write_func(self
, "\n", 1) < 0)
2330 else if (save(self
, pid
, 1) >= 0) {
2331 if (self
->write_func(self
, &binpersid
, 1) < 0)
2348 /* We're saving ob, and args is the 2-thru-5 tuple returned by the
2349 * appropriate __reduce__ method for ob.
2352 save_reduce(Picklerobject
*self
, PyObject
*args
, PyObject
*fn
, PyObject
*ob
)
2356 PyObject
*state
= NULL
;
2357 PyObject
*listitems
= Py_None
;
2358 PyObject
*dictitems
= Py_None
;
2361 int use_newobj
= self
->proto
>= 2;
2363 static char reduce
= REDUCE
;
2364 static char build
= BUILD
;
2365 static char newobj
= NEWOBJ
;
2367 size
= PyTuple_Size(args
);
2368 if (size
< 2 || size
> 5) {
2369 cPickle_ErrFormat(PicklingError
, "tuple returned by "
2370 "%s must contain 2 through 5 elements",
2375 if (! PyArg_UnpackTuple(args
, "save_reduce", 2, 5,
2383 if (!PyTuple_Check(argtup
)) {
2384 cPickle_ErrFormat(PicklingError
, "Second element of "
2385 "tuple returned by %s must be a tuple",
2390 if (state
== Py_None
)
2393 if (listitems
== Py_None
)
2395 else if (!PyIter_Check(listitems
)) {
2396 cPickle_ErrFormat(PicklingError
, "Fourth element of "
2397 "tuple returned by %s must be an iterator, not %s",
2398 "Os", fn
, Py_TYPE(listitems
)->tp_name
);
2402 if (dictitems
== Py_None
)
2404 else if (!PyIter_Check(dictitems
)) {
2405 cPickle_ErrFormat(PicklingError
, "Fifth element of "
2406 "tuple returned by %s must be an iterator, not %s",
2407 "Os", fn
, Py_TYPE(dictitems
)->tp_name
);
2411 /* Protocol 2 special case: if callable's name is __newobj__, use
2412 * NEWOBJ. This consumes a lot of code.
2415 PyObject
*temp
= PyObject_GetAttr(callable
, __name___str
);
2418 if (PyErr_ExceptionMatches(PyExc_AttributeError
))
2425 use_newobj
= PyString_Check(temp
) &&
2426 strcmp(PyString_AS_STRING(temp
),
2433 PyObject
*newargtup
;
2436 /* Sanity checks. */
2437 n
= PyTuple_Size(argtup
);
2439 PyErr_SetString(PicklingError
, "__newobj__ arglist "
2444 cls
= PyTuple_GET_ITEM(argtup
, 0);
2445 if (! PyObject_HasAttrString(cls
, "__new__")) {
2446 PyErr_SetString(PicklingError
, "args[0] from "
2447 "__newobj__ args has no __new__");
2451 /* XXX How could ob be NULL? */
2453 PyObject
*ob_dot_class
;
2455 ob_dot_class
= PyObject_GetAttr(ob
, __class___str
);
2456 if (ob_dot_class
== NULL
) {
2457 if (PyErr_ExceptionMatches(
2458 PyExc_AttributeError
))
2463 i
= ob_dot_class
!= cls
; /* true iff a problem */
2464 Py_XDECREF(ob_dot_class
);
2466 PyErr_SetString(PicklingError
, "args[0] from "
2467 "__newobj__ args has the wrong class");
2472 /* Save the class and its __new__ arguments. */
2473 if (save(self
, cls
, 0) < 0)
2476 newargtup
= PyTuple_New(n
-1); /* argtup[1:] */
2477 if (newargtup
== NULL
)
2479 for (i
= 1; i
< n
; ++i
) {
2480 PyObject
*temp
= PyTuple_GET_ITEM(argtup
, i
);
2482 PyTuple_SET_ITEM(newargtup
, i
-1, temp
);
2484 i
= save(self
, newargtup
, 0);
2485 Py_DECREF(newargtup
);
2489 /* Add NEWOBJ opcode. */
2490 if (self
->write_func(self
, &newobj
, 1) < 0)
2494 /* Not using NEWOBJ. */
2495 if (save(self
, callable
, 0) < 0 ||
2496 save(self
, argtup
, 0) < 0 ||
2497 self
->write_func(self
, &reduce
, 1) < 0)
2502 /* XXX How can ob be NULL? */
2504 if (state
&& !PyDict_Check(state
)) {
2505 if (put2(self
, ob
) < 0)
2508 else if (put(self
, ob
) < 0)
2513 if (listitems
&& batch_list(self
, listitems
) < 0)
2516 if (dictitems
&& batch_dict(self
, dictitems
) < 0)
2520 if (save(self
, state
, 0) < 0 ||
2521 self
->write_func(self
, &build
, 1) < 0)
2529 save(Picklerobject
*self
, PyObject
*args
, int pers_save
)
2532 PyObject
*py_ob_id
= 0, *__reduce__
= 0, *t
= 0;
2536 if (Py_EnterRecursiveCall(" while pickling an object"))
2539 if (!pers_save
&& self
->pers_func
) {
2540 if ((tmp
= save_pers(self
, args
, self
->pers_func
)) != 0) {
2546 if (args
== Py_None
) {
2547 res
= save_none(self
, args
);
2551 type
= Py_TYPE(args
);
2553 switch (type
->tp_name
[0]) {
2555 if (args
== Py_False
|| args
== Py_True
) {
2556 res
= save_bool(self
, args
);
2561 if (type
== &PyInt_Type
) {
2562 res
= save_int(self
, args
);
2568 if (type
== &PyLong_Type
) {
2569 res
= save_long(self
, args
);
2575 if (type
== &PyFloat_Type
) {
2576 res
= save_float(self
, args
);
2582 if (type
== &PyTuple_Type
&& PyTuple_Size(args
) == 0) {
2583 res
= save_tuple(self
, args
);
2589 if ((type
== &PyString_Type
) && (PyString_GET_SIZE(args
) < 2)) {
2590 res
= save_string(self
, args
, 0);
2595 #ifdef Py_USING_UNICODE
2597 if ((type
== &PyUnicode_Type
) && (PyString_GET_SIZE(args
) < 2)) {
2598 res
= save_unicode(self
, args
, 0);
2605 if (Py_REFCNT(args
) > 1) {
2606 if (!( py_ob_id
= PyLong_FromVoidPtr(args
)))
2609 if (PyDict_GetItem(self
->memo
, py_ob_id
)) {
2610 if (get(self
, py_ob_id
) < 0)
2618 switch (type
->tp_name
[0]) {
2620 if (type
== &PyString_Type
) {
2621 res
= save_string(self
, args
, 1);
2626 #ifdef Py_USING_UNICODE
2628 if (type
== &PyUnicode_Type
) {
2629 res
= save_unicode(self
, args
, 1);
2636 if (type
== &PyTuple_Type
) {
2637 res
= save_tuple(self
, args
);
2640 if (type
== &PyType_Type
) {
2641 res
= save_global(self
, args
, NULL
);
2647 if (type
== &PyList_Type
) {
2648 res
= save_list(self
, args
);
2654 if (type
== &PyDict_Type
) {
2655 res
= save_dict(self
, args
);
2661 if (type
== &PyInstance_Type
) {
2662 res
= save_inst(self
, args
);
2668 if (type
== &PyClass_Type
) {
2669 res
= save_global(self
, args
, NULL
);
2675 if (type
== &PyFunction_Type
) {
2676 res
= save_global(self
, args
, NULL
);
2677 if (res
&& PyErr_ExceptionMatches(PickleError
)) {
2678 /* fall back to reduce */
2687 if (type
== &PyCFunction_Type
) {
2688 res
= save_global(self
, args
, NULL
);
2693 if (!pers_save
&& self
->inst_pers_func
) {
2694 if ((tmp
= save_pers(self
, args
, self
->inst_pers_func
)) != 0) {
2700 if (PyType_IsSubtype(type
, &PyType_Type
)) {
2701 res
= save_global(self
, args
, NULL
);
2705 /* Get a reduction callable, and call it. This may come from
2706 * copy_reg.dispatch_table, the object's __reduce_ex__ method,
2707 * or the object's __reduce__ method.
2709 __reduce__
= PyDict_GetItem(dispatch_table
, (PyObject
*)type
);
2710 if (__reduce__
!= NULL
) {
2711 Py_INCREF(__reduce__
);
2713 ARG_TUP(self
, args
);
2715 t
= PyObject_Call(__reduce__
, self
->arg
, NULL
);
2720 /* Check for a __reduce_ex__ method. */
2721 __reduce__
= PyObject_GetAttr(args
, __reduce_ex___str
);
2722 if (__reduce__
!= NULL
) {
2723 t
= PyInt_FromLong(self
->proto
);
2728 t
= PyObject_Call(__reduce__
,
2735 if (PyErr_ExceptionMatches(PyExc_AttributeError
))
2739 /* Check for a __reduce__ method. */
2740 __reduce__
= PyObject_GetAttr(args
, __reduce___str
);
2741 if (__reduce__
!= NULL
) {
2742 t
= PyObject_Call(__reduce__
,
2746 PyErr_SetObject(UnpickleableError
, args
);
2755 if (PyString_Check(t
)) {
2756 res
= save_global(self
, args
, t
);
2760 if (!PyTuple_Check(t
)) {
2761 cPickle_ErrFormat(PicklingError
, "Value returned by "
2762 "%s must be string or tuple",
2767 res
= save_reduce(self
, t
, __reduce__
, args
);
2770 Py_LeaveRecursiveCall();
2771 Py_XDECREF(py_ob_id
);
2772 Py_XDECREF(__reduce__
);
2780 dump(Picklerobject
*self
, PyObject
*args
)
2782 static char stop
= STOP
;
2784 if (self
->proto
>= 2) {
2788 assert(self
->proto
>= 0 && self
->proto
< 256);
2789 bytes
[1] = (char)self
->proto
;
2790 if (self
->write_func(self
, bytes
, 2) < 0)
2794 if (save(self
, args
, 0) < 0)
2797 if (self
->write_func(self
, &stop
, 1) < 0)
2800 if (self
->write_func(self
, NULL
, 0) < 0)
2807 Pickle_clear_memo(Picklerobject
*self
, PyObject
*args
)
2810 PyDict_Clear(self
->memo
);
2816 Pickle_getvalue(Picklerobject
*self
, PyObject
*args
)
2818 int l
, i
, rsize
, ssize
, clear
=1, lm
;
2821 char *s
, *p
, *have_get
;
2824 /* Can be called by Python code or C code */
2825 if (args
&& !PyArg_ParseTuple(args
, "|i:getvalue", &clear
))
2828 /* Check to make sure we are based on a list */
2829 if (! Pdata_Check(self
->file
)) {
2830 PyErr_SetString(PicklingError
,
2831 "Attempt to getvalue() a non-list-based pickler");
2835 /* flush write buffer */
2836 if (write_other(self
, NULL
, 0) < 0) return NULL
;
2838 data
=(Pdata
*)self
->file
;
2841 /* set up an array to hold get/put status */
2842 lm
= PyDict_Size(self
->memo
);
2843 if (lm
< 0) return NULL
;
2845 have_get
= malloc(lm
);
2846 if (have_get
== NULL
) return PyErr_NoMemory();
2847 memset(have_get
, 0, lm
);
2849 /* Scan for gets. */
2850 for (rsize
= 0, i
= l
; --i
>= 0; ) {
2853 if (PyString_Check(k
))
2854 rsize
+= PyString_GET_SIZE(k
);
2856 else if (PyInt_Check(k
)) { /* put */
2857 ik
= PyInt_AS_LONG((PyIntObject
*)k
);
2858 if (ik
>= lm
|| ik
== 0) {
2859 PyErr_SetString(PicklingError
,
2860 "Invalid get data");
2863 if (have_get
[ik
]) /* with matching get */
2864 rsize
+= ik
< 256 ? 2 : 5;
2867 else if (! (PyTuple_Check(k
) &&
2868 PyTuple_GET_SIZE(k
) == 2 &&
2869 PyInt_Check((k
= PyTuple_GET_ITEM(k
, 0))))
2871 PyErr_SetString(PicklingError
,
2872 "Unexpected data in internal list");
2877 ik
= PyInt_AS_LONG((PyIntObject
*)k
);
2878 if (ik
>= lm
|| ik
== 0) {
2879 PyErr_SetString(PicklingError
,
2880 "Invalid get data");
2884 rsize
+= ik
< 256 ? 2 : 5;
2888 /* Now generate the result */
2889 r
= PyString_FromStringAndSize(NULL
, rsize
);
2890 if (r
== NULL
) goto err
;
2891 s
= PyString_AS_STRING((PyStringObject
*)r
);
2893 for (i
= 0; i
< l
; i
++) {
2896 if (PyString_Check(k
)) {
2897 ssize
= PyString_GET_SIZE(k
);
2899 p
=PyString_AS_STRING((PyStringObject
*)k
);
2900 while (--ssize
>= 0)
2905 else if (PyTuple_Check(k
)) { /* get */
2906 ik
= PyInt_AS_LONG((PyIntObject
*)
2907 PyTuple_GET_ITEM(k
, 0));
2910 *s
++ = (int)(ik
& 0xff);
2914 *s
++ = (int)(ik
& 0xff);
2915 *s
++ = (int)((ik
>> 8) & 0xff);
2916 *s
++ = (int)((ik
>> 16) & 0xff);
2917 *s
++ = (int)((ik
>> 24) & 0xff);
2922 ik
= PyInt_AS_LONG((PyIntObject
*)k
);
2924 if (have_get
[ik
]) { /* with matching get */
2927 *s
++ = (int)(ik
& 0xff);
2931 *s
++ = (int)(ik
& 0xff);
2932 *s
++ = (int)((ik
>> 8) & 0xff);
2933 *s
++ = (int)((ik
>> 16) & 0xff);
2934 *s
++ = (int)((ik
>> 24) & 0xff);
2941 PyDict_Clear(self
->memo
);
2942 Pdata_clear(data
, 0);
2953 Pickler_dump(Picklerobject
*self
, PyObject
*args
)
2958 if (!( PyArg_ParseTuple(args
, "O|i:dump", &ob
, &get
)))
2961 if (dump(self
, ob
) < 0)
2964 if (get
) return Pickle_getvalue(self
, NULL
);
2966 /* XXX Why does dump() return self? */
2968 return (PyObject
*)self
;
2972 static struct PyMethodDef Pickler_methods
[] =
2974 {"dump", (PyCFunction
)Pickler_dump
, METH_VARARGS
,
2975 PyDoc_STR("dump(object) -- "
2976 "Write an object in pickle format to the object's pickle stream")},
2977 {"clear_memo", (PyCFunction
)Pickle_clear_memo
, METH_NOARGS
,
2978 PyDoc_STR("clear_memo() -- Clear the picklers memo")},
2979 {"getvalue", (PyCFunction
)Pickle_getvalue
, METH_VARARGS
,
2980 PyDoc_STR("getvalue() -- Finish picking a list-based pickle")},
2981 {NULL
, NULL
} /* sentinel */
2985 static Picklerobject
*
2986 newPicklerobject(PyObject
*file
, int proto
)
2988 Picklerobject
*self
;
2991 proto
= HIGHEST_PROTOCOL
;
2992 if (proto
> HIGHEST_PROTOCOL
) {
2993 PyErr_Format(PyExc_ValueError
, "pickle protocol %d asked for; "
2994 "the highest available protocol is %d",
2995 proto
, HIGHEST_PROTOCOL
);
2999 self
= PyObject_GC_New(Picklerobject
, &Picklertype
);
3002 self
->proto
= proto
;
3003 self
->bin
= proto
> 0;
3008 self
->pers_func
= NULL
;
3009 self
->inst_pers_func
= NULL
;
3010 self
->write_buf
= NULL
;
3012 self
->fast_container
= 0;
3013 self
->fast_memo
= NULL
;
3015 self
->dispatch_table
= NULL
;
3027 if (!( self
->memo
= PyDict_New()))
3030 if (PyFile_Check(file
)) {
3031 self
->fp
= PyFile_AsFile(file
);
3032 if (self
->fp
== NULL
) {
3033 PyErr_SetString(PyExc_ValueError
,
3034 "I/O operation on closed file");
3037 self
->write_func
= write_file
;
3039 else if (PycStringIO_OutputCheck(file
)) {
3040 self
->write_func
= write_cStringIO
;
3042 else if (file
== Py_None
) {
3043 self
->write_func
= write_none
;
3046 self
->write_func
= write_other
;
3048 if (! Pdata_Check(file
)) {
3049 self
->write
= PyObject_GetAttr(file
, write_str
);
3052 PyErr_SetString(PyExc_TypeError
,
3053 "argument must have 'write' "
3059 self
->write_buf
= (char *)PyMem_Malloc(WRITE_BUF_SIZE
);
3060 if (self
->write_buf
== NULL
) {
3066 if (PyEval_GetRestricted()) {
3067 /* Restricted execution, get private tables */
3068 PyObject
*m
= PyImport_ImportModule("copy_reg");
3072 self
->dispatch_table
= PyObject_GetAttr(m
, dispatch_table_str
);
3074 if (self
->dispatch_table
== NULL
)
3078 self
->dispatch_table
= dispatch_table
;
3079 Py_INCREF(dispatch_table
);
3081 PyObject_GC_Track(self
);
3092 get_Pickler(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
3094 static char *kwlist
[] = {"file", "protocol", NULL
};
3095 PyObject
*file
= NULL
;
3099 * The documented signature is Pickler(file, protocol=0), but this
3100 * accepts Pickler() and Pickler(integer) too. The meaning then
3101 * is clear as mud, undocumented, and not supported by pickle.py.
3102 * I'm told Zope uses this, but I haven't traced into this code
3103 * far enough to figure out what it means.
3105 if (!PyArg_ParseTuple(args
, "|i:Pickler", &proto
)) {
3108 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "O|i:Pickler",
3109 kwlist
, &file
, &proto
))
3112 return (PyObject
*)newPicklerobject(file
, proto
);
3117 Pickler_dealloc(Picklerobject
*self
)
3119 PyObject_GC_UnTrack(self
);
3120 Py_XDECREF(self
->write
);
3121 Py_XDECREF(self
->memo
);
3122 Py_XDECREF(self
->fast_memo
);
3123 Py_XDECREF(self
->arg
);
3124 Py_XDECREF(self
->file
);
3125 Py_XDECREF(self
->pers_func
);
3126 Py_XDECREF(self
->inst_pers_func
);
3127 Py_XDECREF(self
->dispatch_table
);
3128 PyMem_Free(self
->write_buf
);
3129 Py_TYPE(self
)->tp_free((PyObject
*)self
);
3133 Pickler_traverse(Picklerobject
*self
, visitproc visit
, void *arg
)
3135 Py_VISIT(self
->write
);
3136 Py_VISIT(self
->memo
);
3137 Py_VISIT(self
->fast_memo
);
3138 Py_VISIT(self
->arg
);
3139 Py_VISIT(self
->file
);
3140 Py_VISIT(self
->pers_func
);
3141 Py_VISIT(self
->inst_pers_func
);
3142 Py_VISIT(self
->dispatch_table
);
3147 Pickler_clear(Picklerobject
*self
)
3149 Py_CLEAR(self
->write
);
3150 Py_CLEAR(self
->memo
);
3151 Py_CLEAR(self
->fast_memo
);
3152 Py_CLEAR(self
->arg
);
3153 Py_CLEAR(self
->file
);
3154 Py_CLEAR(self
->pers_func
);
3155 Py_CLEAR(self
->inst_pers_func
);
3156 Py_CLEAR(self
->dispatch_table
);
3161 Pickler_get_pers_func(Picklerobject
*p
)
3163 if (p
->pers_func
== NULL
)
3164 PyErr_SetString(PyExc_AttributeError
, "persistent_id");
3166 Py_INCREF(p
->pers_func
);
3167 return p
->pers_func
;
3171 Pickler_set_pers_func(Picklerobject
*p
, PyObject
*v
)
3174 PyErr_SetString(PyExc_TypeError
,
3175 "attribute deletion is not supported");
3178 Py_XDECREF(p
->pers_func
);
3185 Pickler_set_inst_pers_func(Picklerobject
*p
, PyObject
*v
)
3188 PyErr_SetString(PyExc_TypeError
,
3189 "attribute deletion is not supported");
3192 Py_XDECREF(p
->inst_pers_func
);
3194 p
->inst_pers_func
= v
;
3199 Pickler_get_memo(Picklerobject
*p
)
3201 if (p
->memo
== NULL
)
3202 PyErr_SetString(PyExc_AttributeError
, "memo");
3209 Pickler_set_memo(Picklerobject
*p
, PyObject
*v
)
3212 PyErr_SetString(PyExc_TypeError
,
3213 "attribute deletion is not supported");
3216 if (!PyDict_Check(v
)) {
3217 PyErr_SetString(PyExc_TypeError
, "memo must be a dictionary");
3220 Py_XDECREF(p
->memo
);
3227 Pickler_get_error(Picklerobject
*p
)
3229 /* why is this an attribute on the Pickler? */
3230 Py_INCREF(PicklingError
);
3231 return PicklingError
;
3234 static PyMemberDef Pickler_members
[] = {
3235 {"binary", T_INT
, offsetof(Picklerobject
, bin
)},
3236 {"fast", T_INT
, offsetof(Picklerobject
, fast
)},
3240 static PyGetSetDef Pickler_getsets
[] = {
3241 {"persistent_id", (getter
)Pickler_get_pers_func
,
3242 (setter
)Pickler_set_pers_func
},
3243 {"inst_persistent_id", NULL
, (setter
)Pickler_set_inst_pers_func
},
3244 {"memo", (getter
)Pickler_get_memo
, (setter
)Pickler_set_memo
},
3245 {"PicklingError", (getter
)Pickler_get_error
, NULL
},
3249 PyDoc_STRVAR(Picklertype__doc__
,
3250 "Objects that know how to pickle objects\n");
3252 static PyTypeObject Picklertype
= {
3253 PyVarObject_HEAD_INIT(NULL
, 0)
3254 "cPickle.Pickler", /*tp_name*/
3255 sizeof(Picklerobject
), /*tp_basicsize*/
3257 (destructor
)Pickler_dealloc
, /* tp_dealloc */
3263 0, /* tp_as_number */
3264 0, /* tp_as_sequence */
3265 0, /* tp_as_mapping */
3269 PyObject_GenericGetAttr
, /* tp_getattro */
3270 PyObject_GenericSetAttr
, /* tp_setattro */
3271 0, /* tp_as_buffer */
3272 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
| Py_TPFLAGS_HAVE_GC
,
3273 Picklertype__doc__
, /* tp_doc */
3274 (traverseproc
)Pickler_traverse
, /* tp_traverse */
3275 (inquiry
)Pickler_clear
, /* tp_clear */
3276 0, /* tp_richcompare */
3277 0, /* tp_weaklistoffset */
3279 0, /* tp_iternext */
3280 Pickler_methods
, /* tp_methods */
3281 Pickler_members
, /* tp_members */
3282 Pickler_getsets
, /* tp_getset */
3286 find_class(PyObject
*py_module_name
, PyObject
*py_global_name
, PyObject
*fc
)
3288 PyObject
*global
= 0, *module
;
3292 PyErr_SetString(UnpicklingError
, "Global and instance "
3293 "pickles are not supported.");
3296 return PyObject_CallFunctionObjArgs(fc
, py_module_name
,
3297 py_global_name
, NULL
);
3300 module
= PySys_GetObject("modules");
3304 module
= PyDict_GetItem(module
, py_module_name
);
3305 if (module
== NULL
) {
3306 module
= PyImport_Import(py_module_name
);
3309 global
= PyObject_GetAttr(module
, py_global_name
);
3313 global
= PyObject_GetAttr(module
, py_global_name
);
3318 marker(Unpicklerobject
*self
)
3320 if (self
->num_marks
< 1) {
3321 PyErr_SetString(UnpicklingError
, "could not find MARK");
3325 return self
->marks
[--self
->num_marks
];
3330 load_none(Unpicklerobject
*self
)
3332 PDATA_APPEND(self
->stack
, Py_None
, -1);
3339 PyErr_SetString(UnpicklingError
, "pickle data was truncated");
3344 load_int(Unpicklerobject
*self
)
3346 PyObject
*py_int
= 0;
3351 if ((len
= self
->readline_func(self
, &s
)) < 0) return -1;
3352 if (len
< 2) return bad_readline();
3353 if (!( s
=pystrndup(s
,len
))) return -1;
3356 l
= strtol(s
, &endptr
, 0);
3358 if (errno
|| (*endptr
!= '\n') || (endptr
[1] != '\0')) {
3359 /* Hm, maybe we've got something long. Let's try reading
3360 it as a Python long object. */
3362 py_int
= PyLong_FromString(s
, NULL
, 0);
3363 if (py_int
== NULL
) {
3364 PyErr_SetString(PyExc_ValueError
,
3365 "could not convert string to int");
3370 if (len
== 3 && (l
== 0 || l
== 1)) {
3371 if (!( py_int
= PyBool_FromLong(l
))) goto finally
;
3374 if (!( py_int
= PyInt_FromLong(l
))) goto finally
;
3379 PDATA_PUSH(self
->stack
, py_int
, -1);
3389 load_bool(Unpicklerobject
*self
, PyObject
*boolean
)
3391 assert(boolean
== Py_True
|| boolean
== Py_False
);
3392 PDATA_APPEND(self
->stack
, boolean
, -1);
3396 /* s contains x bytes of a little-endian integer. Return its value as a
3397 * C int. Obscure: when x is 1 or 2, this is an unsigned little-endian
3398 * int, but when x is 4 it's a signed one. This is an historical source
3399 * of x-platform bugs.
3402 calc_binint(char *s
, int x
)
3408 for (i
= 0, l
= 0L; i
< x
; i
++) {
3409 c
= (unsigned char)s
[i
];
3410 l
|= (long)c
<< (i
* 8);
3413 /* Unlike BININT1 and BININT2, BININT (more accurately BININT4)
3414 * is signed, so on a box with longs bigger than 4 bytes we need
3415 * to extend a BININT's sign bit to the full width.
3417 if (x
== 4 && l
& (1L << 31))
3425 load_binintx(Unpicklerobject
*self
, char *s
, int x
)
3427 PyObject
*py_int
= 0;
3430 l
= calc_binint(s
, x
);
3432 if (!( py_int
= PyInt_FromLong(l
)))
3435 PDATA_PUSH(self
->stack
, py_int
, -1);
3441 load_binint(Unpicklerobject
*self
)
3445 if (self
->read_func(self
, &s
, 4) < 0)
3448 return load_binintx(self
, s
, 4);
3453 load_binint1(Unpicklerobject
*self
)
3457 if (self
->read_func(self
, &s
, 1) < 0)
3460 return load_binintx(self
, s
, 1);
3465 load_binint2(Unpicklerobject
*self
)
3469 if (self
->read_func(self
, &s
, 2) < 0)
3472 return load_binintx(self
, s
, 2);
3476 load_long(Unpicklerobject
*self
)
3482 if ((len
= self
->readline_func(self
, &s
)) < 0) return -1;
3483 if (len
< 2) return bad_readline();
3484 if (!( s
=pystrndup(s
,len
))) return -1;
3486 if (!( l
= PyLong_FromString(s
, &end
, 0)))
3490 PDATA_PUSH(self
->stack
, l
, -1);
3499 /* 'size' bytes contain the # of bytes of little-endian 256's-complement
3503 load_counted_long(Unpicklerobject
*self
, int size
)
3507 unsigned char *pdata
;
3510 assert(size
== 1 || size
== 4);
3511 i
= self
->read_func(self
, &nbytes
, size
);
3512 if (i
< 0) return -1;
3514 size
= calc_binint(nbytes
, size
);
3516 /* Corrupt or hostile pickle -- we never write one like
3519 PyErr_SetString(UnpicklingError
, "LONG pickle has negative "
3525 along
= PyLong_FromLong(0L);
3527 /* Read the raw little-endian bytes & convert. */
3528 i
= self
->read_func(self
, (char **)&pdata
, size
);
3529 if (i
< 0) return -1;
3530 along
= _PyLong_FromByteArray(pdata
, (size_t)size
,
3531 1 /* little endian */, 1 /* signed */);
3535 PDATA_PUSH(self
->stack
, along
, -1);
3540 load_float(Unpicklerobject
*self
)
3542 PyObject
*py_float
= 0;
3547 if ((len
= self
->readline_func(self
, &s
)) < 0) return -1;
3548 if (len
< 2) return bad_readline();
3549 if (!( s
=pystrndup(s
,len
))) return -1;
3551 d
= PyOS_string_to_double(s
, &endptr
, PyExc_OverflowError
);
3553 if (d
== -1.0 && PyErr_Occurred()) {
3555 } else if ((endptr
[0] != '\n') || (endptr
[1] != '\0')) {
3556 PyErr_SetString(PyExc_ValueError
,
3557 "could not convert string to float");
3561 if (!( py_float
= PyFloat_FromDouble(d
)))
3565 PDATA_PUSH(self
->stack
, py_float
, -1);
3575 load_binfloat(Unpicklerobject
*self
)
3581 if (self
->read_func(self
, &p
, 8) < 0)
3584 x
= _PyFloat_Unpack8((unsigned char *)p
, 0);
3585 if (x
== -1.0 && PyErr_Occurred())
3588 py_float
= PyFloat_FromDouble(x
);
3589 if (py_float
== NULL
)
3592 PDATA_PUSH(self
->stack
, py_float
, -1);
3597 load_string(Unpicklerobject
*self
)
3603 if ((len
= self
->readline_func(self
, &s
)) < 0) return -1;
3604 if (len
< 2) return bad_readline();
3605 if (!( s
=pystrndup(s
,len
))) return -1;
3608 /* Strip outermost quotes */
3609 while (s
[len
-1] <= ' ')
3611 if(s
[0]=='"' && s
[len
-1]=='"'){
3615 } else if(s
[0]=='\'' && s
[len
-1]=='\''){
3621 /********************************************/
3623 str
= PyString_DecodeEscape(p
, len
, NULL
, 0, NULL
);
3626 PDATA_PUSH(self
->stack
, str
, -1);
3633 PyErr_SetString(PyExc_ValueError
,"insecure string pickle");
3639 load_binstring(Unpicklerobject
*self
)
3641 PyObject
*py_string
= 0;
3645 if (self
->read_func(self
, &s
, 4) < 0) return -1;
3647 l
= calc_binint(s
, 4);
3649 /* Corrupt or hostile pickle -- we never write one like
3652 PyErr_SetString(UnpicklingError
,
3653 "BINSTRING pickle has negative byte count");
3657 if (self
->read_func(self
, &s
, l
) < 0)
3660 if (!( py_string
= PyString_FromStringAndSize(s
, l
)))
3663 PDATA_PUSH(self
->stack
, py_string
, -1);
3669 load_short_binstring(Unpicklerobject
*self
)
3671 PyObject
*py_string
= 0;
3675 if (self
->read_func(self
, &s
, 1) < 0)
3678 l
= (unsigned char)s
[0];
3680 if (self
->read_func(self
, &s
, l
) < 0) return -1;
3682 if (!( py_string
= PyString_FromStringAndSize(s
, l
))) return -1;
3684 PDATA_PUSH(self
->stack
, py_string
, -1);
3689 #ifdef Py_USING_UNICODE
3691 load_unicode(Unpicklerobject
*self
)
3697 if ((len
= self
->readline_func(self
, &s
)) < 0) return -1;
3698 if (len
< 1) return bad_readline();
3700 if (!( str
= PyUnicode_DecodeRawUnicodeEscape(s
, len
- 1, NULL
)))
3703 PDATA_PUSH(self
->stack
, str
, -1);
3712 #ifdef Py_USING_UNICODE
3714 load_binunicode(Unpicklerobject
*self
)
3720 if (self
->read_func(self
, &s
, 4) < 0) return -1;
3722 l
= calc_binint(s
, 4);
3724 /* Corrupt or hostile pickle -- we never write one like
3727 PyErr_SetString(UnpicklingError
,
3728 "BINUNICODE pickle has negative byte count");
3732 if (self
->read_func(self
, &s
, l
) < 0)
3735 if (!( unicode
= PyUnicode_DecodeUTF8(s
, l
, NULL
)))
3738 PDATA_PUSH(self
->stack
, unicode
, -1);
3745 load_tuple(Unpicklerobject
*self
)
3750 if ((i
= marker(self
)) < 0) return -1;
3751 if (!( tup
=Pdata_popTuple(self
->stack
, i
))) return -1;
3752 PDATA_PUSH(self
->stack
, tup
, -1);
3757 load_counted_tuple(Unpicklerobject
*self
, int len
)
3759 PyObject
*tup
= PyTuple_New(len
);
3764 while (--len
>= 0) {
3767 PDATA_POP(self
->stack
, element
);
3768 if (element
== NULL
)
3770 PyTuple_SET_ITEM(tup
, len
, element
);
3772 PDATA_PUSH(self
->stack
, tup
, -1);
3777 load_empty_list(Unpicklerobject
*self
)
3781 if (!( list
=PyList_New(0))) return -1;
3782 PDATA_PUSH(self
->stack
, list
, -1);
3787 load_empty_dict(Unpicklerobject
*self
)
3791 if (!( dict
=PyDict_New())) return -1;
3792 PDATA_PUSH(self
->stack
, dict
, -1);
3798 load_list(Unpicklerobject
*self
)
3803 if ((i
= marker(self
)) < 0) return -1;
3804 if (!( list
=Pdata_popList(self
->stack
, i
))) return -1;
3805 PDATA_PUSH(self
->stack
, list
, -1);
3810 load_dict(Unpicklerobject
*self
)
3812 PyObject
*dict
, *key
, *value
;
3815 if ((i
= marker(self
)) < 0) return -1;
3816 j
=self
->stack
->length
;
3818 if (!( dict
= PyDict_New())) return -1;
3820 for (k
= i
+1; k
< j
; k
+= 2) {
3821 key
=self
->stack
->data
[k
-1];
3822 value
=self
->stack
->data
[k
];
3823 if (PyDict_SetItem(dict
, key
, value
) < 0) {
3828 Pdata_clear(self
->stack
, i
);
3829 PDATA_PUSH(self
->stack
, dict
, -1);
3834 Instance_New(PyObject
*cls
, PyObject
*args
)
3838 if (PyClass_Check(cls
)) {
3841 if ((l
=PyObject_Size(args
)) < 0) goto err
;
3843 PyObject
*__getinitargs__
;
3845 __getinitargs__
= PyObject_GetAttr(cls
,
3846 __getinitargs___str
);
3847 if (!__getinitargs__
) {
3848 /* We have a class with no __getinitargs__,
3849 so bypass usual construction */
3853 if (!( inst
=PyInstance_NewRaw(cls
, NULL
)))
3857 Py_DECREF(__getinitargs__
);
3860 if ((r
=PyInstance_New(cls
, args
, NULL
))) return r
;
3864 if ((r
=PyObject_CallObject(cls
, args
))) return r
;
3868 PyObject
*tp
, *v
, *tb
, *tmp_value
;
3870 PyErr_Fetch(&tp
, &v
, &tb
);
3872 /* NULL occurs when there was a KeyboardInterrupt */
3873 if (tmp_value
== NULL
)
3874 tmp_value
= Py_None
;
3875 if ((r
= PyTuple_Pack(3, tmp_value
, cls
, args
))) {
3879 PyErr_Restore(tp
,v
,tb
);
3886 load_obj(Unpicklerobject
*self
)
3888 PyObject
*class, *tup
, *obj
=0;
3891 if ((i
= marker(self
)) < 0) return -1;
3892 if (!( tup
=Pdata_popTuple(self
->stack
, i
+1))) return -1;
3893 PDATA_POP(self
->stack
, class);
3895 obj
= Instance_New(class, tup
);
3900 if (! obj
) return -1;
3901 PDATA_PUSH(self
->stack
, obj
, -1);
3907 load_inst(Unpicklerobject
*self
)
3909 PyObject
*tup
, *class=0, *obj
=0, *module_name
, *class_name
;
3913 if ((i
= marker(self
)) < 0) return -1;
3915 if ((len
= self
->readline_func(self
, &s
)) < 0) return -1;
3916 if (len
< 2) return bad_readline();
3917 module_name
= PyString_FromStringAndSize(s
, len
- 1);
3918 if (!module_name
) return -1;
3920 if ((len
= self
->readline_func(self
, &s
)) >= 0) {
3921 if (len
< 2) return bad_readline();
3922 if ((class_name
= PyString_FromStringAndSize(s
, len
- 1))) {
3923 class = find_class(module_name
, class_name
,
3925 Py_DECREF(class_name
);
3928 Py_DECREF(module_name
);
3930 if (! class) return -1;
3932 if ((tup
=Pdata_popTuple(self
->stack
, i
))) {
3933 obj
= Instance_New(class, tup
);
3938 if (! obj
) return -1;
3940 PDATA_PUSH(self
->stack
, obj
, -1);
3945 load_newobj(Unpicklerobject
*self
)
3947 PyObject
*args
= NULL
;
3948 PyObject
*clsraw
= NULL
;
3949 PyTypeObject
*cls
; /* clsraw cast to its true type */
3952 /* Stack is ... cls argtuple, and we want to call
3953 * cls.__new__(cls, *argtuple).
3955 PDATA_POP(self
->stack
, args
);
3956 if (args
== NULL
) goto Fail
;
3957 if (! PyTuple_Check(args
)) {
3958 PyErr_SetString(UnpicklingError
, "NEWOBJ expected an arg "
3963 PDATA_POP(self
->stack
, clsraw
);
3964 cls
= (PyTypeObject
*)clsraw
;
3965 if (cls
== NULL
) goto Fail
;
3966 if (! PyType_Check(cls
)) {
3967 PyErr_SetString(UnpicklingError
, "NEWOBJ class argument "
3968 "isn't a type object");
3971 if (cls
->tp_new
== NULL
) {
3972 PyErr_SetString(UnpicklingError
, "NEWOBJ class argument "
3978 obj
= cls
->tp_new(cls
, args
, NULL
);
3979 if (obj
== NULL
) goto Fail
;
3983 PDATA_PUSH(self
->stack
, obj
, -1);
3993 load_global(Unpicklerobject
*self
)
3995 PyObject
*class = 0, *module_name
= 0, *class_name
= 0;
3999 if ((len
= self
->readline_func(self
, &s
)) < 0) return -1;
4000 if (len
< 2) return bad_readline();
4001 module_name
= PyString_FromStringAndSize(s
, len
- 1);
4002 if (!module_name
) return -1;
4004 if ((len
= self
->readline_func(self
, &s
)) >= 0) {
4006 Py_DECREF(module_name
);
4007 return bad_readline();
4009 if ((class_name
= PyString_FromStringAndSize(s
, len
- 1))) {
4010 class = find_class(module_name
, class_name
,
4012 Py_DECREF(class_name
);
4015 Py_DECREF(module_name
);
4017 if (! class) return -1;
4018 PDATA_PUSH(self
->stack
, class, -1);
4024 load_persid(Unpicklerobject
*self
)
4030 if (self
->pers_func
) {
4031 if ((len
= self
->readline_func(self
, &s
)) < 0) return -1;
4032 if (len
< 2) return bad_readline();
4034 pid
= PyString_FromStringAndSize(s
, len
- 1);
4035 if (!pid
) return -1;
4037 if (PyList_Check(self
->pers_func
)) {
4038 if (PyList_Append(self
->pers_func
, pid
) < 0) {
4046 pid
= PyObject_Call(self
->pers_func
, self
->arg
,
4052 if (! pid
) return -1;
4054 PDATA_PUSH(self
->stack
, pid
, -1);
4058 PyErr_SetString(UnpicklingError
,
4059 "A load persistent id instruction was encountered,\n"
4060 "but no persistent_load function was specified.");
4066 load_binpersid(Unpicklerobject
*self
)
4070 if (self
->pers_func
) {
4071 PDATA_POP(self
->stack
, pid
);
4072 if (! pid
) return -1;
4074 if (PyList_Check(self
->pers_func
)) {
4075 if (PyList_Append(self
->pers_func
, pid
) < 0) {
4083 pid
= PyObject_Call(self
->pers_func
, self
->arg
,
4087 if (! pid
) return -1;
4090 PDATA_PUSH(self
->stack
, pid
, -1);
4094 PyErr_SetString(UnpicklingError
,
4095 "A load persistent id instruction was encountered,\n"
4096 "but no persistent_load function was specified.");
4103 load_pop(Unpicklerobject
*self
)
4105 int len
= self
->stack
->length
;
4107 /* Note that we split the (pickle.py) stack into two stacks,
4108 an object stack and a mark stack. We have to be clever and
4109 pop the right one. We do this by looking at the top of the
4110 mark stack first, and only signalling a stack underflow if
4111 the object stack is empty and the mark stack doesn't match
4114 if (self
->num_marks
> 0 && self
->marks
[self
->num_marks
- 1] == len
) {
4116 } else if (len
> 0) {
4118 Py_DECREF(self
->stack
->data
[len
]);
4119 self
->stack
->length
= len
;
4121 return stackUnderflow();
4128 load_pop_mark(Unpicklerobject
*self
)
4132 if ((i
= marker(self
)) < 0)
4135 Pdata_clear(self
->stack
, i
);
4142 load_dup(Unpicklerobject
*self
)
4147 if ((len
= self
->stack
->length
) <= 0) return stackUnderflow();
4148 last
=self
->stack
->data
[len
-1];
4150 PDATA_PUSH(self
->stack
, last
, -1);
4156 load_get(Unpicklerobject
*self
)
4158 PyObject
*py_str
= 0, *value
= 0;
4163 if ((len
= self
->readline_func(self
, &s
)) < 0) return -1;
4164 if (len
< 2) return bad_readline();
4166 if (!( py_str
= PyString_FromStringAndSize(s
, len
- 1))) return -1;
4168 value
= PyDict_GetItem(self
->memo
, py_str
);
4170 PyErr_SetObject(BadPickleGet
, py_str
);
4174 PDATA_APPEND(self
->stack
, value
, -1);
4184 load_binget(Unpicklerobject
*self
)
4186 PyObject
*py_key
= 0, *value
= 0;
4191 if (self
->read_func(self
, &s
, 1) < 0) return -1;
4193 key
= (unsigned char)s
[0];
4194 if (!( py_key
= PyInt_FromLong((long)key
))) return -1;
4196 value
= PyDict_GetItem(self
->memo
, py_key
);
4198 PyErr_SetObject(BadPickleGet
, py_key
);
4202 PDATA_APPEND(self
->stack
, value
, -1);
4212 load_long_binget(Unpicklerobject
*self
)
4214 PyObject
*py_key
= 0, *value
= 0;
4220 if (self
->read_func(self
, &s
, 4) < 0) return -1;
4222 c
= (unsigned char)s
[0];
4224 c
= (unsigned char)s
[1];
4225 key
|= (long)c
<< 8;
4226 c
= (unsigned char)s
[2];
4227 key
|= (long)c
<< 16;
4228 c
= (unsigned char)s
[3];
4229 key
|= (long)c
<< 24;
4231 if (!( py_key
= PyInt_FromLong((long)key
))) return -1;
4233 value
= PyDict_GetItem(self
->memo
, py_key
);
4235 PyErr_SetObject(BadPickleGet
, py_key
);
4239 PDATA_APPEND(self
->stack
, value
, -1);
4247 /* Push an object from the extension registry (EXT[124]). nbytes is
4248 * the number of bytes following the opcode, holding the index (code) value.
4251 load_extension(Unpicklerobject
*self
, int nbytes
)
4253 char *codebytes
; /* the nbytes bytes after the opcode */
4254 long code
; /* calc_binint returns long */
4255 PyObject
*py_code
; /* code as a Python int */
4256 PyObject
*obj
; /* the object to push */
4257 PyObject
*pair
; /* (module_name, class_name) */
4258 PyObject
*module_name
, *class_name
;
4260 assert(nbytes
== 1 || nbytes
== 2 || nbytes
== 4);
4261 if (self
->read_func(self
, &codebytes
, nbytes
) < 0) return -1;
4262 code
= calc_binint(codebytes
, nbytes
);
4263 if (code
<= 0) { /* note that 0 is forbidden */
4264 /* Corrupt or hostile pickle. */
4265 PyErr_SetString(UnpicklingError
, "EXT specifies code <= 0");
4269 /* Look for the code in the cache. */
4270 py_code
= PyInt_FromLong(code
);
4271 if (py_code
== NULL
) return -1;
4272 obj
= PyDict_GetItem(extension_cache
, py_code
);
4276 PDATA_APPEND(self
->stack
, obj
, -1);
4280 /* Look up the (module_name, class_name) pair. */
4281 pair
= PyDict_GetItem(inverted_registry
, py_code
);
4284 PyErr_Format(PyExc_ValueError
, "unregistered extension "
4288 /* Since the extension registry is manipulable via Python code,
4289 * confirm that pair is really a 2-tuple of strings.
4291 if (!PyTuple_Check(pair
) || PyTuple_Size(pair
) != 2 ||
4292 !PyString_Check(module_name
= PyTuple_GET_ITEM(pair
, 0)) ||
4293 !PyString_Check(class_name
= PyTuple_GET_ITEM(pair
, 1))) {
4295 PyErr_Format(PyExc_ValueError
, "_inverted_registry[%ld] "
4296 "isn't a 2-tuple of strings", code
);
4299 /* Load the object. */
4300 obj
= find_class(module_name
, class_name
, self
->find_class
);
4305 /* Cache code -> obj. */
4306 code
= PyDict_SetItem(extension_cache
, py_code
, obj
);
4312 PDATA_PUSH(self
->stack
, obj
, -1);
4317 load_put(Unpicklerobject
*self
)
4319 PyObject
*py_str
= 0, *value
= 0;
4323 if ((l
= self
->readline_func(self
, &s
)) < 0) return -1;
4324 if (l
< 2) return bad_readline();
4325 if (!( len
=self
->stack
->length
)) return stackUnderflow();
4326 if (!( py_str
= PyString_FromStringAndSize(s
, l
- 1))) return -1;
4327 value
=self
->stack
->data
[len
-1];
4328 l
=PyDict_SetItem(self
->memo
, py_str
, value
);
4335 load_binput(Unpicklerobject
*self
)
4337 PyObject
*py_key
= 0, *value
= 0;
4342 if (self
->read_func(self
, &s
, 1) < 0) return -1;
4343 if (!( (len
=self
->stack
->length
) > 0 )) return stackUnderflow();
4345 key
= (unsigned char)s
[0];
4347 if (!( py_key
= PyInt_FromLong((long)key
))) return -1;
4348 value
=self
->stack
->data
[len
-1];
4349 len
=PyDict_SetItem(self
->memo
, py_key
, value
);
4356 load_long_binput(Unpicklerobject
*self
)
4358 PyObject
*py_key
= 0, *value
= 0;
4364 if (self
->read_func(self
, &s
, 4) < 0) return -1;
4365 if (!( len
=self
->stack
->length
)) return stackUnderflow();
4367 c
= (unsigned char)s
[0];
4369 c
= (unsigned char)s
[1];
4370 key
|= (long)c
<< 8;
4371 c
= (unsigned char)s
[2];
4372 key
|= (long)c
<< 16;
4373 c
= (unsigned char)s
[3];
4374 key
|= (long)c
<< 24;
4376 if (!( py_key
= PyInt_FromLong(key
))) return -1;
4377 value
=self
->stack
->data
[len
-1];
4378 len
=PyDict_SetItem(self
->memo
, py_key
, value
);
4385 do_append(Unpicklerobject
*self
, int x
)
4387 PyObject
*value
= 0, *list
= 0, *append_method
= 0;
4390 len
=self
->stack
->length
;
4391 if (!( len
>= x
&& x
> 0 )) return stackUnderflow();
4393 if (len
==x
) return 0;
4395 list
=self
->stack
->data
[x
-1];
4397 if (PyList_Check(list
)) {
4401 slice
=Pdata_popList(self
->stack
, x
);
4402 if (! slice
) return -1;
4403 list_len
= PyList_GET_SIZE(list
);
4404 i
=PyList_SetSlice(list
, list_len
, list_len
, slice
);
4410 if (!( append_method
= PyObject_GetAttr(list
, append_str
)))
4413 for (i
= x
; i
< len
; i
++) {
4416 value
=self
->stack
->data
[i
];
4418 ARG_TUP(self
, value
);
4420 junk
= PyObject_Call(append_method
, self
->arg
,
4425 Pdata_clear(self
->stack
, i
+1);
4426 self
->stack
->length
=x
;
4427 Py_DECREF(append_method
);
4432 self
->stack
->length
=x
;
4433 Py_DECREF(append_method
);
4441 load_append(Unpicklerobject
*self
)
4443 return do_append(self
, self
->stack
->length
- 1);
4448 load_appends(Unpicklerobject
*self
)
4450 return do_append(self
, marker(self
));
4455 do_setitems(Unpicklerobject
*self
, int x
)
4457 PyObject
*value
= 0, *key
= 0, *dict
= 0;
4460 if (!( (len
=self
->stack
->length
) >= x
4461 && x
> 0 )) return stackUnderflow();
4463 dict
=self
->stack
->data
[x
-1];
4465 for (i
= x
+1; i
< len
; i
+= 2) {
4466 key
=self
->stack
->data
[i
-1];
4467 value
=self
->stack
->data
[i
];
4468 if (PyObject_SetItem(dict
, key
, value
) < 0) {
4474 Pdata_clear(self
->stack
, x
);
4481 load_setitem(Unpicklerobject
*self
)
4483 return do_setitems(self
, self
->stack
->length
- 2);
4487 load_setitems(Unpicklerobject
*self
)
4489 return do_setitems(self
, marker(self
));
4494 load_build(Unpicklerobject
*self
)
4496 PyObject
*state
, *inst
, *slotstate
;
4497 PyObject
*__setstate__
;
4498 PyObject
*d_key
, *d_value
;
4502 /* Stack is ... instance, state. We want to leave instance at
4503 * the stack top, possibly mutated via instance.__setstate__(state).
4505 if (self
->stack
->length
< 2)
4506 return stackUnderflow();
4507 PDATA_POP(self
->stack
, state
);
4510 inst
= self
->stack
->data
[self
->stack
->length
- 1];
4512 __setstate__
= PyObject_GetAttr(inst
, __setstate___str
);
4513 if (__setstate__
!= NULL
) {
4514 PyObject
*junk
= NULL
;
4516 /* The explicit __setstate__ is responsible for everything. */
4517 ARG_TUP(self
, state
);
4519 junk
= PyObject_Call(__setstate__
, self
->arg
, NULL
);
4522 Py_DECREF(__setstate__
);
4528 if (!PyErr_ExceptionMatches(PyExc_AttributeError
))
4532 /* A default __setstate__. First see whether state embeds a
4533 * slot state dict too (a proto 2 addition).
4535 if (PyTuple_Check(state
) && PyTuple_Size(state
) == 2) {
4536 PyObject
*temp
= state
;
4537 state
= PyTuple_GET_ITEM(temp
, 0);
4538 slotstate
= PyTuple_GET_ITEM(temp
, 1);
4540 Py_INCREF(slotstate
);
4546 /* Set inst.__dict__ from the state dict (if any). */
4547 if (state
!= Py_None
) {
4549 if (! PyDict_Check(state
)) {
4550 PyErr_SetString(UnpicklingError
, "state is not a "
4554 dict
= PyObject_GetAttr(inst
, __dict___str
);
4559 while (PyDict_Next(state
, &i
, &d_key
, &d_value
)) {
4560 /* normally the keys for instance attributes are
4561 interned. we should try to do that here. */
4563 if (PyString_CheckExact(d_key
))
4564 PyString_InternInPlace(&d_key
);
4565 if (PyObject_SetItem(dict
, d_key
, d_value
) < 0) {
4574 /* Also set instance attributes from the slotstate dict (if any). */
4575 if (slotstate
!= NULL
) {
4576 if (! PyDict_Check(slotstate
)) {
4577 PyErr_SetString(UnpicklingError
, "slot state is not "
4582 while (PyDict_Next(slotstate
, &i
, &d_key
, &d_value
)) {
4583 if (PyObject_SetAttr(inst
, d_key
, d_value
) < 0)
4591 Py_XDECREF(slotstate
);
4597 load_mark(Unpicklerobject
*self
)
4601 /* Note that we split the (pickle.py) stack into two stacks, an
4602 object stack and a mark stack. Here we push a mark onto the
4606 if ((self
->num_marks
+ 1) >= self
->marks_size
) {
4608 s
=self
->marks_size
+20;
4609 if (s
<= self
->num_marks
) s
=self
->num_marks
+ 1;
4610 if (self
->marks
== NULL
)
4611 marks
=(int *)malloc(s
* sizeof(int));
4613 marks
=(int *)realloc(self
->marks
,
4619 self
->marks
= marks
;
4620 self
->marks_size
= s
;
4623 self
->marks
[self
->num_marks
++] = self
->stack
->length
;
4629 load_reduce(Unpicklerobject
*self
)
4631 PyObject
*callable
= 0, *arg_tup
= 0, *ob
= 0;
4633 PDATA_POP(self
->stack
, arg_tup
);
4634 if (! arg_tup
) return -1;
4635 PDATA_POP(self
->stack
, callable
);
4637 ob
= Instance_New(callable
, arg_tup
);
4638 Py_DECREF(callable
);
4642 if (! ob
) return -1;
4644 PDATA_PUSH(self
->stack
, ob
, -1);
4648 /* Just raises an error if we don't know the protocol specified. PROTO
4649 * is the first opcode for protocols >= 2.
4652 load_proto(Unpicklerobject
*self
)
4657 i
= self
->read_func(self
, &protobyte
, 1);
4661 i
= calc_binint(protobyte
, 1);
4662 /* No point checking for < 0, since calc_binint returns an unsigned
4663 * int when chewing on 1 byte.
4666 if (i
<= HIGHEST_PROTOCOL
)
4669 PyErr_Format(PyExc_ValueError
, "unsupported pickle protocol: %d", i
);
4674 load(Unpicklerobject
*self
)
4676 PyObject
*err
= 0, *val
= 0;
4679 self
->num_marks
= 0;
4680 if (self
->stack
->length
) Pdata_clear(self
->stack
, 0);
4683 if (self
->read_func(self
, &s
, 1) < 0)
4688 if (load_none(self
) < 0)
4693 if (load_binint(self
) < 0)
4698 if (load_binint1(self
) < 0)
4703 if (load_binint2(self
) < 0)
4708 if (load_int(self
) < 0)
4713 if (load_long(self
) < 0)
4718 if (load_counted_long(self
, 1) < 0)
4723 if (load_counted_long(self
, 4) < 0)
4728 if (load_float(self
) < 0)
4733 if (load_binfloat(self
) < 0)
4738 if (load_binstring(self
) < 0)
4742 case SHORT_BINSTRING
:
4743 if (load_short_binstring(self
) < 0)
4748 if (load_string(self
) < 0)
4752 #ifdef Py_USING_UNICODE
4754 if (load_unicode(self
) < 0)
4759 if (load_binunicode(self
) < 0)
4765 if (load_counted_tuple(self
, 0) < 0)
4770 if (load_counted_tuple(self
, 1) < 0)
4775 if (load_counted_tuple(self
, 2) < 0)
4780 if (load_counted_tuple(self
, 3) < 0)
4785 if (load_tuple(self
) < 0)
4790 if (load_empty_list(self
) < 0)
4795 if (load_list(self
) < 0)
4800 if (load_empty_dict(self
) < 0)
4805 if (load_dict(self
) < 0)
4810 if (load_obj(self
) < 0)
4815 if (load_inst(self
) < 0)
4820 if (load_newobj(self
) < 0)
4825 if (load_global(self
) < 0)
4830 if (load_append(self
) < 0)
4835 if (load_appends(self
) < 0)
4840 if (load_build(self
) < 0)
4845 if (load_dup(self
) < 0)
4850 if (load_binget(self
) < 0)
4855 if (load_long_binget(self
) < 0)
4860 if (load_get(self
) < 0)
4865 if (load_extension(self
, 1) < 0)
4870 if (load_extension(self
, 2) < 0)
4875 if (load_extension(self
, 4) < 0)
4879 if (load_mark(self
) < 0)
4884 if (load_binput(self
) < 0)
4889 if (load_long_binput(self
) < 0)
4894 if (load_put(self
) < 0)
4899 if (load_pop(self
) < 0)
4904 if (load_pop_mark(self
) < 0)
4909 if (load_setitem(self
) < 0)
4914 if (load_setitems(self
) < 0)
4922 if (load_persid(self
) < 0)
4927 if (load_binpersid(self
) < 0)
4932 if (load_reduce(self
) < 0)
4937 if (load_proto(self
) < 0)
4942 if (load_bool(self
, Py_True
) < 0)
4947 if (load_bool(self
, Py_False
) < 0)
4953 PyErr_SetNone(PyExc_EOFError
);
4957 cPickle_ErrFormat(UnpicklingError
,
4958 "invalid load key, '%s'.",
4966 if ((err
= PyErr_Occurred())) {
4967 if (err
== PyExc_EOFError
) {
4968 PyErr_SetNone(PyExc_EOFError
);
4973 PDATA_POP(self
->stack
, val
);
4978 /* No-load functions to support noload, which is used to
4979 find persistent references. */
4982 noload_obj(Unpicklerobject
*self
)
4986 if ((i
= marker(self
)) < 0) return -1;
4987 return Pdata_clear(self
->stack
, i
+1);
4992 noload_inst(Unpicklerobject
*self
)
4997 if ((i
= marker(self
)) < 0) return -1;
4998 Pdata_clear(self
->stack
, i
);
4999 if (self
->readline_func(self
, &s
) < 0) return -1;
5000 if (self
->readline_func(self
, &s
) < 0) return -1;
5001 PDATA_APPEND(self
->stack
, Py_None
, -1);
5006 noload_newobj(Unpicklerobject
*self
)
5010 PDATA_POP(self
->stack
, obj
); /* pop argtuple */
5011 if (obj
== NULL
) return -1;
5014 PDATA_POP(self
->stack
, obj
); /* pop cls */
5015 if (obj
== NULL
) return -1;
5018 PDATA_APPEND(self
->stack
, Py_None
, -1);
5023 noload_global(Unpicklerobject
*self
)
5027 if (self
->readline_func(self
, &s
) < 0) return -1;
5028 if (self
->readline_func(self
, &s
) < 0) return -1;
5029 PDATA_APPEND(self
->stack
, Py_None
,-1);
5034 noload_reduce(Unpicklerobject
*self
)
5037 if (self
->stack
->length
< 2) return stackUnderflow();
5038 Pdata_clear(self
->stack
, self
->stack
->length
-2);
5039 PDATA_APPEND(self
->stack
, Py_None
,-1);
5044 noload_build(Unpicklerobject
*self
) {
5046 if (self
->stack
->length
< 1) return stackUnderflow();
5047 Pdata_clear(self
->stack
, self
->stack
->length
-1);
5052 noload_extension(Unpicklerobject
*self
, int nbytes
)
5056 assert(nbytes
== 1 || nbytes
== 2 || nbytes
== 4);
5057 if (self
->read_func(self
, &codebytes
, nbytes
) < 0) return -1;
5058 PDATA_APPEND(self
->stack
, Py_None
, -1);
5063 noload_append(Unpicklerobject
*self
)
5065 return Pdata_clear(self
->stack
, self
->stack
->length
- 1);
5069 noload_appends(Unpicklerobject
*self
)
5072 if ((i
= marker(self
)) < 0) return -1;
5073 return Pdata_clear(self
->stack
, i
);
5077 noload_setitem(Unpicklerobject
*self
)
5079 return Pdata_clear(self
->stack
, self
->stack
->length
- 2);
5083 noload_setitems(Unpicklerobject
*self
)
5086 if ((i
= marker(self
)) < 0) return -1;
5087 return Pdata_clear(self
->stack
, i
);
5091 noload(Unpicklerobject
*self
)
5093 PyObject
*err
= 0, *val
= 0;
5096 self
->num_marks
= 0;
5097 Pdata_clear(self
->stack
, 0);
5100 if (self
->read_func(self
, &s
, 1) < 0)
5105 if (load_none(self
) < 0)
5110 if (load_binint(self
) < 0)
5115 if (load_binint1(self
) < 0)
5120 if (load_binint2(self
) < 0)
5125 if (load_int(self
) < 0)
5130 if (load_long(self
) < 0)
5135 if (load_counted_long(self
, 1) < 0)
5140 if (load_counted_long(self
, 4) < 0)
5145 if (load_float(self
) < 0)
5150 if (load_binfloat(self
) < 0)
5155 if (load_binstring(self
) < 0)
5159 case SHORT_BINSTRING
:
5160 if (load_short_binstring(self
) < 0)
5165 if (load_string(self
) < 0)
5169 #ifdef Py_USING_UNICODE
5171 if (load_unicode(self
) < 0)
5176 if (load_binunicode(self
) < 0)
5182 if (load_counted_tuple(self
, 0) < 0)
5187 if (load_counted_tuple(self
, 1) < 0)
5192 if (load_counted_tuple(self
, 2) < 0)
5197 if (load_counted_tuple(self
, 3) < 0)
5202 if (load_tuple(self
) < 0)
5207 if (load_empty_list(self
) < 0)
5212 if (load_list(self
) < 0)
5217 if (load_empty_dict(self
) < 0)
5222 if (load_dict(self
) < 0)
5227 if (noload_obj(self
) < 0)
5232 if (noload_inst(self
) < 0)
5237 if (noload_newobj(self
) < 0)
5242 if (noload_global(self
) < 0)
5247 if (noload_append(self
) < 0)
5252 if (noload_appends(self
) < 0)
5257 if (noload_build(self
) < 0)
5262 if (load_dup(self
) < 0)
5267 if (load_binget(self
) < 0)
5272 if (load_long_binget(self
) < 0)
5277 if (load_get(self
) < 0)
5282 if (noload_extension(self
, 1) < 0)
5287 if (noload_extension(self
, 2) < 0)
5292 if (noload_extension(self
, 4) < 0)
5297 if (load_mark(self
) < 0)
5302 if (load_binput(self
) < 0)
5307 if (load_long_binput(self
) < 0)
5312 if (load_put(self
) < 0)
5317 if (load_pop(self
) < 0)
5322 if (load_pop_mark(self
) < 0)
5327 if (noload_setitem(self
) < 0)
5332 if (noload_setitems(self
) < 0)
5340 if (load_persid(self
) < 0)
5345 if (load_binpersid(self
) < 0)
5350 if (noload_reduce(self
) < 0)
5355 if (load_proto(self
) < 0)
5360 if (load_bool(self
, Py_True
) < 0)
5365 if (load_bool(self
, Py_False
) < 0)
5369 cPickle_ErrFormat(UnpicklingError
,
5370 "invalid load key, '%s'.",
5378 if ((err
= PyErr_Occurred())) {
5379 if (err
== PyExc_EOFError
) {
5380 PyErr_SetNone(PyExc_EOFError
);
5385 PDATA_POP(self
->stack
, val
);
5391 Unpickler_load(Unpicklerobject
*self
, PyObject
*unused
)
5397 Unpickler_noload(Unpicklerobject
*self
, PyObject
*unused
)
5399 return noload(self
);
5403 static struct PyMethodDef Unpickler_methods
[] = {
5404 {"load", (PyCFunction
)Unpickler_load
, METH_NOARGS
,
5405 PyDoc_STR("load() -- Load a pickle")
5407 {"noload", (PyCFunction
)Unpickler_noload
, METH_NOARGS
,
5409 "noload() -- not load a pickle, but go through most of the motions\n"
5411 "This function can be used to read past a pickle without instantiating\n"
5412 "any objects or importing any modules. It can also be used to find all\n"
5413 "persistent references without instantiating any objects or importing\n"
5416 {NULL
, NULL
} /* sentinel */
5420 static Unpicklerobject
*
5421 newUnpicklerobject(PyObject
*f
)
5423 Unpicklerobject
*self
;
5425 if (!( self
= PyObject_GC_New(Unpicklerobject
, &Unpicklertype
)))
5430 self
->stack
= (Pdata
*)Pdata_New();
5431 self
->pers_func
= NULL
;
5432 self
->last_string
= NULL
;
5434 self
->num_marks
= 0;
5435 self
->marks_size
= 0;
5438 self
->readline
= NULL
;
5439 self
->find_class
= NULL
;
5441 if (!( self
->memo
= PyDict_New()))
5450 /* Set read, readline based on type of f */
5451 if (PyFile_Check(f
)) {
5452 self
->fp
= PyFile_AsFile(f
);
5453 if (self
->fp
== NULL
) {
5454 PyErr_SetString(PyExc_ValueError
,
5455 "I/O operation on closed file");
5458 self
->read_func
= read_file
;
5459 self
->readline_func
= readline_file
;
5461 else if (PycStringIO_InputCheck(f
)) {
5463 self
->read_func
= read_cStringIO
;
5464 self
->readline_func
= readline_cStringIO
;
5469 self
->read_func
= read_other
;
5470 self
->readline_func
= readline_other
;
5472 if (!( (self
->readline
= PyObject_GetAttr(f
, readline_str
)) &&
5473 (self
->read
= PyObject_GetAttr(f
, read_str
)))) {
5475 PyErr_SetString( PyExc_TypeError
,
5476 "argument must have 'read' and "
5477 "'readline' attributes" );
5481 PyObject_GC_Track(self
);
5486 Py_DECREF((PyObject
*)self
);
5492 get_Unpickler(PyObject
*self
, PyObject
*file
)
5494 return (PyObject
*)newUnpicklerobject(file
);
5499 Unpickler_dealloc(Unpicklerobject
*self
)
5501 PyObject_GC_UnTrack((PyObject
*)self
);
5502 Py_XDECREF(self
->readline
);
5503 Py_XDECREF(self
->read
);
5504 Py_XDECREF(self
->file
);
5505 Py_XDECREF(self
->memo
);
5506 Py_XDECREF(self
->stack
);
5507 Py_XDECREF(self
->pers_func
);
5508 Py_XDECREF(self
->arg
);
5509 Py_XDECREF(self
->last_string
);
5510 Py_XDECREF(self
->find_class
);
5516 if (self
->buf_size
) {
5520 Py_TYPE(self
)->tp_free((PyObject
*)self
);
5524 Unpickler_traverse(Unpicklerobject
*self
, visitproc visit
, void *arg
)
5526 Py_VISIT(self
->readline
);
5527 Py_VISIT(self
->read
);
5528 Py_VISIT(self
->file
);
5529 Py_VISIT(self
->memo
);
5530 Py_VISIT(self
->stack
);
5531 Py_VISIT(self
->pers_func
);
5532 Py_VISIT(self
->arg
);
5533 Py_VISIT(self
->last_string
);
5534 Py_VISIT(self
->find_class
);
5539 Unpickler_clear(Unpicklerobject
*self
)
5541 Py_CLEAR(self
->readline
);
5542 Py_CLEAR(self
->read
);
5543 Py_CLEAR(self
->file
);
5544 Py_CLEAR(self
->memo
);
5545 Py_CLEAR(self
->stack
);
5546 Py_CLEAR(self
->pers_func
);
5547 Py_CLEAR(self
->arg
);
5548 Py_CLEAR(self
->last_string
);
5549 Py_CLEAR(self
->find_class
);
5554 Unpickler_getattr(Unpicklerobject
*self
, char *name
)
5556 if (!strcmp(name
, "persistent_load")) {
5557 if (!self
->pers_func
) {
5558 PyErr_SetString(PyExc_AttributeError
, name
);
5562 Py_INCREF(self
->pers_func
);
5563 return self
->pers_func
;
5566 if (!strcmp(name
, "find_global")) {
5567 if (!self
->find_class
) {
5568 PyErr_SetString(PyExc_AttributeError
, name
);
5572 Py_INCREF(self
->find_class
);
5573 return self
->find_class
;
5576 if (!strcmp(name
, "memo")) {
5578 PyErr_SetString(PyExc_AttributeError
, name
);
5582 Py_INCREF(self
->memo
);
5586 if (!strcmp(name
, "UnpicklingError")) {
5587 Py_INCREF(UnpicklingError
);
5588 return UnpicklingError
;
5591 return Py_FindMethod(Unpickler_methods
, (PyObject
*)self
, name
);
5596 Unpickler_setattr(Unpicklerobject
*self
, char *name
, PyObject
*value
)
5599 if (!strcmp(name
, "persistent_load")) {
5600 Py_XDECREF(self
->pers_func
);
5601 self
->pers_func
= value
;
5606 if (!strcmp(name
, "find_global")) {
5607 Py_XDECREF(self
->find_class
);
5608 self
->find_class
= value
;
5614 PyErr_SetString(PyExc_TypeError
,
5615 "attribute deletion is not supported");
5619 if (strcmp(name
, "memo") == 0) {
5620 if (!PyDict_Check(value
)) {
5621 PyErr_SetString(PyExc_TypeError
,
5622 "memo must be a dictionary");
5625 Py_XDECREF(self
->memo
);
5631 PyErr_SetString(PyExc_AttributeError
, name
);
5635 /* ---------------------------------------------------------------------------
5636 * Module-level functions.
5639 /* dump(obj, file, protocol=0). */
5641 cpm_dump(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
5643 static char *kwlist
[] = {"obj", "file", "protocol", NULL
};
5644 PyObject
*ob
, *file
, *res
= NULL
;
5645 Picklerobject
*pickler
= 0;
5648 if (!( PyArg_ParseTupleAndKeywords(args
, kwds
, "OO|i", kwlist
,
5649 &ob
, &file
, &proto
)))
5652 if (!( pickler
= newPicklerobject(file
, proto
)))
5655 if (dump(pickler
, ob
) < 0)
5662 Py_XDECREF(pickler
);
5668 /* dumps(obj, protocol=0). */
5670 cpm_dumps(PyObject
*self
, PyObject
*args
, PyObject
*kwds
)
5672 static char *kwlist
[] = {"obj", "protocol", NULL
};
5673 PyObject
*ob
, *file
= 0, *res
= NULL
;
5674 Picklerobject
*pickler
= 0;
5677 if (!( PyArg_ParseTupleAndKeywords(args
, kwds
, "O|i:dumps", kwlist
,
5681 if (!( file
= PycStringIO
->NewOutput(128)))
5684 if (!( pickler
= newPicklerobject(file
, proto
)))
5687 if (dump(pickler
, ob
) < 0)
5690 res
= PycStringIO
->cgetvalue(file
);
5693 Py_XDECREF(pickler
);
5700 /* load(fileobj). */
5702 cpm_load(PyObject
*self
, PyObject
*ob
)
5704 Unpicklerobject
*unpickler
= 0;
5705 PyObject
*res
= NULL
;
5707 if (!( unpickler
= newUnpicklerobject(ob
)))
5710 res
= load(unpickler
);
5713 Py_XDECREF(unpickler
);
5721 cpm_loads(PyObject
*self
, PyObject
*args
)
5723 PyObject
*ob
, *file
= 0, *res
= NULL
;
5724 Unpicklerobject
*unpickler
= 0;
5726 if (!( PyArg_ParseTuple(args
, "S:loads", &ob
)))
5729 if (!( file
= PycStringIO
->NewInput(ob
)))
5732 if (!( unpickler
= newUnpicklerobject(file
)))
5735 res
= load(unpickler
);
5739 Py_XDECREF(unpickler
);
5745 PyDoc_STRVAR(Unpicklertype__doc__
,
5746 "Objects that know how to unpickle");
5748 static PyTypeObject Unpicklertype
= {
5749 PyVarObject_HEAD_INIT(NULL
, 0)
5750 "cPickle.Unpickler", /*tp_name*/
5751 sizeof(Unpicklerobject
), /*tp_basicsize*/
5753 (destructor
)Unpickler_dealloc
, /* tp_dealloc */
5755 (getattrfunc
)Unpickler_getattr
, /* tp_getattr */
5756 (setattrfunc
)Unpickler_setattr
, /* tp_setattr */
5759 0, /* tp_as_number */
5760 0, /* tp_as_sequence */
5761 0, /* tp_as_mapping */
5765 0, /* tp_getattro */
5766 0, /* tp_setattro */
5767 0, /* tp_as_buffer */
5768 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
| Py_TPFLAGS_HAVE_GC
,
5769 Unpicklertype__doc__
, /* tp_doc */
5770 (traverseproc
)Unpickler_traverse
, /* tp_traverse */
5771 (inquiry
)Unpickler_clear
, /* tp_clear */
5774 static struct PyMethodDef cPickle_methods
[] = {
5775 {"dump", (PyCFunction
)cpm_dump
, METH_VARARGS
| METH_KEYWORDS
,
5776 PyDoc_STR("dump(obj, file, protocol=0) -- "
5777 "Write an object in pickle format to the given file.\n"
5779 "See the Pickler docstring for the meaning of optional argument proto.")
5782 {"dumps", (PyCFunction
)cpm_dumps
, METH_VARARGS
| METH_KEYWORDS
,
5783 PyDoc_STR("dumps(obj, protocol=0) -- "
5784 "Return a string containing an object in pickle format.\n"
5786 "See the Pickler docstring for the meaning of optional argument proto.")
5789 {"load", (PyCFunction
)cpm_load
, METH_O
,
5790 PyDoc_STR("load(file) -- Load a pickle from the given file")},
5792 {"loads", (PyCFunction
)cpm_loads
, METH_VARARGS
,
5793 PyDoc_STR("loads(string) -- Load a pickle from the given string")},
5795 {"Pickler", (PyCFunction
)get_Pickler
, METH_VARARGS
| METH_KEYWORDS
,
5796 PyDoc_STR("Pickler(file, protocol=0) -- Create a pickler.\n"
5798 "This takes a file-like object for writing a pickle data stream.\n"
5799 "The optional proto argument tells the pickler to use the given\n"
5800 "protocol; supported protocols are 0, 1, 2. The default\n"
5801 "protocol is 0, to be backwards compatible. (Protocol 0 is the\n"
5802 "only protocol that can be written to a file opened in text\n"
5803 "mode and read back successfully. When using a protocol higher\n"
5804 "than 0, make sure the file is opened in binary mode, both when\n"
5805 "pickling and unpickling.)\n"
5807 "Protocol 1 is more efficient than protocol 0; protocol 2 is\n"
5808 "more efficient than protocol 1.\n"
5810 "Specifying a negative protocol version selects the highest\n"
5811 "protocol version supported. The higher the protocol used, the\n"
5812 "more recent the version of Python needed to read the pickle\n"
5815 "The file parameter must have a write() method that accepts a single\n"
5816 "string argument. It can thus be an open file object, a StringIO\n"
5817 "object, or any other custom object that meets this interface.\n")
5820 {"Unpickler", (PyCFunction
)get_Unpickler
, METH_O
,
5821 PyDoc_STR("Unpickler(file) -- Create an unpickler.")},
5827 init_stuff(PyObject
*module_dict
)
5829 PyObject
*copyreg
, *t
, *r
;
5831 #define INIT_STR(S) if (!( S ## _str=PyString_InternFromString(#S))) return -1;
5833 if (PyType_Ready(&Unpicklertype
) < 0)
5835 if (PyType_Ready(&Picklertype
) < 0)
5838 INIT_STR(__class__
);
5839 INIT_STR(__getinitargs__
);
5841 INIT_STR(__getstate__
);
5842 INIT_STR(__setstate__
);
5845 INIT_STR(__reduce__
);
5846 INIT_STR(__reduce_ex__
);
5851 INIT_STR(dispatch_table
);
5853 if (!( copyreg
= PyImport_ImportModule("copy_reg")))
5856 /* This is special because we want to use a different
5857 one in restricted mode. */
5858 dispatch_table
= PyObject_GetAttr(copyreg
, dispatch_table_str
);
5859 if (!dispatch_table
) return -1;
5861 extension_registry
= PyObject_GetAttrString(copyreg
,
5862 "_extension_registry");
5863 if (!extension_registry
) return -1;
5865 inverted_registry
= PyObject_GetAttrString(copyreg
,
5866 "_inverted_registry");
5867 if (!inverted_registry
) return -1;
5869 extension_cache
= PyObject_GetAttrString(copyreg
,
5870 "_extension_cache");
5871 if (!extension_cache
) return -1;
5875 if (!(empty_tuple
= PyTuple_New(0)))
5878 two_tuple
= PyTuple_New(2);
5879 if (two_tuple
== NULL
)
5881 /* We use this temp container with no regard to refcounts, or to
5882 * keeping containees alive. Exempt from GC, because we don't
5883 * want anything looking at two_tuple() by magic.
5885 PyObject_GC_UnTrack(two_tuple
);
5888 if (!( t
=PyImport_ImportModule("__builtin__"))) return -1;
5889 if (PyDict_SetItemString(module_dict
, "__builtins__", t
) < 0)
5892 if (!( t
=PyDict_New())) return -1;
5893 if (!( r
=PyRun_String(
5894 "def __str__(self):\n"
5895 " return self.args and ('%s' % self.args[0]) or '(what)'\n",
5897 module_dict
, t
) )) return -1;
5900 PickleError
= PyErr_NewException("cPickle.PickleError", NULL
, t
);
5906 PicklingError
= PyErr_NewException("cPickle.PicklingError",
5911 if (!( t
=PyDict_New())) return -1;
5912 if (!( r
=PyRun_String(
5913 "def __str__(self):\n"
5915 " a=a and type(a[0]) or '(what)'\n"
5916 " return 'Cannot pickle %s objects' % a\n"
5918 module_dict
, t
) )) return -1;
5921 if (!( UnpickleableError
= PyErr_NewException(
5922 "cPickle.UnpickleableError", PicklingError
, t
)))
5927 if (!( UnpicklingError
= PyErr_NewException("cPickle.UnpicklingError",
5928 PickleError
, NULL
)))
5931 if (!( BadPickleGet
= PyErr_NewException("cPickle.BadPickleGet",
5932 UnpicklingError
, NULL
)))
5935 if (PyDict_SetItemString(module_dict
, "PickleError",
5939 if (PyDict_SetItemString(module_dict
, "PicklingError",
5943 if (PyDict_SetItemString(module_dict
, "UnpicklingError",
5944 UnpicklingError
) < 0)
5947 if (PyDict_SetItemString(module_dict
, "UnpickleableError",
5948 UnpickleableError
) < 0)
5951 if (PyDict_SetItemString(module_dict
, "BadPickleGet",
5960 #ifndef PyMODINIT_FUNC /* declarations for DLL import/export */
5961 #define PyMODINIT_FUNC void
5966 PyObject
*m
, *d
, *di
, *v
, *k
;
5968 char *rev
= "1.71"; /* XXX when does this change? */
5969 PyObject
*format_version
;
5970 PyObject
*compatible_formats
;
5972 Py_TYPE(&Picklertype
) = &PyType_Type
;
5973 Py_TYPE(&Unpicklertype
) = &PyType_Type
;
5974 Py_TYPE(&PdataType
) = &PyType_Type
;
5976 /* Initialize some pieces. We need to do this before module creation,
5977 * so we're forced to use a temporary dictionary. :(
5981 if (init_stuff(di
) < 0) return;
5983 /* Create the module and add the functions */
5984 m
= Py_InitModule4("cPickle", cPickle_methods
,
5985 cPickle_module_documentation
,
5986 (PyObject
*)NULL
,PYTHON_API_VERSION
);
5990 /* Add some symbolic constants to the module */
5991 d
= PyModule_GetDict(m
);
5992 v
= PyString_FromString(rev
);
5993 PyDict_SetItemString(d
, "__version__", v
);
5996 /* Copy data from di. Waaa. */
5997 for (i
=0; PyDict_Next(di
, &i
, &k
, &v
); ) {
5998 if (PyObject_SetItem(d
, k
, v
) < 0) {
6005 i
= PyModule_AddIntConstant(m
, "HIGHEST_PROTOCOL", HIGHEST_PROTOCOL
);
6009 /* These are purely informational; no code uses them. */
6010 /* File format version we write. */
6011 format_version
= PyString_FromString("2.0");
6012 /* Format versions we can read. */
6013 compatible_formats
= Py_BuildValue("[sssss]",
6014 "1.0", /* Original protocol 0 */
6015 "1.1", /* Protocol 0 + INST */
6016 "1.2", /* Original protocol 1 */
6017 "1.3", /* Protocol 1 + BINFLOAT */
6018 "2.0"); /* Original protocol 2 */
6019 PyDict_SetItemString(d
, "format_version", format_version
);
6020 PyDict_SetItemString(d
, "compatible_formats", compatible_formats
);
6021 Py_XDECREF(format_version
);
6022 Py_XDECREF(compatible_formats
);