2 * cPickle.c,v 1.71 1999/07/11 13:30:34 jim Exp
4 * Copyright (c) 1996-1998, Digital Creations, Fredericksburg, VA, USA.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions are
11 * o Redistributions of source code must retain the above copyright
12 * notice, this list of conditions, and the disclaimer that follows.
14 * o Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions, and the following disclaimer in
16 * the documentation and/or other materials provided with the
19 * o Neither the name of Digital Creations nor the names of its
20 * contributors may be used to endorse or promote products derived
21 * from this software without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS AND CONTRIBUTORS *AS
25 * IS* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
26 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
27 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL DIGITAL
28 * CREATIONS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
29 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
30 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
31 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
32 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
33 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
34 * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
38 # If you have questions regarding this software, contact:
40 # Digital Creations, L.C.
41 # 910 Princess Ann Street
42 # Fredericksburge, Virginia 22401
49 static char cPickle_module_documentation
[] =
50 "C implementation and optimization of the Python pickle module\n"
52 "cPickle.c,v 1.71 1999/07/11 13:30:34 jim Exp\n"
56 #include "cStringIO.h"
60 #define Py_eval_input eval_input
61 #endif /* Py_eval_input */
65 #define UNLESS(E) if (!(E))
67 #define DEL_LIST_SLICE(list, from, to) (PyList_SetSlice(list, from, to, NULL))
69 #define WRITE_BUF_SIZE 256
71 /* --------------------------------------------------------------------------
72 NOTES on format codes.
73 XXX much more is needed here
76 BININT1 8-bit unsigned integer; followed by 1 byte.
77 BININT2 16-bit unsigned integer; followed by 2 bytes, little-endian.
78 BININT 32-bit signed integer; followed by 4 bytes, little-endian.
79 INT Integer; natural decimal string conversion, then newline.
80 CAUTION: INT-reading code can't assume that what follows
81 fits in a Python int, because the size of Python ints varies
83 LONG Long (unbounded) integer; repr(i), then newline.
84 -------------------------------------------------------------------------- */
100 #define BINPERSID 'Q'
103 #define BINSTRING 'T'
104 #define SHORT_BINSTRING 'U'
106 #define BINUNICODE 'X'
111 #define EMPTY_DICT '}'
116 #define LONG_BINGET 'j'
118 #define EMPTY_LIST ']'
122 #define LONG_BINPUT 'r'
125 #define EMPTY_TUPLE ')'
128 static char MARKv
= MARK
;
130 /* atol function from string module */
131 static PyObject
*atol_func
;
133 static PyObject
*PickleError
;
134 static PyObject
*PicklingError
;
135 static PyObject
*UnpickleableError
;
136 static PyObject
*UnpicklingError
;
137 static PyObject
*BadPickleGet
;
140 static PyObject
*dispatch_table
;
141 static PyObject
*safe_constructors
;
142 static PyObject
*empty_tuple
;
144 static PyObject
*__class___str
, *__getinitargs___str
, *__dict___str
,
145 *__getstate___str
, *__setstate___str
, *__name___str
, *__reduce___str
,
146 *write_str
, *__safe_for_unpickling___str
, *append_str
,
147 *read_str
, *readline_str
, *__main___str
, *__basicnew___str
,
148 *copy_reg_str
, *dispatch_table_str
, *safe_constructors_str
, *empty_str
;
150 #ifndef PyList_SET_ITEM
151 #define PyList_SET_ITEM(op, i, v) (((PyListObject *)(op))->ob_item[i] = (v))
153 #ifndef PyList_GET_SIZE
154 #define PyList_GET_SIZE(op) (((PyListObject *)(op))->ob_size)
156 #ifndef PyTuple_SET_ITEM
157 #define PyTuple_SET_ITEM(op, i, v) (((PyTupleObject *)(op))->ob_item[i] = (v))
159 #ifndef PyTuple_GET_SIZE
160 #define PyTuple_GET_SIZE(op) (((PyTupleObject *)(op))->ob_size)
162 #ifndef PyString_GET_SIZE
163 #define PyString_GET_SIZE(op) (((PyStringObject *)(op))->ob_size)
166 /*************************************************************************
167 Internal Data type for pickle data. */
176 Pdata_dealloc(Pdata
*self
) {
180 for (i
=self
->length
, p
=self
->data
; --i
>= 0; p
++) Py_DECREF(*p
);
182 if (self
->data
) free(self
->data
);
187 static PyTypeObject PdataType
= {
188 PyObject_HEAD_INIT(NULL
) 0, "Pdata", sizeof(Pdata
), 0,
189 (destructor
)Pdata_dealloc
,
190 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0L,0L,0L,0L, ""
193 #define Pdata_Check(O) ((O)->ob_type == &PdataType)
199 UNLESS (self
= PyObject_New(Pdata
, &PdataType
)) return NULL
;
202 self
->data
=malloc(self
->size
* sizeof(PyObject
*));
203 if (self
->data
) return (PyObject
*)self
;
205 return PyErr_NoMemory();
209 stackUnderflow(void) {
210 PyErr_SetString(UnpicklingError
, "unpickling stack underflow");
215 Pdata_clear(Pdata
*self
, int clearto
) {
219 if (clearto
< 0) return stackUnderflow();
220 if (clearto
>= self
->length
) return 0;
222 for (i
=self
->length
, p
=self
->data
+clearto
; --i
>= clearto
; p
++)
224 self
->length
=clearto
;
231 Pdata_grow(Pdata
*self
) {
237 self
->data
= realloc(self
->data
, self
->size
*sizeof(PyObject
*));
246 #define PDATA_POP(D,V) { \
247 if ((D)->length) V=D->data[--((D)->length)]; \
249 PyErr_SetString(UnpicklingError, "bad pickle data"); \
256 Pdata_popTuple(Pdata
*self
, int start
) {
260 l
=self
->length
-start
;
261 UNLESS (r
=PyTuple_New(l
)) return NULL
;
262 for (i
=start
, j
=0 ; j
< l
; i
++, j
++)
263 PyTuple_SET_ITEM(r
, j
, self
->data
[i
]);
270 Pdata_popList(Pdata
*self
, int start
) {
274 l
=self
->length
-start
;
275 UNLESS (r
=PyList_New(l
)) return NULL
;
276 for (i
=start
, j
=0 ; j
< l
; i
++, j
++)
277 PyList_SET_ITEM(r
, j
, self
->data
[i
]);
283 #define PDATA_APPEND_(D,O,ER) { \
284 if (Pdata_Append(((Pdata*)(D)), O) < 0) return ER; \
287 #define PDATA_APPEND(D,O,ER) { \
288 if (((Pdata*)(D))->length == ((Pdata*)(D))->size && \
289 Pdata_grow((Pdata*)(D)) < 0) \
292 ((Pdata*)(D))->data[((Pdata*)(D))->length++]=O; \
295 #define PDATA_PUSH(D,O,ER) { \
296 if (((Pdata*)(D))->length == ((Pdata*)(D))->size && \
297 Pdata_grow((Pdata*)(D)) < 0) { \
301 ((Pdata*)(D))->data[((Pdata*)(D))->length++]=O; \
304 /*************************************************************************/
306 #define ARG_TUP(self, o) { \
307 if (self->arg || (self->arg=PyTuple_New(1))) { \
308 Py_XDECREF(PyTuple_GET_ITEM(self->arg,0)); \
309 PyTuple_SET_ITEM(self->arg,0,o); \
316 #define FREE_ARG_TUP(self) { \
317 if (self->arg->ob_refcnt > 1) { \
318 Py_DECREF(self->arg); \
323 typedef struct Picklerobject
{
331 PyObject
*inst_pers_func
;
333 int fast
; /* Fast mode doesn't save in memo, don't use if circ ref */
334 int (*write_func
)(struct Picklerobject
*, char *, int);
337 PyObject
*dispatch_table
;
340 staticforward PyTypeObject Picklertype
;
342 typedef struct Unpicklerobject
{
353 PyObject
*last_string
;
357 int (*read_func
)(struct Unpicklerobject
*, char **, int);
358 int (*readline_func
)(struct Unpicklerobject
*, char **);
361 PyObject
*safe_constructors
;
362 PyObject
*find_class
;
365 staticforward PyTypeObject Unpicklertype
;
367 /* Forward decls that need the above structs */
368 static int save(Picklerobject
*, PyObject
*, int);
369 static int put2(Picklerobject
*, PyObject
*);
372 cPickle_PyMapping_HasKey(PyObject
*o
, PyObject
*key
) {
375 if ((v
= PyObject_GetItem(o
,key
))) {
386 cPickle_ErrFormat(PyObject
*ErrType
, char *stringformat
, char *format
, ...)
389 PyObject
*args
=0, *retval
=0;
390 va_start(va
, format
);
392 if (format
) args
= Py_VaBuildValue(format
, va
);
394 if (format
&& ! args
) return NULL
;
395 if (stringformat
&& !(retval
=PyString_FromString(stringformat
))) return NULL
;
400 v
=PyString_Format(retval
, args
);
403 if (! v
) return NULL
;
408 if (args
) retval
=args
;
410 PyErr_SetObject(ErrType
,Py_None
);
413 PyErr_SetObject(ErrType
,retval
);
419 write_file(Picklerobject
*self
, char *s
, int n
) {
420 size_t nbyteswritten
;
426 Py_BEGIN_ALLOW_THREADS
427 nbyteswritten
= fwrite(s
, sizeof(char), n
, self
->fp
);
429 if (nbyteswritten
!= (size_t)n
) {
430 PyErr_SetFromErrno(PyExc_IOError
);
438 write_cStringIO(Picklerobject
*self
, char *s
, int n
) {
443 if (PycStringIO
->cwrite((PyObject
*)self
->file
, s
, n
) != n
) {
451 write_none(Picklerobject
*self
, char *s
, int n
) {
452 if (s
== NULL
) return 0;
457 write_other(Picklerobject
*self
, char *s
, int n
) {
458 PyObject
*py_str
= 0, *junk
= 0;
461 UNLESS (self
->buf_size
) return 0;
463 PyString_FromStringAndSize(self
->write_buf
, self
->buf_size
))
467 if (self
->buf_size
&& (n
+ self
->buf_size
) > WRITE_BUF_SIZE
) {
468 if (write_other(self
, NULL
, 0) < 0)
472 if (n
> WRITE_BUF_SIZE
) {
474 PyString_FromStringAndSize(s
, n
))
478 memcpy(self
->write_buf
+ self
->buf_size
, s
, n
);
485 /* object with write method */
486 ARG_TUP(self
, py_str
);
488 junk
= PyObject_CallObject(self
->write
, self
->arg
);
491 if (junk
) Py_DECREF(junk
);
495 PDATA_PUSH(self
->file
, py_str
, -1);
503 read_file(Unpicklerobject
*self
, char **s
, int n
) {
506 if (self
->buf_size
== 0) {
509 size
= ((n
< 32) ? 32 : n
);
510 UNLESS (self
->buf
= (char *)malloc(size
* sizeof(char))) {
515 self
->buf_size
= size
;
517 else if (n
> self
->buf_size
) {
518 UNLESS (self
->buf
= (char *)realloc(self
->buf
, n
* sizeof(char))) {
526 Py_BEGIN_ALLOW_THREADS
527 nbytesread
= fread(self
->buf
, sizeof(char), n
, self
->fp
);
529 if (nbytesread
!= (size_t)n
) {
530 if (feof(self
->fp
)) {
531 PyErr_SetNone(PyExc_EOFError
);
535 PyErr_SetFromErrno(PyExc_IOError
);
546 readline_file(Unpicklerobject
*self
, char **s
) {
549 if (self
->buf_size
== 0) {
550 UNLESS (self
->buf
= (char *)malloc(40 * sizeof(char))) {
560 for (; i
< (self
->buf_size
- 1); i
++) {
561 if (feof(self
->fp
) || (self
->buf
[i
] = getc(self
->fp
)) == '\n') {
562 self
->buf
[i
+ 1] = '\0';
568 UNLESS (self
->buf
= (char *)realloc(self
->buf
,
569 (self
->buf_size
* 2) * sizeof(char))) {
581 read_cStringIO(Unpicklerobject
*self
, char **s
, int n
) {
584 if (PycStringIO
->cread((PyObject
*)self
->file
, &ptr
, n
) != n
) {
585 PyErr_SetNone(PyExc_EOFError
);
596 readline_cStringIO(Unpicklerobject
*self
, char **s
) {
600 if ((n
= PycStringIO
->creadline((PyObject
*)self
->file
, &ptr
)) < 0) {
611 read_other(Unpicklerobject
*self
, char **s
, int n
) {
612 PyObject
*bytes
, *str
=0;
614 UNLESS (bytes
= PyInt_FromLong(n
)) return -1;
616 ARG_TUP(self
, bytes
);
618 str
= PyObject_CallObject(self
->read
, self
->arg
);
621 if (! str
) return -1;
623 Py_XDECREF(self
->last_string
);
624 self
->last_string
= str
;
626 if (! (*s
= PyString_AsString(str
))) return -1;
632 readline_other(Unpicklerobject
*self
, char **s
) {
636 UNLESS (str
= PyObject_CallObject(self
->readline
, empty_tuple
)) {
640 if ((str_size
= PyString_Size(str
)) < 0)
643 Py_XDECREF(self
->last_string
);
644 self
->last_string
= str
;
646 if (! (*s
= PyString_AsString(str
)))
654 pystrndup(char *s
, int l
) {
656 UNLESS (r
=malloc((l
+1)*sizeof(char))) return (char*)PyErr_NoMemory();
664 get(Picklerobject
*self
, PyObject
*id
) {
665 PyObject
*value
, *mv
;
670 UNLESS (mv
= PyDict_GetItem(self
->memo
, id
)) {
671 PyErr_SetObject(PyExc_KeyError
, id
);
675 UNLESS (value
= PyTuple_GetItem(mv
, 0))
678 UNLESS (PyInt_Check(value
)) {
679 PyErr_SetString(PicklingError
, "no int where int expected in memo");
682 c_value
= PyInt_AS_LONG((PyIntObject
*)value
);
686 sprintf(s
+ 1, "%ld\n", c_value
);
689 else if (Pdata_Check(self
->file
)) {
690 if (write_other(self
, NULL
, 0) < 0) return -1;
691 PDATA_APPEND(self
->file
, mv
, -1);
697 s
[1] = (int)(c_value
& 0xff);
702 s
[1] = (int)(c_value
& 0xff);
703 s
[2] = (int)((c_value
>> 8) & 0xff);
704 s
[3] = (int)((c_value
>> 16) & 0xff);
705 s
[4] = (int)((c_value
>> 24) & 0xff);
710 if ((*self
->write_func
)(self
, s
, len
) < 0)
718 put(Picklerobject
*self
, PyObject
*ob
) {
719 if (ob
->ob_refcnt
< 2 || self
->fast
)
722 return put2(self
, ob
);
727 put2(Picklerobject
*self
, PyObject
*ob
) {
732 PyObject
*py_ob_id
= 0, *memo_len
= 0, *t
= 0;
734 if (self
->fast
) return 0;
736 if ((p
= PyDict_Size(self
->memo
)) < 0)
739 p
++; /* Make sure memo keys are positive! */
741 UNLESS (py_ob_id
= PyLong_FromVoidPtr(ob
))
744 UNLESS (memo_len
= PyInt_FromLong(p
))
747 UNLESS (t
= PyTuple_New(2))
750 PyTuple_SET_ITEM(t
, 0, memo_len
);
752 PyTuple_SET_ITEM(t
, 1, ob
);
755 if (PyDict_SetItem(self
->memo
, py_ob_id
, t
) < 0)
760 sprintf(c_str
+ 1, "%d\n", p
);
763 else if (Pdata_Check(self
->file
)) {
764 if (write_other(self
, NULL
, 0) < 0) return -1;
765 PDATA_APPEND(self
->file
, memo_len
, -1);
766 res
=0; /* Job well done ;) */
771 c_str
[0] = LONG_BINPUT
;
772 c_str
[1] = (int)(p
& 0xff);
773 c_str
[2] = (int)((p
>> 8) & 0xff);
774 c_str
[3] = (int)((p
>> 16) & 0xff);
775 c_str
[4] = (int)((p
>> 24) & 0xff);
785 if ((*self
->write_func
)(self
, c_str
, len
) < 0)
791 Py_XDECREF(py_ob_id
);
792 Py_XDECREF(memo_len
);
798 #define PyImport_Import cPickle_Import
801 PyImport_Import(PyObject
*module_name
) {
802 static PyObject
*silly_list
=0, *__builtins___str
=0, *__import___str
;
803 static PyObject
*standard_builtins
=0;
804 PyObject
*globals
=0, *__import__
=0, *__builtins__
=0, *r
=0;
806 UNLESS (silly_list
) {
807 UNLESS (__import___str
=PyString_FromString("__import__"))
809 UNLESS (__builtins___str
=PyString_FromString("__builtins__"))
811 UNLESS (silly_list
=Py_BuildValue("[s]","__doc__"))
815 if ((globals
=PyEval_GetGlobals())) {
817 UNLESS (__builtins__
=PyObject_GetItem(globals
,__builtins___str
))
823 UNLESS (standard_builtins
||
824 (standard_builtins
=PyImport_ImportModule("__builtin__")))
827 __builtins__
=standard_builtins
;
828 Py_INCREF(__builtins__
);
829 UNLESS (globals
= Py_BuildValue("{sO}", "__builtins__", __builtins__
))
833 if (PyDict_Check(__builtins__
)) {
834 UNLESS (__import__
=PyObject_GetItem(__builtins__
,__import___str
)) goto err
;
837 UNLESS (__import__
=PyObject_GetAttr(__builtins__
,__import___str
)) goto err
;
840 UNLESS (r
=PyObject_CallFunction(__import__
,"OOOO",
841 module_name
, globals
, globals
, silly_list
))
845 Py_DECREF(__builtins__
);
846 Py_DECREF(__import__
);
851 Py_XDECREF(__builtins__
);
852 Py_XDECREF(__import__
);
857 whichmodule(PyObject
*global
, PyObject
*global_name
) {
859 PyObject
*module
= 0, *modules_dict
= 0,
860 *global_name_attr
= 0, *name
= 0;
862 module
= PyObject_GetAttrString(global
, "__module__");
863 if (module
) return module
;
866 UNLESS (modules_dict
= PySys_GetObject("modules"))
870 while ((j
= PyDict_Next(modules_dict
, &i
, &name
, &module
))) {
872 if (PyObject_Compare(name
, __main___str
)==0) continue;
874 UNLESS (global_name_attr
= PyObject_GetAttr(module
, global_name
)) {
879 if (global_name_attr
!= global
) {
880 Py_DECREF(global_name_attr
);
884 Py_DECREF(global_name_attr
);
889 /* The following implements the rule in pickle.py added in 1.5
890 that used __main__ if no module is found. I don't actually
904 save_none(Picklerobject
*self
, PyObject
*args
) {
905 static char none
= NONE
;
906 if ((*self
->write_func
)(self
, &none
, 1) < 0)
914 save_int(Picklerobject
*self
, PyObject
*args
) {
916 long l
= PyInt_AS_LONG((PyIntObject
*)args
);
925 /* Text-mode pickle, or long too big to fit in the 4-byte
926 * signed BININT format: store as a string.
929 sprintf(c_str
+ 1, "%ld\n", l
);
930 if ((*self
->write_func
)(self
, c_str
, strlen(c_str
)) < 0)
934 /* Binary pickle and l fits in a signed 4-byte int. */
935 c_str
[1] = (int)( l
& 0xff);
936 c_str
[2] = (int)((l
>> 8) & 0xff);
937 c_str
[3] = (int)((l
>> 16) & 0xff);
938 c_str
[4] = (int)((l
>> 24) & 0xff);
940 if ((c_str
[4] == 0) && (c_str
[3] == 0)) {
955 if ((*self
->write_func
)(self
, c_str
, len
) < 0)
964 save_long(Picklerobject
*self
, PyObject
*args
) {
968 static char l
= LONG
;
970 UNLESS (repr
= PyObject_Repr(args
))
973 if ((size
= PyString_Size(repr
)) < 0)
976 if ((*self
->write_func
)(self
, &l
, 1) < 0)
979 if ((*self
->write_func
)(self
,
980 PyString_AS_STRING((PyStringObject
*)repr
), size
) < 0)
983 if ((*self
->write_func
)(self
, "\n", 1) < 0)
996 save_float(Picklerobject
*self
, PyObject
*args
) {
997 double x
= PyFloat_AS_DOUBLE((PyFloatObject
*)args
);
1003 char str
[9], *p
= str
;
1017 /* Normalize f to be in the range [1.0, 2.0) */
1018 if (0.5 <= f
&& f
< 1.0) {
1022 else if (f
== 0.0) {
1026 PyErr_SetString(PyExc_SystemError
,
1027 "frexp() result out of range");
1032 /* XXX 1024 itself is reserved for Inf/NaN */
1033 PyErr_SetString(PyExc_OverflowError
,
1034 "float too large to pack with d format");
1037 else if (e
< -1022) {
1038 /* Gradual underflow */
1039 f
= ldexp(f
, 1022 + e
);
1042 else if (!(e
== 0 && f
== 0.0)) {
1044 f
-= 1.0; /* Get rid of leading 1 */
1047 /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
1048 f
*= 268435456.0; /* 2**28 */
1049 fhi
= (long) floor(f
); /* Truncate */
1051 f
*= 16777216.0; /* 2**24 */
1052 flo
= (long) floor(f
+ 0.5); /* Round */
1055 *p
= (s
<<7) | (e
>>4);
1059 *p
= (char) (((e
&0xF)<<4) | (fhi
>>24));
1063 *p
= (fhi
>>16) & 0xFF;
1067 *p
= (fhi
>>8) & 0xFF;
1075 *p
= (flo
>>16) & 0xFF;
1079 *p
= (flo
>>8) & 0xFF;
1085 if ((*self
->write_func
)(self
, str
, 9) < 0)
1091 sprintf(c_str
+ 1, "%.17g\n", x
);
1093 if ((*self
->write_func
)(self
, c_str
, strlen(c_str
)) < 0)
1102 save_string(Picklerobject
*self
, PyObject
*args
, int doput
) {
1106 if ((size
= PyString_Size(args
)) < 0)
1112 static char string
= STRING
;
1114 UNLESS (repr
= PyObject_Repr(args
))
1117 if ((len
= PyString_Size(repr
)) < 0)
1119 repr_str
= PyString_AS_STRING((PyStringObject
*)repr
);
1121 if ((*self
->write_func
)(self
, &string
, 1) < 0)
1124 if ((*self
->write_func
)(self
, repr_str
, len
) < 0)
1127 if ((*self
->write_func
)(self
, "\n", 1) < 0)
1136 if ((size
= PyString_Size(args
)) < 0)
1140 c_str
[0] = SHORT_BINSTRING
;
1145 c_str
[0] = BINSTRING
;
1146 for (i
= 1; i
< 5; i
++)
1147 c_str
[i
] = (int)(size
>> ((i
- 1) * 8));
1151 if ((*self
->write_func
)(self
, c_str
, len
) < 0)
1154 if (size
> 128 && Pdata_Check(self
->file
)) {
1155 if (write_other(self
, NULL
, 0) < 0) return -1;
1156 PDATA_APPEND(self
->file
, args
, -1);
1159 if ((*self
->write_func
)(self
,
1160 PyString_AS_STRING((PyStringObject
*)args
), size
) < 0)
1166 if (put(self
, args
) < 0)
1177 /* A copy of PyUnicode_EncodeRawUnicodeEscape() that also translates
1178 backslash and newline characters to \uXXXX escapes. */
1180 modified_EncodeRawUnicodeEscape(const Py_UNICODE
*s
, int size
)
1186 static const char *hexdigit
= "0123456789ABCDEF";
1188 repr
= PyString_FromStringAndSize(NULL
, 6 * size
);
1194 p
= q
= PyString_AS_STRING(repr
);
1195 while (size
-- > 0) {
1196 Py_UNICODE ch
= *s
++;
1197 /* Map 16-bit characters to '\uxxxx' */
1198 if (ch
>= 256 || ch
== '\\' || ch
== '\n') {
1201 *p
++ = hexdigit
[(ch
>> 12) & 0xf];
1202 *p
++ = hexdigit
[(ch
>> 8) & 0xf];
1203 *p
++ = hexdigit
[(ch
>> 4) & 0xf];
1204 *p
++ = hexdigit
[ch
& 15];
1206 /* Copy everything else as-is */
1211 if (_PyString_Resize(&repr
, p
- q
))
1223 save_unicode(Picklerobject
*self
, PyObject
*args
, int doput
) {
1227 if (!PyUnicode_Check(args
))
1232 static char string
= UNICODE
;
1234 UNLESS(repr
= modified_EncodeRawUnicodeEscape(
1235 PyUnicode_AS_UNICODE(args
), PyUnicode_GET_SIZE(args
)))
1238 if ((len
= PyString_Size(repr
)) < 0)
1240 repr_str
= PyString_AS_STRING((PyStringObject
*)repr
);
1242 if ((*self
->write_func
)(self
, &string
, 1) < 0)
1245 if ((*self
->write_func
)(self
, repr_str
, len
) < 0)
1248 if ((*self
->write_func
)(self
, "\n", 1) < 0)
1257 UNLESS (repr
= PyUnicode_AsUTF8String(args
))
1260 if ((size
= PyString_Size(repr
)) < 0)
1263 c_str
[0] = BINUNICODE
;
1264 for (i
= 1; i
< 5; i
++)
1265 c_str
[i
] = (int)(size
>> ((i
- 1) * 8));
1268 if ((*self
->write_func
)(self
, c_str
, len
) < 0)
1271 if (size
> 128 && Pdata_Check(self
->file
)) {
1272 if (write_other(self
, NULL
, 0) < 0)
1274 PDATA_APPEND(self
->file
, repr
, -1);
1277 if ((*self
->write_func
)(self
, PyString_AS_STRING(repr
), size
) < 0)
1285 if (put(self
, args
) < 0)
1297 save_tuple(Picklerobject
*self
, PyObject
*args
) {
1298 PyObject
*element
= 0, *py_tuple_id
= 0;
1299 int len
, i
, has_key
, res
= -1;
1301 static char tuple
= TUPLE
;
1303 if ((*self
->write_func
)(self
, &MARKv
, 1) < 0)
1306 if ((len
= PyTuple_Size(args
)) < 0)
1309 for (i
= 0; i
< len
; i
++) {
1310 UNLESS (element
= PyTuple_GET_ITEM((PyTupleObject
*)args
, i
))
1313 if (save(self
, element
, 0) < 0)
1317 UNLESS (py_tuple_id
= PyLong_FromVoidPtr(args
))
1321 if ((has_key
= cPickle_PyMapping_HasKey(self
->memo
, py_tuple_id
)) < 0)
1326 static char pop_mark
= POP_MARK
;
1328 if ((*self
->write_func
)(self
, &pop_mark
, 1) < 0)
1332 static char pop
= POP
;
1334 for (i
= 0; i
<= len
; i
++) {
1335 if ((*self
->write_func
)(self
, &pop
, 1) < 0)
1340 if (get(self
, py_tuple_id
) < 0)
1348 if ((*self
->write_func
)(self
, &tuple
, 1) < 0) {
1352 if (put(self
, args
) < 0)
1358 Py_XDECREF(py_tuple_id
);
1364 save_empty_tuple(Picklerobject
*self
, PyObject
*args
) {
1365 static char tuple
= EMPTY_TUPLE
;
1367 return (*self
->write_func
)(self
, &tuple
, 1);
1372 save_list(Picklerobject
*self
, PyObject
*args
) {
1373 PyObject
*element
= 0;
1374 int s_len
, len
, i
, using_appends
, res
= -1;
1377 static char append
= APPEND
, appends
= APPENDS
;
1389 if ((len
= PyList_Size(args
)) < 0)
1392 if ((*self
->write_func
)(self
, s
, s_len
) < 0)
1396 if (put(self
, args
) < 0)
1400 if (put2(self
, args
) < 0)
1404 if ((using_appends
= (self
->bin
&& (len
> 1))))
1405 if ((*self
->write_func
)(self
, &MARKv
, 1) < 0)
1408 for (i
= 0; i
< len
; i
++) {
1409 UNLESS (element
= PyList_GET_ITEM((PyListObject
*)args
, i
))
1412 if (save(self
, element
, 0) < 0)
1415 if (!using_appends
) {
1416 if ((*self
->write_func
)(self
, &append
, 1) < 0)
1421 if (using_appends
) {
1422 if ((*self
->write_func
)(self
, &appends
, 1) < 0)
1435 save_dict(Picklerobject
*self
, PyObject
*args
) {
1436 PyObject
*key
= 0, *value
= 0;
1437 int i
, len
, res
= -1, using_setitems
;
1440 static char setitem
= SETITEM
, setitems
= SETITEMS
;
1452 if ((*self
->write_func
)(self
, s
, len
) < 0)
1455 if ((len
= PyDict_Size(args
)) < 0)
1459 if (put(self
, args
) < 0)
1463 if (put2(self
, args
) < 0)
1467 if ((using_setitems
= (self
->bin
&& (PyDict_Size(args
) > 1))))
1468 if ((*self
->write_func
)(self
, &MARKv
, 1) < 0)
1472 while (PyDict_Next(args
, &i
, &key
, &value
)) {
1473 if (save(self
, key
, 0) < 0)
1476 if (save(self
, value
, 0) < 0)
1479 if (!using_setitems
) {
1480 if ((*self
->write_func
)(self
, &setitem
, 1) < 0)
1485 if (using_setitems
) {
1486 if ((*self
->write_func
)(self
, &setitems
, 1) < 0)
1499 save_inst(Picklerobject
*self
, PyObject
*args
) {
1500 PyObject
*class = 0, *module
= 0, *name
= 0, *state
= 0,
1501 *getinitargs_func
= 0, *getstate_func
= 0, *class_args
= 0;
1502 char *module_str
, *name_str
;
1503 int module_size
, name_size
, res
= -1;
1505 static char inst
= INST
, obj
= OBJ
, build
= BUILD
;
1507 if ((*self
->write_func
)(self
, &MARKv
, 1) < 0)
1510 UNLESS (class = PyObject_GetAttr(args
, __class___str
))
1514 if (save(self
, class, 0) < 0)
1518 if ((getinitargs_func
= PyObject_GetAttr(args
, __getinitargs___str
))) {
1519 PyObject
*element
= 0;
1522 UNLESS (class_args
=
1523 PyObject_CallObject(getinitargs_func
, empty_tuple
))
1526 if ((len
= PyObject_Size(class_args
)) < 0)
1529 for (i
= 0; i
< len
; i
++) {
1530 UNLESS (element
= PySequence_GetItem(class_args
, i
))
1533 if (save(self
, element
, 0) < 0) {
1546 UNLESS (name
= ((PyClassObject
*)class)->cl_name
) {
1547 PyErr_SetString(PicklingError
, "class has no name");
1551 UNLESS (module
= whichmodule(class, name
))
1555 if ((module_size
= PyString_Size(module
)) < 0 ||
1556 (name_size
= PyString_Size(name
)) < 0)
1559 module_str
= PyString_AS_STRING((PyStringObject
*)module
);
1560 name_str
= PyString_AS_STRING((PyStringObject
*)name
);
1562 if ((*self
->write_func
)(self
, &inst
, 1) < 0)
1565 if ((*self
->write_func
)(self
, module_str
, module_size
) < 0)
1568 if ((*self
->write_func
)(self
, "\n", 1) < 0)
1571 if ((*self
->write_func
)(self
, name_str
, name_size
) < 0)
1574 if ((*self
->write_func
)(self
, "\n", 1) < 0)
1577 else if ((*self
->write_func
)(self
, &obj
, 1) < 0) {
1581 if ((getstate_func
= PyObject_GetAttr(args
, __getstate___str
))) {
1582 UNLESS (state
= PyObject_CallObject(getstate_func
, empty_tuple
))
1588 UNLESS (state
= PyObject_GetAttr(args
, __dict___str
)) {
1595 if (!PyDict_Check(state
)) {
1596 if (put2(self
, args
) < 0)
1600 if (put(self
, args
) < 0)
1604 if (save(self
, state
, 0) < 0)
1607 if ((*self
->write_func
)(self
, &build
, 1) < 0)
1616 Py_XDECREF(getinitargs_func
);
1617 Py_XDECREF(getstate_func
);
1618 Py_XDECREF(class_args
);
1625 save_global(Picklerobject
*self
, PyObject
*args
, PyObject
*name
) {
1626 PyObject
*global_name
= 0, *module
= 0;
1627 char *name_str
, *module_str
;
1628 int module_size
, name_size
, res
= -1;
1630 static char global
= GLOBAL
;
1634 Py_INCREF(global_name
);
1637 UNLESS (global_name
= PyObject_GetAttr(args
, __name___str
))
1641 UNLESS (module
= whichmodule(args
, global_name
))
1644 if ((module_size
= PyString_Size(module
)) < 0 ||
1645 (name_size
= PyString_Size(global_name
)) < 0)
1648 module_str
= PyString_AS_STRING((PyStringObject
*)module
);
1649 name_str
= PyString_AS_STRING((PyStringObject
*)global_name
);
1651 if ((*self
->write_func
)(self
, &global
, 1) < 0)
1654 if ((*self
->write_func
)(self
, module_str
, module_size
) < 0)
1657 if ((*self
->write_func
)(self
, "\n", 1) < 0)
1660 if ((*self
->write_func
)(self
, name_str
, name_size
) < 0)
1663 if ((*self
->write_func
)(self
, "\n", 1) < 0)
1666 if (put(self
, args
) < 0)
1673 Py_XDECREF(global_name
);
1679 save_pers(Picklerobject
*self
, PyObject
*args
, PyObject
*f
) {
1683 static char persid
= PERSID
, binpersid
= BINPERSID
;
1686 ARG_TUP(self
, args
);
1688 pid
= PyObject_CallObject(f
, self
->arg
);
1691 if (! pid
) return -1;
1693 if (pid
!= Py_None
) {
1695 if (!PyString_Check(pid
)) {
1696 PyErr_SetString(PicklingError
,
1697 "persistent id must be string");
1701 if ((*self
->write_func
)(self
, &persid
, 1) < 0)
1704 if ((size
= PyString_Size(pid
)) < 0)
1707 if ((*self
->write_func
)(self
,
1708 PyString_AS_STRING((PyStringObject
*)pid
), size
) < 0)
1711 if ((*self
->write_func
)(self
, "\n", 1) < 0)
1717 else if (save(self
, pid
, 1) >= 0) {
1718 if ((*self
->write_func
)(self
, &binpersid
, 1) < 0)
1737 save_reduce(Picklerobject
*self
, PyObject
*callable
,
1738 PyObject
*tup
, PyObject
*state
, PyObject
*ob
) {
1739 static char reduce
= REDUCE
, build
= BUILD
;
1741 if (save(self
, callable
, 0) < 0)
1744 if (save(self
, tup
, 0) < 0)
1747 if ((*self
->write_func
)(self
, &reduce
, 1) < 0)
1751 if (state
&& !PyDict_Check(state
)) {
1752 if (put2(self
, ob
) < 0)
1756 if (put(self
, ob
) < 0)
1762 if (save(self
, state
, 0) < 0)
1765 if ((*self
->write_func
)(self
, &build
, 1) < 0)
1773 save(Picklerobject
*self
, PyObject
*args
, int pers_save
) {
1775 PyObject
*py_ob_id
= 0, *__reduce__
= 0, *t
= 0, *arg_tup
= 0,
1776 *callable
= 0, *state
= 0;
1777 int res
= -1, tmp
, size
;
1779 if (!pers_save
&& self
->pers_func
) {
1780 if ((tmp
= save_pers(self
, args
, self
->pers_func
)) != 0) {
1786 if (args
== Py_None
) {
1787 res
= save_none(self
, args
);
1791 type
= args
->ob_type
;
1793 switch (type
->tp_name
[0]) {
1795 if (type
== &PyInt_Type
) {
1796 res
= save_int(self
, args
);
1802 if (type
== &PyLong_Type
) {
1803 res
= save_long(self
, args
);
1809 if (type
== &PyFloat_Type
) {
1810 res
= save_float(self
, args
);
1816 if (type
== &PyTuple_Type
&& PyTuple_Size(args
)==0) {
1817 if (self
->bin
) res
= save_empty_tuple(self
, args
);
1818 else res
= save_tuple(self
, args
);
1824 if ((type
== &PyString_Type
) && (PyString_GET_SIZE(args
) < 2)) {
1825 res
= save_string(self
, args
, 0);
1830 if ((type
== &PyUnicode_Type
) && (PyString_GET_SIZE(args
) < 2)) {
1831 res
= save_unicode(self
, args
, 0);
1836 if (args
->ob_refcnt
> 1) {
1839 UNLESS (py_ob_id
= PyLong_FromVoidPtr(args
))
1842 if ((has_key
= cPickle_PyMapping_HasKey(self
->memo
, py_ob_id
)) < 0)
1846 if (get(self
, py_ob_id
) < 0)
1854 switch (type
->tp_name
[0]) {
1856 if (type
== &PyString_Type
) {
1857 res
= save_string(self
, args
, 1);
1863 if (type
== &PyUnicode_Type
) {
1864 res
= save_unicode(self
, args
, 1);
1870 if (type
== &PyTuple_Type
) {
1871 res
= save_tuple(self
, args
);
1877 if (type
== &PyList_Type
) {
1878 res
= save_list(self
, args
);
1884 if (type
== &PyDict_Type
) {
1885 res
= save_dict(self
, args
);
1891 if (type
== &PyInstance_Type
) {
1892 res
= save_inst(self
, args
);
1898 if (type
== &PyClass_Type
) {
1899 res
= save_global(self
, args
, NULL
);
1905 if (type
== &PyFunction_Type
) {
1906 res
= save_global(self
, args
, NULL
);
1912 if (type
== &PyCFunction_Type
) {
1913 res
= save_global(self
, args
, NULL
);
1918 if (!pers_save
&& self
->inst_pers_func
) {
1919 if ((tmp
= save_pers(self
, args
, self
->inst_pers_func
)) != 0) {
1925 if ((__reduce__
= PyDict_GetItem(dispatch_table
, (PyObject
*)type
))) {
1926 Py_INCREF(__reduce__
);
1929 ARG_TUP(self
, args
);
1931 t
= PyObject_CallObject(__reduce__
, self
->arg
);
1934 if (! t
) goto finally
;
1939 if ((__reduce__
= PyObject_GetAttr(args
, __reduce___str
))) {
1940 UNLESS (t
= PyObject_CallObject(__reduce__
, empty_tuple
))
1949 if (PyString_Check(t
)) {
1950 res
= save_global(self
, args
, t
);
1954 if (!PyTuple_Check(t
)) {
1955 cPickle_ErrFormat(PicklingError
, "Value returned by %s must "
1956 "be a tuple", "O", __reduce__
);
1960 size
= PyTuple_Size(t
);
1962 if ((size
!= 3) && (size
!= 2)) {
1963 cPickle_ErrFormat(PicklingError
, "tuple returned by %s must "
1964 "contain only two or three elements", "O", __reduce__
);
1968 callable
= PyTuple_GET_ITEM(t
, 0);
1970 arg_tup
= PyTuple_GET_ITEM(t
, 1);
1973 state
= PyTuple_GET_ITEM(t
, 2);
1976 UNLESS (PyTuple_Check(arg_tup
) || arg_tup
==Py_None
) {
1977 cPickle_ErrFormat(PicklingError
, "Second element of tuple "
1978 "returned by %s must be a tuple", "O", __reduce__
);
1982 res
= save_reduce(self
, callable
, arg_tup
, state
, args
);
1986 PyErr_SetObject(UnpickleableError
, args
);
1989 Py_XDECREF(py_ob_id
);
1990 Py_XDECREF(__reduce__
);
1998 dump(Picklerobject
*self
, PyObject
*args
) {
1999 static char stop
= STOP
;
2001 if (save(self
, args
, 0) < 0)
2004 if ((*self
->write_func
)(self
, &stop
, 1) < 0)
2007 if ((*self
->write_func
)(self
, NULL
, 0) < 0)
2014 Pickle_clear_memo(Picklerobject
*self
, PyObject
*args
) {
2015 if (args
&& ! PyArg_ParseTuple(args
,":clear_memo")) return NULL
;
2016 if (self
->memo
) PyDict_Clear(self
->memo
);
2022 Pickle_getvalue(Picklerobject
*self
, PyObject
*args
) {
2023 int l
, i
, rsize
, ssize
, clear
=1, lm
;
2026 char *s
, *p
, *have_get
;
2029 if (args
&& ! PyArg_ParseTuple(args
,"|i:getvalue",&clear
)) return NULL
;
2031 /* Check to make sure we are based on a list */
2032 if (! Pdata_Check(self
->file
)) {
2033 PyErr_SetString(PicklingError
,
2034 "Attempt to getvalue a non-list-based pickler");
2038 /* flush write buffer */
2039 if (write_other(self
, NULL
, 0) < 0) return NULL
;
2041 data
=(Pdata
*)self
->file
;
2044 /* set up an array to hold get/put status */
2045 if ((lm
=PyDict_Size(self
->memo
)) < 0) return NULL
;
2047 if (! (have_get
=malloc((lm
)*sizeof(char)))) return PyErr_NoMemory();
2048 memset(have_get
,0,lm
);
2050 /* Scan for gets. */
2051 for (rsize
=0, i
=l
; --i
>= 0; ) {
2054 if (PyString_Check(k
)) {
2055 rsize
+= PyString_GET_SIZE(k
);
2058 else if (PyInt_Check(k
)) { /* put */
2059 ik
=PyInt_AS_LONG((PyIntObject
*)k
);
2060 if (ik
>= lm
|| ik
==0) {
2061 PyErr_SetString(PicklingError
,
2062 "Invalid get data");
2065 if (have_get
[ik
]) { /* with matching get */
2066 if (ik
< 256) rsize
+= 2;
2071 else if (! (PyTuple_Check(k
) &&
2072 PyTuple_GET_SIZE(k
) == 2 &&
2073 PyInt_Check((k
=PyTuple_GET_ITEM(k
,0))))
2075 PyErr_SetString(PicklingError
,
2076 "Unexpected data in internal list");
2081 ik
=PyInt_AS_LONG((PyIntObject
*)k
);
2082 if (ik
>= lm
|| ik
==0) {
2083 PyErr_SetString(PicklingError
,
2084 "Invalid get data");
2088 if (ik
< 256) rsize
+= 2;
2094 /* Now generate the result */
2095 UNLESS (r
=PyString_FromStringAndSize(NULL
,rsize
)) goto err
;
2096 s
=PyString_AS_STRING((PyStringObject
*)r
);
2098 for (i
=0; i
<l
; i
++) {
2101 if (PyString_Check(k
)) {
2102 ssize
=PyString_GET_SIZE(k
);
2104 p
=PyString_AS_STRING((PyStringObject
*)k
);
2105 while (--ssize
>= 0) *s
++=*p
++;
2109 else if (PyTuple_Check(k
)) { /* get */
2110 ik
=PyInt_AS_LONG((PyIntObject
*)PyTuple_GET_ITEM(k
,0));
2113 *s
++ = (int)(ik
& 0xff);
2117 *s
++ = (int)(ik
& 0xff);
2118 *s
++ = (int)((ik
>> 8) & 0xff);
2119 *s
++ = (int)((ik
>> 16) & 0xff);
2120 *s
++ = (int)((ik
>> 24) & 0xff);
2125 ik
=PyInt_AS_LONG((PyIntObject
*)k
);
2127 if (have_get
[ik
]) { /* with matching get */
2130 *s
++ = (int)(ik
& 0xff);
2134 *s
++ = (int)(ik
& 0xff);
2135 *s
++ = (int)((ik
>> 8) & 0xff);
2136 *s
++ = (int)((ik
>> 16) & 0xff);
2137 *s
++ = (int)((ik
>> 24) & 0xff);
2145 PyDict_Clear(self
->memo
);
2146 Pdata_clear(data
,0);
2157 Pickler_dump(Picklerobject
*self
, PyObject
*args
) {
2161 UNLESS (PyArg_ParseTuple(args
, "O|i:dump", &ob
, &get
))
2164 if (dump(self
, ob
) < 0)
2167 if (get
) return Pickle_getvalue(self
, NULL
);
2170 return (PyObject
*)self
;
2174 static struct PyMethodDef Pickler_methods
[] = {
2175 {"dump", (PyCFunction
)Pickler_dump
, 1,
2177 "Write an object in pickle format to the object's pickle stream\n"
2179 {"clear_memo", (PyCFunction
)Pickle_clear_memo
, 1,
2180 "clear_memo() -- Clear the picklers memo"},
2181 {"getvalue", (PyCFunction
)Pickle_getvalue
, 1,
2182 "getvalue() -- Finish picking a list-based pickle"},
2183 {NULL
, NULL
} /* sentinel */
2187 static Picklerobject
*
2188 newPicklerobject(PyObject
*file
, int bin
) {
2189 Picklerobject
*self
;
2191 UNLESS (self
= PyObject_New(Picklerobject
, &Picklertype
))
2198 self
->pers_func
= NULL
;
2199 self
->inst_pers_func
= NULL
;
2200 self
->write_buf
= NULL
;
2204 self
->dispatch_table
= NULL
;
2211 UNLESS (self
->file
= file
)
2214 UNLESS (self
->memo
= PyDict_New())
2217 if (PyFile_Check(file
)) {
2218 self
->fp
= PyFile_AsFile(file
);
2219 if (self
->fp
== NULL
) {
2220 PyErr_SetString(PyExc_ValueError
, "I/O operation on closed file");
2223 self
->write_func
= write_file
;
2225 else if (PycStringIO_OutputCheck(file
)) {
2226 self
->write_func
= write_cStringIO
;
2228 else if (file
== Py_None
) {
2229 self
->write_func
= write_none
;
2232 self
->write_func
= write_other
;
2234 if (! Pdata_Check(file
)) {
2235 UNLESS (self
->write
= PyObject_GetAttr(file
, write_str
)) {
2237 PyErr_SetString(PyExc_TypeError
, "argument must have 'write' "
2243 UNLESS (self
->write_buf
=
2244 (char *)malloc(WRITE_BUF_SIZE
* sizeof(char))) {
2250 if (PyEval_GetRestricted()) {
2251 /* Restricted execution, get private tables */
2254 UNLESS (m
=PyImport_Import(copy_reg_str
)) goto err
;
2255 self
->dispatch_table
=PyObject_GetAttr(m
, dispatch_table_str
);
2257 UNLESS (self
->dispatch_table
) goto err
;
2260 self
->dispatch_table
=dispatch_table
;
2261 Py_INCREF(dispatch_table
);
2267 Py_DECREF((PyObject
*)self
);
2273 get_Pickler(PyObject
*self
, PyObject
*args
) {
2274 PyObject
*file
=NULL
;
2278 if (! PyArg_ParseTuple(args
, "|i:Pickler", &bin
)) {
2281 if (! PyArg_ParseTuple(args
, "O|i:Pickler", &file
, &bin
))
2284 return (PyObject
*)newPicklerobject(file
, bin
);
2289 Pickler_dealloc(Picklerobject
*self
) {
2290 Py_XDECREF(self
->write
);
2291 Py_XDECREF(self
->memo
);
2292 Py_XDECREF(self
->arg
);
2293 Py_XDECREF(self
->file
);
2294 Py_XDECREF(self
->pers_func
);
2295 Py_XDECREF(self
->inst_pers_func
);
2296 Py_XDECREF(self
->dispatch_table
);
2298 if (self
->write_buf
) {
2299 free(self
->write_buf
);
2307 Pickler_getattr(Picklerobject
*self
, char *name
) {
2311 if (strcmp(name
, "persistent_id") == 0) {
2312 if (!self
->pers_func
) {
2313 PyErr_SetString(PyExc_AttributeError
, name
);
2317 Py_INCREF(self
->pers_func
);
2318 return self
->pers_func
;
2322 if (strcmp(name
, "memo") == 0) {
2324 PyErr_SetString(PyExc_AttributeError
, name
);
2328 Py_INCREF(self
->memo
);
2333 if (strcmp(name
, "PicklingError") == 0) {
2334 Py_INCREF(PicklingError
);
2335 return PicklingError
;
2339 if (strcmp(name
, "binary")==0)
2340 return PyInt_FromLong(self
->bin
);
2343 if (strcmp(name
, "fast")==0)
2344 return PyInt_FromLong(self
->fast
);
2347 if (strcmp(name
, "getvalue")==0 && ! Pdata_Check(self
->file
)) {
2348 PyErr_SetString(PyExc_AttributeError
, name
);
2353 return Py_FindMethod(Pickler_methods
, (PyObject
*)self
, name
);
2358 Pickler_setattr(Picklerobject
*self
, char *name
, PyObject
*value
) {
2361 PyErr_SetString(PyExc_TypeError
,
2362 "attribute deletion is not supported");
2366 if (strcmp(name
, "persistent_id") == 0) {
2367 Py_XDECREF(self
->pers_func
);
2368 self
->pers_func
= value
;
2373 if (strcmp(name
, "inst_persistent_id") == 0) {
2374 Py_XDECREF(self
->inst_pers_func
);
2375 self
->inst_pers_func
= value
;
2380 if (strcmp(name
, "memo") == 0) {
2381 if (! PyDict_Check(value
)) {
2382 PyErr_SetString(PyExc_TypeError
, "memo must be a dictionary");
2385 Py_XDECREF(self
->memo
);
2391 if (strcmp(name
, "binary")==0) {
2392 self
->bin
=PyObject_IsTrue(value
);
2396 if (strcmp(name
, "fast")==0) {
2397 self
->fast
=PyObject_IsTrue(value
);
2401 PyErr_SetString(PyExc_AttributeError
, name
);
2406 static char Picklertype__doc__
[] =
2407 "Objects that know how to pickle objects\n"
2410 static PyTypeObject Picklertype
= {
2411 PyObject_HEAD_INIT(NULL
)
2413 "Pickler", /*tp_name*/
2414 sizeof(Picklerobject
), /*tp_basicsize*/
2417 (destructor
)Pickler_dealloc
, /*tp_dealloc*/
2418 (printfunc
)0, /*tp_print*/
2419 (getattrfunc
)Pickler_getattr
, /*tp_getattr*/
2420 (setattrfunc
)Pickler_setattr
, /*tp_setattr*/
2421 (cmpfunc
)0, /*tp_compare*/
2422 (reprfunc
)0, /*tp_repr*/
2424 0, /*tp_as_sequence*/
2425 0, /*tp_as_mapping*/
2426 (hashfunc
)0, /*tp_hash*/
2427 (ternaryfunc
)0, /*tp_call*/
2428 (reprfunc
)0, /*tp_str*/
2430 /* Space for future expansion */
2432 Picklertype__doc__
/* Documentation string */
2436 find_class(PyObject
*py_module_name
, PyObject
*py_global_name
, PyObject
*fc
) {
2437 PyObject
*global
= 0, *module
;
2441 PyErr_SetString(UnpicklingError
,
2442 "Global and instance pickles are not supported.");
2445 return PyObject_CallFunction(fc
, "OO", py_module_name
, py_global_name
);
2448 module
= PySys_GetObject("modules");
2452 module
= PyDict_GetItem(module
, py_module_name
);
2453 if (module
== NULL
) {
2454 module
= PyImport_Import(py_module_name
);
2457 global
= PyObject_GetAttr(module
, py_global_name
);
2461 global
= PyObject_GetAttr(module
, py_global_name
);
2462 if (global
== NULL
) {
2464 sprintf(buf
, "Failed to import class %.128s from module %.128s",
2465 PyString_AS_STRING((PyStringObject
*)py_global_name
),
2466 PyString_AS_STRING((PyStringObject
*)py_module_name
));
2467 PyErr_SetString(PyExc_SystemError
, buf
);
2474 marker(Unpicklerobject
*self
) {
2475 if (self
->num_marks
< 1) {
2476 PyErr_SetString(UnpicklingError
, "could not find MARK");
2480 return self
->marks
[--self
->num_marks
];
2485 load_none(Unpicklerobject
*self
) {
2486 PDATA_APPEND(self
->stack
, Py_None
, -1);
2491 bad_readline(void) {
2492 PyErr_SetString(UnpicklingError
, "pickle data was truncated");
2497 load_int(Unpicklerobject
*self
) {
2498 PyObject
*py_int
= 0;
2503 if ((len
= (*self
->readline_func
)(self
, &s
)) < 0) return -1;
2504 if (len
< 2) return bad_readline();
2505 UNLESS (s
=pystrndup(s
,len
)) return -1;
2508 l
= strtol(s
, &endptr
, 0);
2510 if (errno
|| (*endptr
!= '\n') || (endptr
[1] != '\0')) {
2511 /* Hm, maybe we've got something long. Let's try reading
2512 it as a Python long object. */
2514 UNLESS (py_int
=PyLong_FromString(s
,&endptr
,0)) goto finally
;
2516 if ((*endptr
!= '\n') || (endptr
[1] != '\0')) {
2517 PyErr_SetString(PyExc_ValueError
,
2518 "could not convert string to int");
2523 UNLESS (py_int
= PyInt_FromLong(l
)) goto finally
;
2527 PDATA_PUSH(self
->stack
, py_int
, -1);
2538 calc_binint(char *s
, int x
) {
2543 for (i
= 0, l
= 0L; i
< x
; i
++) {
2544 c
= (unsigned char)s
[i
];
2545 l
|= (long)c
<< (i
* 8);
2548 /* Unlike BININT1 and BININT2, BININT (more accurately BININT4)
2549 * is signed, so on a box with longs bigger than 4 bytes we need
2550 * to extend a BININT's sign bit to the full width.
2552 if (x
== 4 && l
& (1L << 31))
2560 load_binintx(Unpicklerobject
*self
, char *s
, int x
) {
2561 PyObject
*py_int
= 0;
2564 l
= calc_binint(s
, x
);
2566 UNLESS (py_int
= PyInt_FromLong(l
))
2569 PDATA_PUSH(self
->stack
, py_int
, -1);
2575 load_binint(Unpicklerobject
*self
) {
2578 if ((*self
->read_func
)(self
, &s
, 4) < 0)
2581 return load_binintx(self
, s
, 4);
2586 load_binint1(Unpicklerobject
*self
) {
2589 if ((*self
->read_func
)(self
, &s
, 1) < 0)
2592 return load_binintx(self
, s
, 1);
2597 load_binint2(Unpicklerobject
*self
) {
2600 if ((*self
->read_func
)(self
, &s
, 2) < 0)
2603 return load_binintx(self
, s
, 2);
2607 load_long(Unpicklerobject
*self
) {
2612 if ((len
= (*self
->readline_func
)(self
, &s
)) < 0) return -1;
2613 if (len
< 2) return bad_readline();
2614 UNLESS (s
=pystrndup(s
,len
)) return -1;
2616 UNLESS (l
= PyLong_FromString(s
, &end
, 0))
2620 PDATA_PUSH(self
->stack
, l
, -1);
2631 load_float(Unpicklerobject
*self
) {
2632 PyObject
*py_float
= 0;
2637 if ((len
= (*self
->readline_func
)(self
, &s
)) < 0) return -1;
2638 if (len
< 2) return bad_readline();
2639 UNLESS (s
=pystrndup(s
,len
)) return -1;
2642 d
= strtod(s
, &endptr
);
2644 if (errno
|| (endptr
[0] != '\n') || (endptr
[1] != '\0')) {
2645 PyErr_SetString(PyExc_ValueError
,
2646 "could not convert string to float");
2650 UNLESS (py_float
= PyFloat_FromDouble(d
))
2654 PDATA_PUSH(self
->stack
, py_float
, -1);
2664 load_binfloat(Unpicklerobject
*self
) {
2665 PyObject
*py_float
= 0;
2671 if ((*self
->read_func
)(self
, &p
, 8) < 0)
2676 e
= (*p
& 0x7F) << 4;
2681 fhi
= (*p
& 0xF) << 24;
2685 fhi
|= (*p
& 0xFF) << 16;
2689 fhi
|= (*p
& 0xFF) << 8;
2697 flo
= (*p
& 0xFF) << 16;
2701 flo
|= (*p
& 0xFF) << 8;
2707 x
= (double)fhi
+ (double)flo
/ 16777216.0; /* 2**24 */
2708 x
/= 268435456.0; /* 2**28 */
2710 /* XXX This sadly ignores Inf/NaN */
2722 UNLESS (py_float
= PyFloat_FromDouble(x
)) return -1;
2724 PDATA_PUSH(self
->stack
, py_float
, -1);
2729 load_string(Unpicklerobject
*self
) {
2731 int len
, res
= -1, nslash
;
2734 static PyObject
*eval_dict
= 0;
2736 if ((len
= (*self
->readline_func
)(self
, &s
)) < 0) return -1;
2737 if (len
< 2) return bad_readline();
2738 UNLESS (s
=pystrndup(s
,len
)) return -1;
2740 /* Check for unquoted quotes (evil strings) */
2742 if (q
!= '"' && q
!= '\'') goto insecure
;
2743 for (p
=s
+1, nslash
=0; *p
; p
++) {
2744 if (*p
==q
&& nslash
%2==0) break;
2745 if (*p
=='\\') nslash
++;
2750 for (p
++; *p
; p
++) if (*p
> ' ') goto insecure
;
2753 /********************************************/
2756 UNLESS (eval_dict
= Py_BuildValue("{s{}}", "__builtins__"))
2759 UNLESS (str
= PyRun_String(s
, Py_eval_input
, eval_dict
, eval_dict
))
2763 PDATA_PUSH(self
->stack
, str
, -1);
2773 PyErr_SetString(PyExc_ValueError
,"insecure string pickle");
2779 load_binstring(Unpicklerobject
*self
) {
2780 PyObject
*py_string
= 0;
2784 if ((*self
->read_func
)(self
, &s
, 4) < 0) return -1;
2786 l
= calc_binint(s
, 4);
2788 if ((*self
->read_func
)(self
, &s
, l
) < 0)
2791 UNLESS (py_string
= PyString_FromStringAndSize(s
, l
))
2794 PDATA_PUSH(self
->stack
, py_string
, -1);
2800 load_short_binstring(Unpicklerobject
*self
) {
2801 PyObject
*py_string
= 0;
2805 if ((*self
->read_func
)(self
, &s
, 1) < 0)
2808 l
= (unsigned char)s
[0];
2810 if ((*self
->read_func
)(self
, &s
, l
) < 0) return -1;
2812 UNLESS (py_string
= PyString_FromStringAndSize(s
, l
)) return -1;
2814 PDATA_PUSH(self
->stack
, py_string
, -1);
2820 load_unicode(Unpicklerobject
*self
) {
2825 if ((len
= (*self
->readline_func
)(self
, &s
)) < 0) return -1;
2826 if (len
< 1) return bad_readline();
2828 UNLESS (str
= PyUnicode_DecodeRawUnicodeEscape(s
, len
- 1, NULL
))
2831 PDATA_PUSH(self
->stack
, str
, -1);
2840 load_binunicode(Unpicklerobject
*self
) {
2845 if ((*self
->read_func
)(self
, &s
, 4) < 0) return -1;
2847 l
= calc_binint(s
, 4);
2849 if ((*self
->read_func
)(self
, &s
, l
) < 0)
2852 UNLESS (unicode
= PyUnicode_DecodeUTF8(s
, l
, NULL
))
2855 PDATA_PUSH(self
->stack
, unicode
, -1);
2861 load_tuple(Unpicklerobject
*self
) {
2865 if ((i
= marker(self
)) < 0) return -1;
2866 UNLESS (tup
=Pdata_popTuple(self
->stack
, i
)) return -1;
2867 PDATA_PUSH(self
->stack
, tup
, -1);
2872 load_empty_tuple(Unpicklerobject
*self
) {
2875 UNLESS (tup
=PyTuple_New(0)) return -1;
2876 PDATA_PUSH(self
->stack
, tup
, -1);
2881 load_empty_list(Unpicklerobject
*self
) {
2884 UNLESS (list
=PyList_New(0)) return -1;
2885 PDATA_PUSH(self
->stack
, list
, -1);
2890 load_empty_dict(Unpicklerobject
*self
) {
2893 UNLESS (dict
=PyDict_New()) return -1;
2894 PDATA_PUSH(self
->stack
, dict
, -1);
2900 load_list(Unpicklerobject
*self
) {
2904 if ((i
= marker(self
)) < 0) return -1;
2905 UNLESS (list
=Pdata_popList(self
->stack
, i
)) return -1;
2906 PDATA_PUSH(self
->stack
, list
, -1);
2911 load_dict(Unpicklerobject
*self
) {
2912 PyObject
*dict
, *key
, *value
;
2915 if ((i
= marker(self
)) < 0) return -1;
2916 j
=self
->stack
->length
;
2918 UNLESS (dict
= PyDict_New()) return -1;
2920 for (k
= i
+1; k
< j
; k
+= 2) {
2921 key
=self
->stack
->data
[k
-1];
2922 value
=self
->stack
->data
[k
];
2923 if (PyDict_SetItem(dict
, key
, value
) < 0) {
2928 Pdata_clear(self
->stack
, i
);
2929 PDATA_PUSH(self
->stack
, dict
, -1);
2934 Instance_New(PyObject
*cls
, PyObject
*args
) {
2936 PyObject
*safe
=0, *r
=0;
2938 if (PyClass_Check(cls
)) {
2941 if ((l
=PyObject_Size(args
)) < 0) goto err
;
2943 PyObject
*__getinitargs__
;
2945 UNLESS (__getinitargs__
=PyObject_GetAttr(cls
, __getinitargs___str
)) {
2946 /* We have a class with no __getinitargs__, so bypass usual
2951 UNLESS (inst
=PyInstance_NewRaw(cls
, NULL
))
2955 Py_DECREF(__getinitargs__
);
2958 if ((r
=PyInstance_New(cls
, args
, NULL
))) return r
;
2963 if ((has_key
= cPickle_PyMapping_HasKey(safe_constructors
, cls
)) < 0)
2967 if (!(safe
= PyObject_GetAttr(cls
, __safe_for_unpickling___str
)) ||
2968 !PyObject_IsTrue(safe
)) {
2969 cPickle_ErrFormat(UnpicklingError
,
2970 "%s is not safe for unpickling", "O", cls
);
2975 if (args
==Py_None
) {
2976 /* Special case, call cls.__basicnew__() */
2979 UNLESS (basicnew
=PyObject_GetAttr(cls
, __basicnew___str
)) return NULL
;
2980 r
=PyObject_CallObject(basicnew
, NULL
);
2981 Py_DECREF(basicnew
);
2985 if ((r
=PyObject_CallObject(cls
, args
))) return r
;
2989 PyObject
*tp
, *v
, *tb
;
2991 PyErr_Fetch(&tp
, &v
, &tb
);
2992 if ((r
=Py_BuildValue("OOO",v
,cls
,args
))) {
2996 PyErr_Restore(tp
,v
,tb
);
3003 load_obj(Unpicklerobject
*self
) {
3004 PyObject
*class, *tup
, *obj
=0;
3007 if ((i
= marker(self
)) < 0) return -1;
3008 UNLESS (tup
=Pdata_popTuple(self
->stack
, i
+1)) return -1;
3009 PDATA_POP(self
->stack
, class);
3011 obj
= Instance_New(class, tup
);
3016 if (! obj
) return -1;
3017 PDATA_PUSH(self
->stack
, obj
, -1);
3023 load_inst(Unpicklerobject
*self
) {
3024 PyObject
*tup
, *class=0, *obj
=0, *module_name
, *class_name
;
3028 if ((i
= marker(self
)) < 0) return -1;
3030 if ((len
= (*self
->readline_func
)(self
, &s
)) < 0) return -1;
3031 if (len
< 2) return bad_readline();
3032 UNLESS (module_name
= PyString_FromStringAndSize(s
, len
- 1)) return -1;
3034 if ((len
= (*self
->readline_func
)(self
, &s
)) >= 0) {
3035 if (len
< 2) return bad_readline();
3036 if ((class_name
= PyString_FromStringAndSize(s
, len
- 1))) {
3037 class = find_class(module_name
, class_name
, self
->find_class
);
3038 Py_DECREF(class_name
);
3041 Py_DECREF(module_name
);
3043 if (! class) return -1;
3045 if ((tup
=Pdata_popTuple(self
->stack
, i
))) {
3046 obj
= Instance_New(class, tup
);
3051 if (! obj
) return -1;
3053 PDATA_PUSH(self
->stack
, obj
, -1);
3059 load_global(Unpicklerobject
*self
) {
3060 PyObject
*class = 0, *module_name
= 0, *class_name
= 0;
3064 if ((len
= (*self
->readline_func
)(self
, &s
)) < 0) return -1;
3065 if (len
< 2) return bad_readline();
3066 UNLESS (module_name
= PyString_FromStringAndSize(s
, len
- 1)) return -1;
3068 if ((len
= (*self
->readline_func
)(self
, &s
)) >= 0) {
3069 if (len
< 2) return bad_readline();
3070 if ((class_name
= PyString_FromStringAndSize(s
, len
- 1))) {
3071 class = find_class(module_name
, class_name
, self
->find_class
);
3072 Py_DECREF(class_name
);
3075 Py_DECREF(module_name
);
3077 if (! class) return -1;
3078 PDATA_PUSH(self
->stack
, class, -1);
3084 load_persid(Unpicklerobject
*self
) {
3089 if (self
->pers_func
) {
3090 if ((len
= (*self
->readline_func
)(self
, &s
)) < 0) return -1;
3091 if (len
< 2) return bad_readline();
3093 UNLESS (pid
= PyString_FromStringAndSize(s
, len
- 1)) return -1;
3095 if (PyList_Check(self
->pers_func
)) {
3096 if (PyList_Append(self
->pers_func
, pid
) < 0) {
3104 pid
= PyObject_CallObject(self
->pers_func
, self
->arg
);
3109 if (! pid
) return -1;
3111 PDATA_PUSH(self
->stack
, pid
, -1);
3115 PyErr_SetString(UnpicklingError
,
3116 "A load persistent id instruction was encountered,\n"
3117 "but no persistent_load function was specified.");
3123 load_binpersid(Unpicklerobject
*self
) {
3126 if (self
->pers_func
) {
3127 PDATA_POP(self
->stack
, pid
);
3128 if (! pid
) return -1;
3130 if (PyList_Check(self
->pers_func
)) {
3131 if (PyList_Append(self
->pers_func
, pid
) < 0) {
3139 pid
= PyObject_CallObject(self
->pers_func
, self
->arg
);
3142 if (! pid
) return -1;
3145 PDATA_PUSH(self
->stack
, pid
, -1);
3149 PyErr_SetString(UnpicklingError
,
3150 "A load persistent id instruction was encountered,\n"
3151 "but no persistent_load function was specified.");
3158 load_pop(Unpicklerobject
*self
) {
3161 UNLESS ((len
=self
->stack
->length
) > 0) return stackUnderflow();
3163 /* Note that we split the (pickle.py) stack into two stacks,
3164 an object stack and a mark stack. We have to be clever and
3165 pop the right one. We do this by looking at the top of the
3169 if ((self
->num_marks
> 0) &&
3170 (self
->marks
[self
->num_marks
- 1] == len
))
3174 Py_DECREF(self
->stack
->data
[len
]);
3175 self
->stack
->length
=len
;
3183 load_pop_mark(Unpicklerobject
*self
) {
3186 if ((i
= marker(self
)) < 0)
3189 Pdata_clear(self
->stack
, i
);
3196 load_dup(Unpicklerobject
*self
) {
3200 if ((len
= self
->stack
->length
) <= 0) return stackUnderflow();
3201 last
=self
->stack
->data
[len
-1];
3203 PDATA_PUSH(self
->stack
, last
, -1);
3209 load_get(Unpicklerobject
*self
) {
3210 PyObject
*py_str
= 0, *value
= 0;
3215 if ((len
= (*self
->readline_func
)(self
, &s
)) < 0) return -1;
3216 if (len
< 2) return bad_readline();
3218 UNLESS (py_str
= PyString_FromStringAndSize(s
, len
- 1)) return -1;
3220 value
= PyDict_GetItem(self
->memo
, py_str
);
3222 PyErr_SetObject(BadPickleGet
, py_str
);
3225 PDATA_APPEND(self
->stack
, value
, -1);
3235 load_binget(Unpicklerobject
*self
) {
3236 PyObject
*py_key
= 0, *value
= 0;
3241 if ((*self
->read_func
)(self
, &s
, 1) < 0) return -1;
3243 key
= (unsigned char)s
[0];
3244 UNLESS (py_key
= PyInt_FromLong((long)key
)) return -1;
3246 value
= PyDict_GetItem(self
->memo
, py_key
);
3248 PyErr_SetObject(BadPickleGet
, py_key
);
3251 PDATA_APPEND(self
->stack
, value
, -1);
3261 load_long_binget(Unpicklerobject
*self
) {
3262 PyObject
*py_key
= 0, *value
= 0;
3268 if ((*self
->read_func
)(self
, &s
, 4) < 0) return -1;
3270 c
= (unsigned char)s
[0];
3272 c
= (unsigned char)s
[1];
3273 key
|= (long)c
<< 8;
3274 c
= (unsigned char)s
[2];
3275 key
|= (long)c
<< 16;
3276 c
= (unsigned char)s
[3];
3277 key
|= (long)c
<< 24;
3279 UNLESS (py_key
= PyInt_FromLong((long)key
)) return -1;
3281 value
= PyDict_GetItem(self
->memo
, py_key
);
3283 PyErr_SetObject(BadPickleGet
, py_key
);
3286 PDATA_APPEND(self
->stack
, value
, -1);
3296 load_put(Unpicklerobject
*self
) {
3297 PyObject
*py_str
= 0, *value
= 0;
3301 if ((l
= (*self
->readline_func
)(self
, &s
)) < 0) return -1;
3302 if (l
< 2) return bad_readline();
3303 UNLESS (len
=self
->stack
->length
) return stackUnderflow();
3304 UNLESS (py_str
= PyString_FromStringAndSize(s
, l
- 1)) return -1;
3305 value
=self
->stack
->data
[len
-1];
3306 l
=PyDict_SetItem(self
->memo
, py_str
, value
);
3313 load_binput(Unpicklerobject
*self
) {
3314 PyObject
*py_key
= 0, *value
= 0;
3319 if ((*self
->read_func
)(self
, &s
, 1) < 0) return -1;
3320 UNLESS ((len
=self
->stack
->length
) > 0) return stackUnderflow();
3322 key
= (unsigned char)s
[0];
3324 UNLESS (py_key
= PyInt_FromLong((long)key
)) return -1;
3325 value
=self
->stack
->data
[len
-1];
3326 len
=PyDict_SetItem(self
->memo
, py_key
, value
);
3333 load_long_binput(Unpicklerobject
*self
) {
3334 PyObject
*py_key
= 0, *value
= 0;
3340 if ((*self
->read_func
)(self
, &s
, 4) < 0) return -1;
3341 UNLESS (len
=self
->stack
->length
) return stackUnderflow();
3343 c
= (unsigned char)s
[0];
3345 c
= (unsigned char)s
[1];
3346 key
|= (long)c
<< 8;
3347 c
= (unsigned char)s
[2];
3348 key
|= (long)c
<< 16;
3349 c
= (unsigned char)s
[3];
3350 key
|= (long)c
<< 24;
3352 UNLESS (py_key
= PyInt_FromLong(key
)) return -1;
3353 value
=self
->stack
->data
[len
-1];
3354 len
=PyDict_SetItem(self
->memo
, py_key
, value
);
3361 do_append(Unpicklerobject
*self
, int x
) {
3362 PyObject
*value
= 0, *list
= 0, *append_method
= 0;
3365 UNLESS ((len
=self
->stack
->length
) >= x
&& x
> 0) return stackUnderflow();
3366 if (len
==x
) return 0; /* nothing to do */
3368 list
=self
->stack
->data
[x
-1];
3370 if (PyList_Check(list
)) {
3374 slice
=Pdata_popList(self
->stack
, x
);
3375 list_len
= PyList_GET_SIZE(list
);
3376 i
=PyList_SetSlice(list
, list_len
, list_len
, slice
);
3382 UNLESS (append_method
= PyObject_GetAttr(list
, append_str
))
3385 for (i
= x
; i
< len
; i
++) {
3388 value
=self
->stack
->data
[i
];
3390 ARG_TUP(self
, value
);
3392 junk
= PyObject_CallObject(append_method
, self
->arg
);
3396 Pdata_clear(self
->stack
, i
+1);
3397 self
->stack
->length
=x
;
3398 Py_DECREF(append_method
);
3403 self
->stack
->length
=x
;
3404 Py_DECREF(append_method
);
3412 load_append(Unpicklerobject
*self
) {
3413 return do_append(self
, self
->stack
->length
- 1);
3418 load_appends(Unpicklerobject
*self
) {
3419 return do_append(self
, marker(self
));
3424 do_setitems(Unpicklerobject
*self
, int x
) {
3425 PyObject
*value
= 0, *key
= 0, *dict
= 0;
3428 UNLESS ((len
=self
->stack
->length
) >= x
3429 && x
> 0) return stackUnderflow();
3431 dict
=self
->stack
->data
[x
-1];
3433 for (i
= x
+1; i
< len
; i
+= 2) {
3434 key
=self
->stack
->data
[i
-1];
3435 value
=self
->stack
->data
[i
];
3436 if (PyObject_SetItem(dict
, key
, value
) < 0) {
3442 Pdata_clear(self
->stack
, x
);
3449 load_setitem(Unpicklerobject
*self
) {
3450 return do_setitems(self
, self
->stack
->length
- 2);
3454 load_setitems(Unpicklerobject
*self
) {
3455 return do_setitems(self
, marker(self
));
3460 load_build(Unpicklerobject
*self
) {
3461 PyObject
*value
= 0, *inst
= 0, *instdict
= 0, *d_key
= 0, *d_value
= 0,
3462 *junk
= 0, *__setstate__
= 0;
3465 if (self
->stack
->length
< 2) return stackUnderflow();
3466 PDATA_POP(self
->stack
, value
);
3467 if (! value
) return -1;
3468 inst
=self
->stack
->data
[self
->stack
->length
-1];
3470 if ((__setstate__
= PyObject_GetAttr(inst
, __setstate___str
))) {
3471 ARG_TUP(self
, value
);
3473 junk
= PyObject_CallObject(__setstate__
, self
->arg
);
3476 Py_DECREF(__setstate__
);
3477 if (! junk
) return -1;
3483 if ((instdict
= PyObject_GetAttr(inst
, __dict___str
))) {
3485 while (PyDict_Next(value
, &i
, &d_key
, &d_value
)) {
3486 if (PyObject_SetItem(instdict
, d_key
, d_value
) < 0) {
3491 Py_DECREF(instdict
);
3502 load_mark(Unpicklerobject
*self
) {
3505 /* Note that we split the (pickle.py) stack into two stacks, an
3506 object stack and a mark stack. Here we push a mark onto the
3510 if ((self
->num_marks
+ 1) >= self
->marks_size
) {
3511 s
=self
->marks_size
+20;
3512 if (s
<= self
->num_marks
) s
=self
->num_marks
+ 1;
3513 if (self
->marks
== NULL
)
3514 self
->marks
=(int *)malloc(s
* sizeof(int));
3516 self
->marks
=(int *)realloc(self
->marks
, s
* sizeof(int));
3517 if (! self
->marks
) {
3521 self
->marks_size
= s
;
3524 self
->marks
[self
->num_marks
++] = self
->stack
->length
;
3530 load_reduce(Unpicklerobject
*self
) {
3531 PyObject
*callable
= 0, *arg_tup
= 0, *ob
= 0;
3533 PDATA_POP(self
->stack
, arg_tup
);
3534 if (! arg_tup
) return -1;
3535 PDATA_POP(self
->stack
, callable
);
3537 ob
= Instance_New(callable
, arg_tup
);
3538 Py_DECREF(callable
);
3542 if (! ob
) return -1;
3544 PDATA_PUSH(self
->stack
, ob
, -1);
3549 load(Unpicklerobject
*self
) {
3550 PyObject
*err
= 0, *val
= 0;
3553 self
->num_marks
= 0;
3554 if (self
->stack
->length
) Pdata_clear(self
->stack
, 0);
3557 if ((*self
->read_func
)(self
, &s
, 1) < 0)
3562 if (load_none(self
) < 0)
3567 if (load_binint(self
) < 0)
3572 if (load_binint1(self
) < 0)
3577 if (load_binint2(self
) < 0)
3582 if (load_int(self
) < 0)
3587 if (load_long(self
) < 0)
3592 if (load_float(self
) < 0)
3597 if (load_binfloat(self
) < 0)
3602 if (load_binstring(self
) < 0)
3606 case SHORT_BINSTRING
:
3607 if (load_short_binstring(self
) < 0)
3612 if (load_string(self
) < 0)
3617 if (load_unicode(self
) < 0)
3622 if (load_binunicode(self
) < 0)
3627 if (load_empty_tuple(self
) < 0)
3632 if (load_tuple(self
) < 0)
3637 if (load_empty_list(self
) < 0)
3642 if (load_list(self
) < 0)
3647 if (load_empty_dict(self
) < 0)
3652 if (load_dict(self
) < 0)
3657 if (load_obj(self
) < 0)
3662 if (load_inst(self
) < 0)
3667 if (load_global(self
) < 0)
3672 if (load_append(self
) < 0)
3677 if (load_appends(self
) < 0)
3682 if (load_build(self
) < 0)
3687 if (load_dup(self
) < 0)
3692 if (load_binget(self
) < 0)
3697 if (load_long_binget(self
) < 0)
3702 if (load_get(self
) < 0)
3707 if (load_mark(self
) < 0)
3712 if (load_binput(self
) < 0)
3717 if (load_long_binput(self
) < 0)
3722 if (load_put(self
) < 0)
3727 if (load_pop(self
) < 0)
3732 if (load_pop_mark(self
) < 0)
3737 if (load_setitem(self
) < 0)
3742 if (load_setitems(self
) < 0)
3750 if (load_persid(self
) < 0)
3755 if (load_binpersid(self
) < 0)
3760 if (load_reduce(self
) < 0)
3765 cPickle_ErrFormat(UnpicklingError
, "invalid load key, '%s'.",
3773 if ((err
= PyErr_Occurred())) {
3774 if (err
== PyExc_EOFError
) {
3775 PyErr_SetNone(PyExc_EOFError
);
3780 PDATA_POP(self
->stack
, val
);
3785 /* No-load functions to support noload, which is used to
3786 find persistent references. */
3789 noload_obj(Unpicklerobject
*self
) {
3792 if ((i
= marker(self
)) < 0) return -1;
3793 return Pdata_clear(self
->stack
, i
+1);
3798 noload_inst(Unpicklerobject
*self
) {
3802 if ((i
= marker(self
)) < 0) return -1;
3803 Pdata_clear(self
->stack
, i
);
3804 if ((*self
->readline_func
)(self
, &s
) < 0) return -1;
3805 if ((*self
->readline_func
)(self
, &s
) < 0) return -1;
3806 PDATA_APPEND(self
->stack
, Py_None
,-1);
3811 noload_global(Unpicklerobject
*self
) {
3814 if ((*self
->readline_func
)(self
, &s
) < 0) return -1;
3815 if ((*self
->readline_func
)(self
, &s
) < 0) return -1;
3816 PDATA_APPEND(self
->stack
, Py_None
,-1);
3821 noload_reduce(Unpicklerobject
*self
) {
3823 if (self
->stack
->length
< 2) return stackUnderflow();
3824 Pdata_clear(self
->stack
, self
->stack
->length
-2);
3825 PDATA_APPEND(self
->stack
, Py_None
,-1);
3830 noload_build(Unpicklerobject
*self
) {
3832 if (self
->stack
->length
< 1) return stackUnderflow();
3833 Pdata_clear(self
->stack
, self
->stack
->length
-1);
3839 noload(Unpicklerobject
*self
) {
3840 PyObject
*err
= 0, *val
= 0;
3843 self
->num_marks
= 0;
3844 Pdata_clear(self
->stack
, 0);
3847 if ((*self
->read_func
)(self
, &s
, 1) < 0)
3852 if (load_none(self
) < 0)
3857 if (load_binint(self
) < 0)
3862 if (load_binint1(self
) < 0)
3867 if (load_binint2(self
) < 0)
3872 if (load_int(self
) < 0)
3877 if (load_long(self
) < 0)
3882 if (load_float(self
) < 0)
3887 if (load_binfloat(self
) < 0)
3892 if (load_binstring(self
) < 0)
3896 case SHORT_BINSTRING
:
3897 if (load_short_binstring(self
) < 0)
3902 if (load_string(self
) < 0)
3907 if (load_unicode(self
) < 0)
3912 if (load_binunicode(self
) < 0)
3917 if (load_empty_tuple(self
) < 0)
3922 if (load_tuple(self
) < 0)
3927 if (load_empty_list(self
) < 0)
3932 if (load_list(self
) < 0)
3937 if (load_empty_dict(self
) < 0)
3942 if (load_dict(self
) < 0)
3947 if (noload_obj(self
) < 0)
3952 if (noload_inst(self
) < 0)
3957 if (noload_global(self
) < 0)
3962 if (load_append(self
) < 0)
3967 if (load_appends(self
) < 0)
3972 if (noload_build(self
) < 0)
3977 if (load_dup(self
) < 0)
3982 if (load_binget(self
) < 0)
3987 if (load_long_binget(self
) < 0)
3992 if (load_get(self
) < 0)
3997 if (load_mark(self
) < 0)
4002 if (load_binput(self
) < 0)
4007 if (load_long_binput(self
) < 0)
4012 if (load_put(self
) < 0)
4017 if (load_pop(self
) < 0)
4022 if (load_pop_mark(self
) < 0)
4027 if (load_setitem(self
) < 0)
4032 if (load_setitems(self
) < 0)
4040 if (load_persid(self
) < 0)
4045 if (load_binpersid(self
) < 0)
4050 if (noload_reduce(self
) < 0)
4055 cPickle_ErrFormat(UnpicklingError
, "invalid load key, '%s'.",
4063 if ((err
= PyErr_Occurred())) {
4064 if (err
== PyExc_EOFError
) {
4065 PyErr_SetNone(PyExc_EOFError
);
4070 PDATA_POP(self
->stack
, val
);
4076 Unpickler_load(Unpicklerobject
*self
, PyObject
*args
) {
4077 UNLESS (PyArg_ParseTuple(args
, ":load"))
4084 Unpickler_noload(Unpicklerobject
*self
, PyObject
*args
) {
4085 UNLESS (PyArg_ParseTuple(args
, ":noload"))
4088 return noload(self
);
4092 static struct PyMethodDef Unpickler_methods
[] = {
4093 {"load", (PyCFunction
)Unpickler_load
, 1,
4094 "load() -- Load a pickle"
4096 {"noload", (PyCFunction
)Unpickler_noload
, 1,
4097 "noload() -- not load a pickle, but go through most of the motions\n"
4099 "This function can be used to read past a pickle without instantiating\n"
4100 "any objects or importing any modules. It can also be used to find all\n"
4101 "persistent references without instantiating any objects or importing\n"
4104 {NULL
, NULL
} /* sentinel */
4108 static Unpicklerobject
*
4109 newUnpicklerobject(PyObject
*f
) {
4110 Unpicklerobject
*self
;
4112 UNLESS (self
= PyObject_New(Unpicklerobject
, &Unpicklertype
))
4117 self
->stack
= (Pdata
*)Pdata_New();
4118 self
->pers_func
= NULL
;
4119 self
->last_string
= NULL
;
4121 self
->num_marks
= 0;
4122 self
->marks_size
= 0;
4125 self
->readline
= NULL
;
4126 self
->safe_constructors
= NULL
;
4127 self
->find_class
= NULL
;
4129 UNLESS (self
->memo
= PyDict_New())
4135 /* Set read, readline based on type of f */
4136 if (PyFile_Check(f
)) {
4137 self
->fp
= PyFile_AsFile(f
);
4138 if (self
->fp
== NULL
) {
4139 PyErr_SetString(PyExc_ValueError
, "I/O operation on closed file");
4142 self
->read_func
= read_file
;
4143 self
->readline_func
= readline_file
;
4145 else if (PycStringIO_InputCheck(f
)) {
4147 self
->read_func
= read_cStringIO
;
4148 self
->readline_func
= readline_cStringIO
;
4153 self
->read_func
= read_other
;
4154 self
->readline_func
= readline_other
;
4156 UNLESS ((self
->readline
= PyObject_GetAttr(f
, readline_str
)) &&
4157 (self
->read
= PyObject_GetAttr(f
, read_str
))) {
4159 PyErr_SetString( PyExc_TypeError
, "argument must have 'read' and "
4160 "'readline' attributes" );
4165 if (PyEval_GetRestricted()) {
4166 /* Restricted execution, get private tables */
4169 UNLESS (m
=PyImport_Import(copy_reg_str
)) goto err
;
4170 self
->safe_constructors
=PyObject_GetAttr(m
, safe_constructors_str
);
4172 UNLESS (self
->safe_constructors
) goto err
;
4175 self
->safe_constructors
=safe_constructors
;
4176 Py_INCREF(safe_constructors
);
4182 Py_DECREF((PyObject
*)self
);
4188 get_Unpickler(PyObject
*self
, PyObject
*args
) {
4191 UNLESS (PyArg_ParseTuple(args
, "O:Unpickler", &file
))
4193 return (PyObject
*)newUnpicklerobject(file
);
4198 Unpickler_dealloc(Unpicklerobject
*self
) {
4199 Py_XDECREF(self
->readline
);
4200 Py_XDECREF(self
->read
);
4201 Py_XDECREF(self
->file
);
4202 Py_XDECREF(self
->memo
);
4203 Py_XDECREF(self
->stack
);
4204 Py_XDECREF(self
->pers_func
);
4205 Py_XDECREF(self
->arg
);
4206 Py_XDECREF(self
->last_string
);
4207 Py_XDECREF(self
->safe_constructors
);
4213 if (self
->buf_size
) {
4222 Unpickler_getattr(Unpicklerobject
*self
, char *name
) {
4223 if (!strcmp(name
, "persistent_load")) {
4224 if (!self
->pers_func
) {
4225 PyErr_SetString(PyExc_AttributeError
, name
);
4229 Py_INCREF(self
->pers_func
);
4230 return self
->pers_func
;
4233 if (!strcmp(name
, "find_global")) {
4234 if (!self
->find_class
) {
4235 PyErr_SetString(PyExc_AttributeError
, name
);
4239 Py_INCREF(self
->find_class
);
4240 return self
->find_class
;
4243 if (!strcmp(name
, "memo")) {
4245 PyErr_SetString(PyExc_AttributeError
, name
);
4249 Py_INCREF(self
->memo
);
4253 if (!strcmp(name
, "UnpicklingError")) {
4254 Py_INCREF(UnpicklingError
);
4255 return UnpicklingError
;
4258 return Py_FindMethod(Unpickler_methods
, (PyObject
*)self
, name
);
4263 Unpickler_setattr(Unpicklerobject
*self
, char *name
, PyObject
*value
) {
4265 if (!strcmp(name
, "persistent_load")) {
4266 Py_XDECREF(self
->pers_func
);
4267 self
->pers_func
= value
;
4272 if (!strcmp(name
, "find_global")) {
4273 Py_XDECREF(self
->find_class
);
4274 self
->find_class
= value
;
4280 PyErr_SetString(PyExc_TypeError
,
4281 "attribute deletion is not supported");
4285 if (strcmp(name
, "memo") == 0) {
4286 if (! PyDict_Check(value
)) {
4287 PyErr_SetString(PyExc_TypeError
, "memo must be a dictionary");
4290 Py_XDECREF(self
->memo
);
4296 PyErr_SetString(PyExc_AttributeError
, name
);
4302 cpm_dump(PyObject
*self
, PyObject
*args
) {
4303 PyObject
*ob
, *file
, *res
= NULL
;
4304 Picklerobject
*pickler
= 0;
4307 UNLESS (PyArg_ParseTuple(args
, "OO|i", &ob
, &file
, &bin
))
4310 UNLESS (pickler
= newPicklerobject(file
, bin
))
4313 if (dump(pickler
, ob
) < 0)
4320 Py_XDECREF(pickler
);
4327 cpm_dumps(PyObject
*self
, PyObject
*args
) {
4328 PyObject
*ob
, *file
= 0, *res
= NULL
;
4329 Picklerobject
*pickler
= 0;
4332 UNLESS (PyArg_ParseTuple(args
, "O|i:dumps", &ob
, &bin
))
4335 UNLESS (file
= PycStringIO
->NewOutput(128))
4338 UNLESS (pickler
= newPicklerobject(file
, bin
))
4341 if (dump(pickler
, ob
) < 0)
4344 res
= PycStringIO
->cgetvalue(file
);
4347 Py_XDECREF(pickler
);
4355 cpm_load(PyObject
*self
, PyObject
*args
) {
4356 Unpicklerobject
*unpickler
= 0;
4357 PyObject
*ob
, *res
= NULL
;
4359 UNLESS (PyArg_ParseTuple(args
, "O:load", &ob
))
4362 UNLESS (unpickler
= newUnpicklerobject(ob
))
4365 res
= load(unpickler
);
4368 Py_XDECREF(unpickler
);
4375 cpm_loads(PyObject
*self
, PyObject
*args
) {
4376 PyObject
*ob
, *file
= 0, *res
= NULL
;
4377 Unpicklerobject
*unpickler
= 0;
4379 UNLESS (PyArg_ParseTuple(args
, "S:loads", &ob
))
4382 UNLESS (file
= PycStringIO
->NewInput(ob
))
4385 UNLESS (unpickler
= newUnpicklerobject(file
))
4388 res
= load(unpickler
);
4392 Py_XDECREF(unpickler
);
4398 static char Unpicklertype__doc__
[] =
4399 "Objects that know how to unpickle";
4401 static PyTypeObject Unpicklertype
= {
4402 PyObject_HEAD_INIT(NULL
)
4404 "Unpickler", /*tp_name*/
4405 sizeof(Unpicklerobject
), /*tp_basicsize*/
4408 (destructor
)Unpickler_dealloc
, /*tp_dealloc*/
4409 (printfunc
)0, /*tp_print*/
4410 (getattrfunc
)Unpickler_getattr
, /*tp_getattr*/
4411 (setattrfunc
)Unpickler_setattr
, /*tp_setattr*/
4412 (cmpfunc
)0, /*tp_compare*/
4413 (reprfunc
)0, /*tp_repr*/
4415 0, /*tp_as_sequence*/
4416 0, /*tp_as_mapping*/
4417 (hashfunc
)0, /*tp_hash*/
4418 (ternaryfunc
)0, /*tp_call*/
4419 (reprfunc
)0, /*tp_str*/
4421 /* Space for future expansion */
4423 Unpicklertype__doc__
/* Documentation string */
4426 static struct PyMethodDef cPickle_methods
[] = {
4427 {"dump", (PyCFunction
)cpm_dump
, 1,
4428 "dump(object, file, [binary]) --"
4429 "Write an object in pickle format to the given file\n"
4431 "If the optional argument, binary, is provided and is true, then the\n"
4432 "pickle will be written in binary format, which is more space and\n"
4433 "computationally efficient. \n"
4435 {"dumps", (PyCFunction
)cpm_dumps
, 1,
4436 "dumps(object, [binary]) --"
4437 "Return a string containing an object in pickle format\n"
4439 "If the optional argument, binary, is provided and is true, then the\n"
4440 "pickle will be written in binary format, which is more space and\n"
4441 "computationally efficient. \n"
4443 {"load", (PyCFunction
)cpm_load
, 1,
4444 "load(file) -- Load a pickle from the given file"},
4445 {"loads", (PyCFunction
)cpm_loads
, 1,
4446 "loads(string) -- Load a pickle from the given string"},
4447 {"Pickler", (PyCFunction
)get_Pickler
, 1,
4448 "Pickler(file, [binary]) -- Create a pickler\n"
4450 "If the optional argument, binary, is provided and is true, then\n"
4451 "pickles will be written in binary format, which is more space and\n"
4452 "computationally efficient. \n"
4454 {"Unpickler", (PyCFunction
)get_Unpickler
, 1,
4455 "Unpickler(file) -- Create an unpickler"},
4460 init_stuff(PyObject
*module_dict
) {
4461 PyObject
*string
, *copy_reg
, *t
, *r
;
4463 #define INIT_STR(S) UNLESS(S ## _str=PyString_FromString(#S)) return -1;
4465 INIT_STR(__class__
);
4466 INIT_STR(__getinitargs__
);
4468 INIT_STR(__getstate__
);
4469 INIT_STR(__setstate__
);
4472 INIT_STR(__reduce__
);
4474 INIT_STR(__safe_for_unpickling__
);
4479 INIT_STR(dispatch_table
);
4480 INIT_STR(safe_constructors
);
4481 INIT_STR(__basicnew__
);
4482 UNLESS (empty_str
=PyString_FromString("")) return -1;
4484 UNLESS (copy_reg
= PyImport_ImportModule("copy_reg"))
4487 /* These next few are special because we want to use different
4488 ones in restricted mode. */
4490 UNLESS (dispatch_table
= PyObject_GetAttr(copy_reg
, dispatch_table_str
))
4493 UNLESS (safe_constructors
= PyObject_GetAttr(copy_reg
,
4494 safe_constructors_str
))
4497 Py_DECREF(copy_reg
);
4499 /* Down to here ********************************** */
4501 UNLESS (string
= PyImport_ImportModule("string"))
4504 UNLESS (atol_func
= PyObject_GetAttrString(string
, "atol"))
4509 UNLESS (empty_tuple
= PyTuple_New(0))
4513 UNLESS (t
=PyImport_ImportModule("__builtin__")) return -1;
4514 if (PyDict_SetItemString(module_dict
, "__builtins__", t
) < 0)
4517 UNLESS (t
=PyDict_New()) return -1;
4518 UNLESS (r
=PyRun_String(
4519 "def __init__(self, *args): self.args=args\n\n"
4520 "def __str__(self):\n"
4521 " return self.args and ('%s' % self.args[0]) or '(what)'\n",
4523 module_dict
, t
) ) return -1;
4526 UNLESS (PickleError
= PyErr_NewException("cPickle.PickleError", NULL
, t
))
4532 UNLESS (PicklingError
= PyErr_NewException("cPickle.PicklingError",
4536 UNLESS (t
=PyDict_New()) return -1;
4537 UNLESS (r
=PyRun_String(
4538 "def __init__(self, *args): self.args=args\n\n"
4539 "def __str__(self):\n"
4541 " a=a and type(a[0]) or '(what)'\n"
4542 " return 'Cannot pickle %s objects' % a\n"
4544 module_dict
, t
) ) return -1;
4547 UNLESS (UnpickleableError
= PyErr_NewException(
4548 "cPickle.UnpickleableError", PicklingError
, t
))
4553 UNLESS (UnpicklingError
= PyErr_NewException("cPickle.UnpicklingError",
4557 if (PyDict_SetItemString(module_dict
, "PickleError",
4561 if (PyDict_SetItemString(module_dict
, "PicklingError",
4565 if (PyDict_SetItemString(module_dict
, "UnpicklingError",
4566 UnpicklingError
) < 0)
4569 if (PyDict_SetItemString(module_dict
, "UnpickleableError",
4570 UnpickleableError
) < 0)
4573 UNLESS (BadPickleGet
= PyString_FromString("cPickle.BadPickleGet"))
4576 if (PyDict_SetItemString(module_dict
, "BadPickleGet",
4585 #ifndef DL_EXPORT /* declarations for DLL import/export */
4586 #define DL_EXPORT(RTYPE) RTYPE
4590 PyObject
*m
, *d
, *di
, *v
, *k
;
4593 PyObject
*format_version
;
4594 PyObject
*compatible_formats
;
4596 Picklertype
.ob_type
= &PyType_Type
;
4597 Unpicklertype
.ob_type
= &PyType_Type
;
4598 PdataType
.ob_type
= &PyType_Type
;
4600 /* Initialize some pieces. We need to do this before module creation,
4601 so we're forced to use a temporary dictionary. :(
4605 if (init_stuff(di
) < 0) return;
4607 /* Create the module and add the functions */
4608 m
= Py_InitModule4("cPickle", cPickle_methods
,
4609 cPickle_module_documentation
,
4610 (PyObject
*)NULL
,PYTHON_API_VERSION
);
4612 /* Add some symbolic constants to the module */
4613 d
= PyModule_GetDict(m
);
4614 PyDict_SetItemString(d
,"__version__", v
= PyString_FromString(rev
));
4617 /* Copy data from di. Waaa. */
4618 for (i
=0; PyDict_Next(di
, &i
, &k
, &v
); ) {
4619 if (PyObject_SetItem(d
, k
, v
) < 0) {
4626 format_version
= PyString_FromString("1.3");
4627 compatible_formats
= Py_BuildValue("[sss]", "1.0", "1.1", "1.2");
4629 PyDict_SetItemString(d
, "format_version", format_version
);
4630 PyDict_SetItemString(d
, "compatible_formats", compatible_formats
);
4631 Py_XDECREF(format_version
);
4632 Py_XDECREF(compatible_formats
);