You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

6518 lines
186 KiB

  1. #include "Python.h"
  2. #include "structmember.h"
  3. PyDoc_STRVAR(pickle_module_doc,
  4. "Optimized C implementation for the Python pickle module.");
  5. /* Bump this when new opcodes are added to the pickle protocol. */
  6. enum {
  7. HIGHEST_PROTOCOL = 3,
  8. DEFAULT_PROTOCOL = 3
  9. };
  10. /* Pickle opcodes. These must be kept updated with pickle.py.
  11. Extensive docs are in pickletools.py. */
  12. enum opcode {
  13. MARK = '(',
  14. STOP = '.',
  15. POP = '0',
  16. POP_MARK = '1',
  17. DUP = '2',
  18. FLOAT = 'F',
  19. INT = 'I',
  20. BININT = 'J',
  21. BININT1 = 'K',
  22. LONG = 'L',
  23. BININT2 = 'M',
  24. NONE = 'N',
  25. PERSID = 'P',
  26. BINPERSID = 'Q',
  27. REDUCE = 'R',
  28. STRING = 'S',
  29. BINSTRING = 'T',
  30. SHORT_BINSTRING = 'U',
  31. UNICODE = 'V',
  32. BINUNICODE = 'X',
  33. APPEND = 'a',
  34. BUILD = 'b',
  35. GLOBAL = 'c',
  36. DICT = 'd',
  37. EMPTY_DICT = '}',
  38. APPENDS = 'e',
  39. GET = 'g',
  40. BINGET = 'h',
  41. INST = 'i',
  42. LONG_BINGET = 'j',
  43. LIST = 'l',
  44. EMPTY_LIST = ']',
  45. OBJ = 'o',
  46. PUT = 'p',
  47. BINPUT = 'q',
  48. LONG_BINPUT = 'r',
  49. SETITEM = 's',
  50. TUPLE = 't',
  51. EMPTY_TUPLE = ')',
  52. SETITEMS = 'u',
  53. BINFLOAT = 'G',
  54. /* Protocol 2. */
  55. PROTO = '\x80',
  56. NEWOBJ = '\x81',
  57. EXT1 = '\x82',
  58. EXT2 = '\x83',
  59. EXT4 = '\x84',
  60. TUPLE1 = '\x85',
  61. TUPLE2 = '\x86',
  62. TUPLE3 = '\x87',
  63. NEWTRUE = '\x88',
  64. NEWFALSE = '\x89',
  65. LONG1 = '\x8a',
  66. LONG4 = '\x8b',
  67. /* Protocol 3 (Python 3.x) */
  68. BINBYTES = 'B',
  69. SHORT_BINBYTES = 'C'
  70. };
  71. /* These aren't opcodes -- they're ways to pickle bools before protocol 2
  72. * so that unpicklers written before bools were introduced unpickle them
  73. * as ints, but unpicklers after can recognize that bools were intended.
  74. * Note that protocol 2 added direct ways to pickle bools.
  75. */
  76. #undef TRUE
  77. #define TRUE "I01\n"
  78. #undef FALSE
  79. #define FALSE "I00\n"
  80. enum {
  81. /* Keep in synch with pickle.Pickler._BATCHSIZE. This is how many elements
  82. batch_list/dict() pumps out before doing APPENDS/SETITEMS. Nothing will
  83. break if this gets out of synch with pickle.py, but it's unclear that would
  84. help anything either. */
  85. BATCHSIZE = 1000,
  86. /* Nesting limit until Pickler, when running in "fast mode", starts
  87. checking for self-referential data-structures. */
  88. FAST_NESTING_LIMIT = 50,
  89. /* Initial size of the write buffer of Pickler. */
  90. WRITE_BUF_SIZE = 4096,
  91. /* Maximum size of the write buffer of Pickler when pickling to a
  92. stream. This is ignored for in-memory pickling. */
  93. MAX_WRITE_BUF_SIZE = 64 * 1024,
  94. /* Prefetch size when unpickling (disabled on unpeekable streams) */
  95. PREFETCH = 8192 * 16
  96. };
  97. /* Exception classes for pickle. These should override the ones defined in
  98. pickle.py, when the C-optimized Pickler and Unpickler are used. */
  99. static PyObject *PickleError = NULL;
  100. static PyObject *PicklingError = NULL;
  101. static PyObject *UnpicklingError = NULL;
  102. /* copyreg.dispatch_table, {type_object: pickling_function} */
  103. static PyObject *dispatch_table = NULL;
  104. /* For EXT[124] opcodes. */
  105. /* copyreg._extension_registry, {(module_name, function_name): code} */
  106. static PyObject *extension_registry = NULL;
  107. /* copyreg._inverted_registry, {code: (module_name, function_name)} */
  108. static PyObject *inverted_registry = NULL;
  109. /* copyreg._extension_cache, {code: object} */
  110. static PyObject *extension_cache = NULL;
  111. /* _compat_pickle.NAME_MAPPING, {(oldmodule, oldname): (newmodule, newname)} */
  112. static PyObject *name_mapping_2to3 = NULL;
  113. /* _compat_pickle.IMPORT_MAPPING, {oldmodule: newmodule} */
  114. static PyObject *import_mapping_2to3 = NULL;
  115. /* Same, but with REVERSE_NAME_MAPPING / REVERSE_IMPORT_MAPPING */
  116. static PyObject *name_mapping_3to2 = NULL;
  117. static PyObject *import_mapping_3to2 = NULL;
  118. /* XXX: Are these really nescessary? */
  119. /* As the name says, an empty tuple. */
  120. static PyObject *empty_tuple = NULL;
  121. /* For looking up name pairs in copyreg._extension_registry. */
  122. static PyObject *two_tuple = NULL;
  123. static int
  124. stack_underflow(void)
  125. {
  126. PyErr_SetString(UnpicklingError, "unpickling stack underflow");
  127. return -1;
  128. }
  129. /* Internal data type used as the unpickling stack. */
  130. typedef struct {
  131. PyObject_VAR_HEAD
  132. PyObject **data;
  133. Py_ssize_t allocated; /* number of slots in data allocated */
  134. } Pdata;
  135. static void
  136. Pdata_dealloc(Pdata *self)
  137. {
  138. Py_ssize_t i = Py_SIZE(self);
  139. while (--i >= 0) {
  140. Py_DECREF(self->data[i]);
  141. }
  142. PyMem_FREE(self->data);
  143. PyObject_Del(self);
  144. }
  145. static PyTypeObject Pdata_Type = {
  146. PyVarObject_HEAD_INIT(NULL, 0)
  147. "_pickle.Pdata", /*tp_name*/
  148. sizeof(Pdata), /*tp_basicsize*/
  149. 0, /*tp_itemsize*/
  150. (destructor)Pdata_dealloc, /*tp_dealloc*/
  151. };
  152. static PyObject *
  153. Pdata_New(void)
  154. {
  155. Pdata *self;
  156. if (!(self = PyObject_New(Pdata, &Pdata_Type)))
  157. return NULL;
  158. Py_SIZE(self) = 0;
  159. self->allocated = 8;
  160. self->data = PyMem_MALLOC(self->allocated * sizeof(PyObject *));
  161. if (self->data)
  162. return (PyObject *)self;
  163. Py_DECREF(self);
  164. return PyErr_NoMemory();
  165. }
  166. /* Retain only the initial clearto items. If clearto >= the current
  167. * number of items, this is a (non-erroneous) NOP.
  168. */
  169. static int
  170. Pdata_clear(Pdata *self, Py_ssize_t clearto)
  171. {
  172. Py_ssize_t i = Py_SIZE(self);
  173. if (clearto < 0)
  174. return stack_underflow();
  175. if (clearto >= i)
  176. return 0;
  177. while (--i >= clearto) {
  178. Py_CLEAR(self->data[i]);
  179. }
  180. Py_SIZE(self) = clearto;
  181. return 0;
  182. }
  183. static int
  184. Pdata_grow(Pdata *self)
  185. {
  186. PyObject **data = self->data;
  187. Py_ssize_t allocated = self->allocated;
  188. Py_ssize_t new_allocated;
  189. new_allocated = (allocated >> 3) + 6;
  190. /* check for integer overflow */
  191. if (new_allocated > PY_SSIZE_T_MAX - allocated)
  192. goto nomemory;
  193. new_allocated += allocated;
  194. if (new_allocated > (PY_SSIZE_T_MAX / sizeof(PyObject *)))
  195. goto nomemory;
  196. data = PyMem_REALLOC(data, new_allocated * sizeof(PyObject *));
  197. if (data == NULL)
  198. goto nomemory;
  199. self->data = data;
  200. self->allocated = new_allocated;
  201. return 0;
  202. nomemory:
  203. PyErr_NoMemory();
  204. return -1;
  205. }
  206. /* D is a Pdata*. Pop the topmost element and store it into V, which
  207. * must be an lvalue holding PyObject*. On stack underflow, UnpicklingError
  208. * is raised and V is set to NULL.
  209. */
  210. static PyObject *
  211. Pdata_pop(Pdata *self)
  212. {
  213. if (Py_SIZE(self) == 0) {
  214. PyErr_SetString(UnpicklingError, "bad pickle data");
  215. return NULL;
  216. }
  217. return self->data[--Py_SIZE(self)];
  218. }
  219. #define PDATA_POP(D, V) do { (V) = Pdata_pop((D)); } while (0)
  220. static int
  221. Pdata_push(Pdata *self, PyObject *obj)
  222. {
  223. if (Py_SIZE(self) == self->allocated && Pdata_grow(self) < 0) {
  224. return -1;
  225. }
  226. self->data[Py_SIZE(self)++] = obj;
  227. return 0;
  228. }
  229. /* Push an object on stack, transferring its ownership to the stack. */
  230. #define PDATA_PUSH(D, O, ER) do { \
  231. if (Pdata_push((D), (O)) < 0) return (ER); } while(0)
  232. /* Push an object on stack, adding a new reference to the object. */
  233. #define PDATA_APPEND(D, O, ER) do { \
  234. Py_INCREF((O)); \
  235. if (Pdata_push((D), (O)) < 0) return (ER); } while(0)
  236. static PyObject *
  237. Pdata_poptuple(Pdata *self, Py_ssize_t start)
  238. {
  239. PyObject *tuple;
  240. Py_ssize_t len, i, j;
  241. len = Py_SIZE(self) - start;
  242. tuple = PyTuple_New(len);
  243. if (tuple == NULL)
  244. return NULL;
  245. for (i = start, j = 0; j < len; i++, j++)
  246. PyTuple_SET_ITEM(tuple, j, self->data[i]);
  247. Py_SIZE(self) = start;
  248. return tuple;
  249. }
  250. static PyObject *
  251. Pdata_poplist(Pdata *self, Py_ssize_t start)
  252. {
  253. PyObject *list;
  254. Py_ssize_t len, i, j;
  255. len = Py_SIZE(self) - start;
  256. list = PyList_New(len);
  257. if (list == NULL)
  258. return NULL;
  259. for (i = start, j = 0; j < len; i++, j++)
  260. PyList_SET_ITEM(list, j, self->data[i]);
  261. Py_SIZE(self) = start;
  262. return list;
  263. }
  264. typedef struct {
  265. PyObject *me_key;
  266. Py_ssize_t me_value;
  267. } PyMemoEntry;
  268. typedef struct {
  269. Py_ssize_t mt_mask;
  270. Py_ssize_t mt_used;
  271. Py_ssize_t mt_allocated;
  272. PyMemoEntry *mt_table;
  273. } PyMemoTable;
  274. typedef struct PicklerObject {
  275. PyObject_HEAD
  276. PyMemoTable *memo; /* Memo table, keep track of the seen
  277. objects to support self-referential objects
  278. pickling. */
  279. PyObject *pers_func; /* persistent_id() method, can be NULL */
  280. PyObject *dispatch_table; /* private dispatch_table, can be NULL */
  281. PyObject *arg;
  282. PyObject *write; /* write() method of the output stream. */
  283. PyObject *output_buffer; /* Write into a local bytearray buffer before
  284. flushing to the stream. */
  285. Py_ssize_t output_len; /* Length of output_buffer. */
  286. Py_ssize_t max_output_len; /* Allocation size of output_buffer. */
  287. int proto; /* Pickle protocol number, >= 0 */
  288. int bin; /* Boolean, true if proto > 0 */
  289. Py_ssize_t buf_size; /* Size of the current buffered pickle data */
  290. int fast; /* Enable fast mode if set to a true value.
  291. The fast mode disable the usage of memo,
  292. therefore speeding the pickling process by
  293. not generating superfluous PUT opcodes. It
  294. should not be used if with self-referential
  295. objects. */
  296. int fast_nesting;
  297. int fix_imports; /* Indicate whether Pickler should fix
  298. the name of globals for Python 2.x. */
  299. PyObject *fast_memo;
  300. } PicklerObject;
  301. typedef struct UnpicklerObject {
  302. PyObject_HEAD
  303. Pdata *stack; /* Pickle data stack, store unpickled objects. */
  304. /* The unpickler memo is just an array of PyObject *s. Using a dict
  305. is unnecessary, since the keys are contiguous ints. */
  306. PyObject **memo;
  307. Py_ssize_t memo_size;
  308. PyObject *arg;
  309. PyObject *pers_func; /* persistent_load() method, can be NULL. */
  310. Py_buffer buffer;
  311. char *input_buffer;
  312. char *input_line;
  313. Py_ssize_t input_len;
  314. Py_ssize_t next_read_idx;
  315. Py_ssize_t prefetched_idx; /* index of first prefetched byte */
  316. PyObject *read; /* read() method of the input stream. */
  317. PyObject *readline; /* readline() method of the input stream. */
  318. PyObject *peek; /* peek() method of the input stream, or NULL */
  319. char *encoding; /* Name of the encoding to be used for
  320. decoding strings pickled using Python
  321. 2.x. The default value is "ASCII" */
  322. char *errors; /* Name of errors handling scheme to used when
  323. decoding strings. The default value is
  324. "strict". */
  325. Py_ssize_t *marks; /* Mark stack, used for unpickling container
  326. objects. */
  327. Py_ssize_t num_marks; /* Number of marks in the mark stack. */
  328. Py_ssize_t marks_size; /* Current allocated size of the mark stack. */
  329. int proto; /* Protocol of the pickle loaded. */
  330. int fix_imports; /* Indicate whether Unpickler should fix
  331. the name of globals pickled by Python 2.x. */
  332. } UnpicklerObject;
  333. /* Forward declarations */
  334. static int save(PicklerObject *, PyObject *, int);
  335. static int save_reduce(PicklerObject *, PyObject *, PyObject *);
  336. static PyTypeObject Pickler_Type;
  337. static PyTypeObject Unpickler_Type;
  338. /*************************************************************************
  339. A custom hashtable mapping void* to longs. This is used by the pickler for
  340. memoization. Using a custom hashtable rather than PyDict allows us to skip
  341. a bunch of unnecessary object creation. This makes a huge performance
  342. difference. */
  343. #define MT_MINSIZE 8
  344. #define PERTURB_SHIFT 5
  345. static PyMemoTable *
  346. PyMemoTable_New(void)
  347. {
  348. PyMemoTable *memo = PyMem_MALLOC(sizeof(PyMemoTable));
  349. if (memo == NULL) {
  350. PyErr_NoMemory();
  351. return NULL;
  352. }
  353. memo->mt_used = 0;
  354. memo->mt_allocated = MT_MINSIZE;
  355. memo->mt_mask = MT_MINSIZE - 1;
  356. memo->mt_table = PyMem_MALLOC(MT_MINSIZE * sizeof(PyMemoEntry));
  357. if (memo->mt_table == NULL) {
  358. PyMem_FREE(memo);
  359. PyErr_NoMemory();
  360. return NULL;
  361. }
  362. memset(memo->mt_table, 0, MT_MINSIZE * sizeof(PyMemoEntry));
  363. return memo;
  364. }
  365. static PyMemoTable *
  366. PyMemoTable_Copy(PyMemoTable *self)
  367. {
  368. Py_ssize_t i;
  369. PyMemoTable *new = PyMemoTable_New();
  370. if (new == NULL)
  371. return NULL;
  372. new->mt_used = self->mt_used;
  373. new->mt_allocated = self->mt_allocated;
  374. new->mt_mask = self->mt_mask;
  375. /* The table we get from _New() is probably smaller than we wanted.
  376. Free it and allocate one that's the right size. */
  377. PyMem_FREE(new->mt_table);
  378. new->mt_table = PyMem_MALLOC(self->mt_allocated * sizeof(PyMemoEntry));
  379. if (new->mt_table == NULL) {
  380. PyMem_FREE(new);
  381. PyErr_NoMemory();
  382. return NULL;
  383. }
  384. for (i = 0; i < self->mt_allocated; i++) {
  385. Py_XINCREF(self->mt_table[i].me_key);
  386. }
  387. memcpy(new->mt_table, self->mt_table,
  388. sizeof(PyMemoEntry) * self->mt_allocated);
  389. return new;
  390. }
  391. static Py_ssize_t
  392. PyMemoTable_Size(PyMemoTable *self)
  393. {
  394. return self->mt_used;
  395. }
  396. static int
  397. PyMemoTable_Clear(PyMemoTable *self)
  398. {
  399. Py_ssize_t i = self->mt_allocated;
  400. while (--i >= 0) {
  401. Py_XDECREF(self->mt_table[i].me_key);
  402. }
  403. self->mt_used = 0;
  404. memset(self->mt_table, 0, self->mt_allocated * sizeof(PyMemoEntry));
  405. return 0;
  406. }
  407. static void
  408. PyMemoTable_Del(PyMemoTable *self)
  409. {
  410. if (self == NULL)
  411. return;
  412. PyMemoTable_Clear(self);
  413. PyMem_FREE(self->mt_table);
  414. PyMem_FREE(self);
  415. }
  416. /* Since entries cannot be deleted from this hashtable, _PyMemoTable_Lookup()
  417. can be considerably simpler than dictobject.c's lookdict(). */
  418. static PyMemoEntry *
  419. _PyMemoTable_Lookup(PyMemoTable *self, PyObject *key)
  420. {
  421. size_t i;
  422. size_t perturb;
  423. size_t mask = (size_t)self->mt_mask;
  424. PyMemoEntry *table = self->mt_table;
  425. PyMemoEntry *entry;
  426. Py_hash_t hash = (Py_hash_t)key >> 3;
  427. i = hash & mask;
  428. entry = &table[i];
  429. if (entry->me_key == NULL || entry->me_key == key)
  430. return entry;
  431. for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
  432. i = (i << 2) + i + perturb + 1;
  433. entry = &table[i & mask];
  434. if (entry->me_key == NULL || entry->me_key == key)
  435. return entry;
  436. }
  437. assert(0); /* Never reached */
  438. return NULL;
  439. }
  440. /* Returns -1 on failure, 0 on success. */
  441. static int
  442. _PyMemoTable_ResizeTable(PyMemoTable *self, Py_ssize_t min_size)
  443. {
  444. PyMemoEntry *oldtable = NULL;
  445. PyMemoEntry *oldentry, *newentry;
  446. Py_ssize_t new_size = MT_MINSIZE;
  447. Py_ssize_t to_process;
  448. assert(min_size > 0);
  449. /* Find the smallest valid table size >= min_size. */
  450. while (new_size < min_size && new_size > 0)
  451. new_size <<= 1;
  452. if (new_size <= 0) {
  453. PyErr_NoMemory();
  454. return -1;
  455. }
  456. /* new_size needs to be a power of two. */
  457. assert((new_size & (new_size - 1)) == 0);
  458. /* Allocate new table. */
  459. oldtable = self->mt_table;
  460. self->mt_table = PyMem_MALLOC(new_size * sizeof(PyMemoEntry));
  461. if (self->mt_table == NULL) {
  462. self->mt_table = oldtable;
  463. PyErr_NoMemory();
  464. return -1;
  465. }
  466. self->mt_allocated = new_size;
  467. self->mt_mask = new_size - 1;
  468. memset(self->mt_table, 0, sizeof(PyMemoEntry) * new_size);
  469. /* Copy entries from the old table. */
  470. to_process = self->mt_used;
  471. for (oldentry = oldtable; to_process > 0; oldentry++) {
  472. if (oldentry->me_key != NULL) {
  473. to_process--;
  474. /* newentry is a pointer to a chunk of the new
  475. mt_table, so we're setting the key:value pair
  476. in-place. */
  477. newentry = _PyMemoTable_Lookup(self, oldentry->me_key);
  478. newentry->me_key = oldentry->me_key;
  479. newentry->me_value = oldentry->me_value;
  480. }
  481. }
  482. /* Deallocate the old table. */
  483. PyMem_FREE(oldtable);
  484. return 0;
  485. }
  486. /* Returns NULL on failure, a pointer to the value otherwise. */
  487. static Py_ssize_t *
  488. PyMemoTable_Get(PyMemoTable *self, PyObject *key)
  489. {
  490. PyMemoEntry *entry = _PyMemoTable_Lookup(self, key);
  491. if (entry->me_key == NULL)
  492. return NULL;
  493. return &entry->me_value;
  494. }
  495. /* Returns -1 on failure, 0 on success. */
  496. static int
  497. PyMemoTable_Set(PyMemoTable *self, PyObject *key, Py_ssize_t value)
  498. {
  499. PyMemoEntry *entry;
  500. assert(key != NULL);
  501. entry = _PyMemoTable_Lookup(self, key);
  502. if (entry->me_key != NULL) {
  503. entry->me_value = value;
  504. return 0;
  505. }
  506. Py_INCREF(key);
  507. entry->me_key = key;
  508. entry->me_value = value;
  509. self->mt_used++;
  510. /* If we added a key, we can safely resize. Otherwise just return!
  511. * If used >= 2/3 size, adjust size. Normally, this quaduples the size.
  512. *
  513. * Quadrupling the size improves average table sparseness
  514. * (reducing collisions) at the cost of some memory. It also halves
  515. * the number of expensive resize operations in a growing memo table.
  516. *
  517. * Very large memo tables (over 50K items) use doubling instead.
  518. * This may help applications with severe memory constraints.
  519. */
  520. if (!(self->mt_used * 3 >= (self->mt_mask + 1) * 2))
  521. return 0;
  522. return _PyMemoTable_ResizeTable(self,
  523. (self->mt_used > 50000 ? 2 : 4) * self->mt_used);
  524. }
  525. #undef MT_MINSIZE
  526. #undef PERTURB_SHIFT
  527. /*************************************************************************/
  528. /* Helpers for creating the argument tuple passed to functions. This has the
  529. performance advantage of calling PyTuple_New() only once.
  530. XXX(avassalotti): Inline directly in _Pickler_FastCall() and
  531. _Unpickler_FastCall(). */
  532. #define ARG_TUP(self, obj) do { \
  533. if ((self)->arg || ((self)->arg=PyTuple_New(1))) { \
  534. Py_XDECREF(PyTuple_GET_ITEM((self)->arg, 0)); \
  535. PyTuple_SET_ITEM((self)->arg, 0, (obj)); \
  536. } \
  537. else { \
  538. Py_DECREF((obj)); \
  539. } \
  540. } while (0)
  541. #define FREE_ARG_TUP(self) do { \
  542. if ((self)->arg->ob_refcnt > 1) \
  543. Py_CLEAR((self)->arg); \
  544. } while (0)
  545. /* A temporary cleaner API for fast single argument function call.
  546. XXX: Does caching the argument tuple provides any real performance benefits?
  547. A quick benchmark, on a 2.0GHz Athlon64 3200+ running Linux 2.6.24 with
  548. glibc 2.7, tells me that it takes roughly 20,000,000 PyTuple_New(1) calls
  549. when the tuple is retrieved from the freelist (i.e, call PyTuple_New() then
  550. immediately DECREF it) and 1,200,000 calls when allocating brand new tuples
  551. (i.e, call PyTuple_New() and store the returned value in an array), to save
  552. one second (wall clock time). Either ways, the loading time a pickle stream
  553. large enough to generate this number of calls would be massively
  554. overwhelmed by other factors, like I/O throughput, the GC traversal and
  555. object allocation overhead. So, I really doubt these functions provide any
  556. real benefits.
  557. On the other hand, oprofile reports that pickle spends a lot of time in
  558. these functions. But, that is probably more related to the function call
  559. overhead, than the argument tuple allocation.
  560. XXX: And, what is the reference behavior of these? Steal, borrow? At first
  561. glance, it seems to steal the reference of 'arg' and borrow the reference
  562. of 'func'. */
  563. static PyObject *
  564. _Pickler_FastCall(PicklerObject *self, PyObject *func, PyObject *arg)
  565. {
  566. PyObject *result = NULL;
  567. ARG_TUP(self, arg);
  568. if (self->arg) {
  569. result = PyObject_Call(func, self->arg, NULL);
  570. FREE_ARG_TUP(self);
  571. }
  572. return result;
  573. }
  574. static int
  575. _Pickler_ClearBuffer(PicklerObject *self)
  576. {
  577. Py_CLEAR(self->output_buffer);
  578. self->output_buffer =
  579. PyBytes_FromStringAndSize(NULL, self->max_output_len);
  580. if (self->output_buffer == NULL)
  581. return -1;
  582. self->output_len = 0;
  583. return 0;
  584. }
  585. static PyObject *
  586. _Pickler_GetString(PicklerObject *self)
  587. {
  588. PyObject *output_buffer = self->output_buffer;
  589. assert(self->output_buffer != NULL);
  590. self->output_buffer = NULL;
  591. /* Resize down to exact size */
  592. if (_PyBytes_Resize(&output_buffer, self->output_len) < 0)
  593. return NULL;
  594. return output_buffer;
  595. }
  596. static int
  597. _Pickler_FlushToFile(PicklerObject *self)
  598. {
  599. PyObject *output, *result;
  600. assert(self->write != NULL);
  601. output = _Pickler_GetString(self);
  602. if (output == NULL)
  603. return -1;
  604. result = _Pickler_FastCall(self, self->write, output);
  605. Py_XDECREF(result);
  606. return (result == NULL) ? -1 : 0;
  607. }
  608. static Py_ssize_t
  609. _Pickler_Write(PicklerObject *self, const char *s, Py_ssize_t n)
  610. {
  611. Py_ssize_t i, required;
  612. char *buffer;
  613. assert(s != NULL);
  614. required = self->output_len + n;
  615. if (required > self->max_output_len) {
  616. if (self->write != NULL && required > MAX_WRITE_BUF_SIZE) {
  617. /* XXX This reallocates a new buffer every time, which is a bit
  618. wasteful. */
  619. if (_Pickler_FlushToFile(self) < 0)
  620. return -1;
  621. if (_Pickler_ClearBuffer(self) < 0)
  622. return -1;
  623. }
  624. if (self->write != NULL && n > MAX_WRITE_BUF_SIZE) {
  625. /* we already flushed above, so the buffer is empty */
  626. PyObject *result;
  627. /* XXX we could spare an intermediate copy and pass
  628. a memoryview instead */
  629. PyObject *output = PyBytes_FromStringAndSize(s, n);
  630. if (s == NULL)
  631. return -1;
  632. result = _Pickler_FastCall(self, self->write, output);
  633. Py_XDECREF(result);
  634. return (result == NULL) ? -1 : 0;
  635. }
  636. else {
  637. if (self->output_len >= PY_SSIZE_T_MAX / 2 - n) {
  638. PyErr_NoMemory();
  639. return -1;
  640. }
  641. self->max_output_len = (self->output_len + n) / 2 * 3;
  642. if (_PyBytes_Resize(&self->output_buffer, self->max_output_len) < 0)
  643. return -1;
  644. }
  645. }
  646. buffer = PyBytes_AS_STRING(self->output_buffer);
  647. if (n < 8) {
  648. /* This is faster than memcpy when the string is short. */
  649. for (i = 0; i < n; i++) {
  650. buffer[self->output_len + i] = s[i];
  651. }
  652. }
  653. else {
  654. memcpy(buffer + self->output_len, s, n);
  655. }
  656. self->output_len += n;
  657. return n;
  658. }
  659. static PicklerObject *
  660. _Pickler_New(void)
  661. {
  662. PicklerObject *self;
  663. self = PyObject_GC_New(PicklerObject, &Pickler_Type);
  664. if (self == NULL)
  665. return NULL;
  666. self->pers_func = NULL;
  667. self->dispatch_table = NULL;
  668. self->arg = NULL;
  669. self->write = NULL;
  670. self->proto = 0;
  671. self->bin = 0;
  672. self->fast = 0;
  673. self->fast_nesting = 0;
  674. self->fix_imports = 0;
  675. self->fast_memo = NULL;
  676. self->max_output_len = WRITE_BUF_SIZE;
  677. self->output_len = 0;
  678. self->memo = PyMemoTable_New();
  679. self->output_buffer = PyBytes_FromStringAndSize(NULL,
  680. self->max_output_len);
  681. if (self->memo == NULL || self->output_buffer == NULL) {
  682. Py_DECREF(self);
  683. return NULL;
  684. }
  685. return self;
  686. }
  687. static int
  688. _Pickler_SetProtocol(PicklerObject *self, PyObject *proto_obj,
  689. PyObject *fix_imports_obj)
  690. {
  691. long proto = 0;
  692. int fix_imports;
  693. if (proto_obj == NULL || proto_obj == Py_None)
  694. proto = DEFAULT_PROTOCOL;
  695. else {
  696. proto = PyLong_AsLong(proto_obj);
  697. if (proto == -1 && PyErr_Occurred())
  698. return -1;
  699. }
  700. if (proto < 0)
  701. proto = HIGHEST_PROTOCOL;
  702. if (proto > HIGHEST_PROTOCOL) {
  703. PyErr_Format(PyExc_ValueError, "pickle protocol must be <= %d",
  704. HIGHEST_PROTOCOL);
  705. return -1;
  706. }
  707. fix_imports = PyObject_IsTrue(fix_imports_obj);
  708. if (fix_imports == -1)
  709. return -1;
  710. self->proto = proto;
  711. self->bin = proto > 0;
  712. self->fix_imports = fix_imports && proto < 3;
  713. return 0;
  714. }
  715. /* Returns -1 (with an exception set) on failure, 0 on success. This may
  716. be called once on a freshly created Pickler. */
  717. static int
  718. _Pickler_SetOutputStream(PicklerObject *self, PyObject *file)
  719. {
  720. _Py_IDENTIFIER(write);
  721. assert(file != NULL);
  722. self->write = _PyObject_GetAttrId(file, &PyId_write);
  723. if (self->write == NULL) {
  724. if (PyErr_ExceptionMatches(PyExc_AttributeError))
  725. PyErr_SetString(PyExc_TypeError,
  726. "file must have a 'write' attribute");
  727. return -1;
  728. }
  729. return 0;
  730. }
  731. /* See documentation for _Pickler_FastCall(). */
  732. static PyObject *
  733. _Unpickler_FastCall(UnpicklerObject *self, PyObject *func, PyObject *arg)
  734. {
  735. PyObject *result = NULL;
  736. ARG_TUP(self, arg);
  737. if (self->arg) {
  738. result = PyObject_Call(func, self->arg, NULL);
  739. FREE_ARG_TUP(self);
  740. }
  741. return result;
  742. }
  743. /* Returns the size of the input on success, -1 on failure. This takes its
  744. own reference to `input`. */
  745. static Py_ssize_t
  746. _Unpickler_SetStringInput(UnpicklerObject *self, PyObject *input)
  747. {
  748. if (self->buffer.buf != NULL)
  749. PyBuffer_Release(&self->buffer);
  750. if (PyObject_GetBuffer(input, &self->buffer, PyBUF_CONTIG_RO) < 0)
  751. return -1;
  752. self->input_buffer = self->buffer.buf;
  753. self->input_len = self->buffer.len;
  754. self->next_read_idx = 0;
  755. self->prefetched_idx = self->input_len;
  756. return self->input_len;
  757. }
  758. static int
  759. _Unpickler_SkipConsumed(UnpicklerObject *self)
  760. {
  761. Py_ssize_t consumed = self->next_read_idx - self->prefetched_idx;
  762. if (consumed > 0) {
  763. PyObject *r;
  764. assert(self->peek); /* otherwise we did something wrong */
  765. /* This makes an useless copy... */
  766. r = PyObject_CallFunction(self->read, "n", consumed);
  767. if (r == NULL)
  768. return -1;
  769. Py_DECREF(r);
  770. self->prefetched_idx = self->next_read_idx;
  771. }
  772. return 0;
  773. }
  774. static const Py_ssize_t READ_WHOLE_LINE = -1;
  775. /* If reading from a file, we need to only pull the bytes we need, since there
  776. may be multiple pickle objects arranged contiguously in the same input
  777. buffer.
  778. If `n` is READ_WHOLE_LINE, read a whole line. Otherwise, read up to `n`
  779. bytes from the input stream/buffer.
  780. Update the unpickler's input buffer with the newly-read data. Returns -1 on
  781. failure; on success, returns the number of bytes read from the file.
  782. On success, self->input_len will be 0; this is intentional so that when
  783. unpickling from a file, the "we've run out of data" code paths will trigger,
  784. causing the Unpickler to go back to the file for more data. Use the returned
  785. size to tell you how much data you can process. */
  786. static Py_ssize_t
  787. _Unpickler_ReadFromFile(UnpicklerObject *self, Py_ssize_t n)
  788. {
  789. PyObject *data;
  790. Py_ssize_t read_size, prefetched_size = 0;
  791. assert(self->read != NULL);
  792. if (_Unpickler_SkipConsumed(self) < 0)
  793. return -1;
  794. if (n == READ_WHOLE_LINE)
  795. data = PyObject_Call(self->readline, empty_tuple, NULL);
  796. else {
  797. PyObject *len = PyLong_FromSsize_t(n);
  798. if (len == NULL)
  799. return -1;
  800. data = _Unpickler_FastCall(self, self->read, len);
  801. }
  802. if (data == NULL)
  803. return -1;
  804. /* Prefetch some data without advancing the file pointer, if possible */
  805. if (self->peek) {
  806. PyObject *len, *prefetched;
  807. len = PyLong_FromSsize_t(PREFETCH);
  808. if (len == NULL) {
  809. Py_DECREF(data);
  810. return -1;
  811. }
  812. prefetched = _Unpickler_FastCall(self, self->peek, len);
  813. if (prefetched == NULL) {
  814. if (PyErr_ExceptionMatches(PyExc_NotImplementedError)) {
  815. /* peek() is probably not supported by the given file object */
  816. PyErr_Clear();
  817. Py_CLEAR(self->peek);
  818. }
  819. else {
  820. Py_DECREF(data);
  821. return -1;
  822. }
  823. }
  824. else {
  825. assert(PyBytes_Check(prefetched));
  826. prefetched_size = PyBytes_GET_SIZE(prefetched);
  827. PyBytes_ConcatAndDel(&data, prefetched);
  828. if (data == NULL)
  829. return -1;
  830. }
  831. }
  832. read_size = _Unpickler_SetStringInput(self, data) - prefetched_size;
  833. Py_DECREF(data);
  834. self->prefetched_idx = read_size;
  835. return read_size;
  836. }
  837. /* Read `n` bytes from the unpickler's data source, storing the result in `*s`.
  838. This should be used for all data reads, rather than accessing the unpickler's
  839. input buffer directly. This method deals correctly with reading from input
  840. streams, which the input buffer doesn't deal with.
  841. Note that when reading from a file-like object, self->next_read_idx won't
  842. be updated (it should remain at 0 for the entire unpickling process). You
  843. should use this function's return value to know how many bytes you can
  844. consume.
  845. Returns -1 (with an exception set) on failure. On success, return the
  846. number of chars read. */
  847. static Py_ssize_t
  848. _Unpickler_Read(UnpicklerObject *self, char **s, Py_ssize_t n)
  849. {
  850. Py_ssize_t num_read;
  851. if (self->next_read_idx + n <= self->input_len) {
  852. *s = self->input_buffer + self->next_read_idx;
  853. self->next_read_idx += n;
  854. return n;
  855. }
  856. if (!self->read) {
  857. PyErr_Format(PyExc_EOFError, "Ran out of input");
  858. return -1;
  859. }
  860. num_read = _Unpickler_ReadFromFile(self, n);
  861. if (num_read < 0)
  862. return -1;
  863. if (num_read < n) {
  864. PyErr_Format(PyExc_EOFError, "Ran out of input");
  865. return -1;
  866. }
  867. *s = self->input_buffer;
  868. self->next_read_idx = n;
  869. return n;
  870. }
  871. static Py_ssize_t
  872. _Unpickler_CopyLine(UnpicklerObject *self, char *line, Py_ssize_t len,
  873. char **result)
  874. {
  875. char *input_line = PyMem_Realloc(self->input_line, len + 1);
  876. if (input_line == NULL) {
  877. PyErr_NoMemory();
  878. return -1;
  879. }
  880. memcpy(input_line, line, len);
  881. input_line[len] = '\0';
  882. self->input_line = input_line;
  883. *result = self->input_line;
  884. return len;
  885. }
  886. /* Read a line from the input stream/buffer. If we run off the end of the input
  887. before hitting \n, return the data we found.
  888. Returns the number of chars read, or -1 on failure. */
  889. static Py_ssize_t
  890. _Unpickler_Readline(UnpicklerObject *self, char **result)
  891. {
  892. Py_ssize_t i, num_read;
  893. for (i = self->next_read_idx; i < self->input_len; i++) {
  894. if (self->input_buffer[i] == '\n') {
  895. char *line_start = self->input_buffer + self->next_read_idx;
  896. num_read = i - self->next_read_idx + 1;
  897. self->next_read_idx = i + 1;
  898. return _Unpickler_CopyLine(self, line_start, num_read, result);
  899. }
  900. }
  901. if (self->read) {
  902. num_read = _Unpickler_ReadFromFile(self, READ_WHOLE_LINE);
  903. if (num_read < 0)
  904. return -1;
  905. self->next_read_idx = num_read;
  906. return _Unpickler_CopyLine(self, self->input_buffer, num_read, result);
  907. }
  908. /* If we get here, we've run off the end of the input string. Return the
  909. remaining string and let the caller figure it out. */
  910. *result = self->input_buffer + self->next_read_idx;
  911. num_read = i - self->next_read_idx;
  912. self->next_read_idx = i;
  913. return num_read;
  914. }
  915. /* Returns -1 (with an exception set) on failure, 0 on success. The memo array
  916. will be modified in place. */
  917. static int
  918. _Unpickler_ResizeMemoList(UnpicklerObject *self, Py_ssize_t new_size)
  919. {
  920. Py_ssize_t i;
  921. PyObject **memo;
  922. assert(new_size > self->memo_size);
  923. memo = PyMem_REALLOC(self->memo, new_size * sizeof(PyObject *));
  924. if (memo == NULL) {
  925. PyErr_NoMemory();
  926. return -1;
  927. }
  928. self->memo = memo;
  929. for (i = self->memo_size; i < new_size; i++)
  930. self->memo[i] = NULL;
  931. self->memo_size = new_size;
  932. return 0;
  933. }
  934. /* Returns NULL if idx is out of bounds. */
  935. static PyObject *
  936. _Unpickler_MemoGet(UnpicklerObject *self, Py_ssize_t idx)
  937. {
  938. if (idx < 0 || idx >= self->memo_size)
  939. return NULL;
  940. return self->memo[idx];
  941. }
  942. /* Returns -1 (with an exception set) on failure, 0 on success.
  943. This takes its own reference to `value`. */
  944. static int
  945. _Unpickler_MemoPut(UnpicklerObject *self, Py_ssize_t idx, PyObject *value)
  946. {
  947. PyObject *old_item;
  948. if (idx >= self->memo_size) {
  949. if (_Unpickler_ResizeMemoList(self, idx * 2) < 0)
  950. return -1;
  951. assert(idx < self->memo_size);
  952. }
  953. Py_INCREF(value);
  954. old_item = self->memo[idx];
  955. self->memo[idx] = value;
  956. Py_XDECREF(old_item);
  957. return 0;
  958. }
  959. static PyObject **
  960. _Unpickler_NewMemo(Py_ssize_t new_size)
  961. {
  962. PyObject **memo = PyMem_MALLOC(new_size * sizeof(PyObject *));
  963. if (memo == NULL) {
  964. PyErr_NoMemory();
  965. return NULL;
  966. }
  967. memset(memo, 0, new_size * sizeof(PyObject *));
  968. return memo;
  969. }
  970. /* Free the unpickler's memo, taking care to decref any items left in it. */
  971. static void
  972. _Unpickler_MemoCleanup(UnpicklerObject *self)
  973. {
  974. Py_ssize_t i;
  975. PyObject **memo = self->memo;
  976. if (self->memo == NULL)
  977. return;
  978. self->memo = NULL;
  979. i = self->memo_size;
  980. while (--i >= 0) {
  981. Py_XDECREF(memo[i]);
  982. }
  983. PyMem_FREE(memo);
  984. }
  985. static UnpicklerObject *
  986. _Unpickler_New(void)
  987. {
  988. UnpicklerObject *self;
  989. self = PyObject_GC_New(UnpicklerObject, &Unpickler_Type);
  990. if (self == NULL)
  991. return NULL;
  992. self->arg = NULL;
  993. self->pers_func = NULL;
  994. self->input_buffer = NULL;
  995. self->input_line = NULL;
  996. self->input_len = 0;
  997. self->next_read_idx = 0;
  998. self->prefetched_idx = 0;
  999. self->read = NULL;
  1000. self->readline = NULL;
  1001. self->peek = NULL;
  1002. self->encoding = NULL;
  1003. self->errors = NULL;
  1004. self->marks = NULL;
  1005. self->num_marks = 0;
  1006. self->marks_size = 0;
  1007. self->proto = 0;
  1008. self->fix_imports = 0;
  1009. memset(&self->buffer, 0, sizeof(Py_buffer));
  1010. self->memo_size = 32;
  1011. self->memo = _Unpickler_NewMemo(self->memo_size);
  1012. self->stack = (Pdata *)Pdata_New();
  1013. if (self->memo == NULL || self->stack == NULL) {
  1014. Py_DECREF(self);
  1015. return NULL;
  1016. }
  1017. return self;
  1018. }
  1019. /* Returns -1 (with an exception set) on failure, 0 on success. This may
  1020. be called once on a freshly created Pickler. */
  1021. static int
  1022. _Unpickler_SetInputStream(UnpicklerObject *self, PyObject *file)
  1023. {
  1024. _Py_IDENTIFIER(peek);
  1025. _Py_IDENTIFIER(read);
  1026. _Py_IDENTIFIER(readline);
  1027. self->peek = _PyObject_GetAttrId(file, &PyId_peek);
  1028. if (self->peek == NULL) {
  1029. if (PyErr_ExceptionMatches(PyExc_AttributeError))
  1030. PyErr_Clear();
  1031. else
  1032. return -1;
  1033. }
  1034. self->read = _PyObject_GetAttrId(file, &PyId_read);
  1035. self->readline = _PyObject_GetAttrId(file, &PyId_readline);
  1036. if (self->readline == NULL || self->read == NULL) {
  1037. if (PyErr_ExceptionMatches(PyExc_AttributeError))
  1038. PyErr_SetString(PyExc_TypeError,
  1039. "file must have 'read' and 'readline' attributes");
  1040. Py_CLEAR(self->read);
  1041. Py_CLEAR(self->readline);
  1042. Py_CLEAR(self->peek);
  1043. return -1;
  1044. }
  1045. return 0;
  1046. }
  1047. /* Returns -1 (with an exception set) on failure, 0 on success. This may
  1048. be called once on a freshly created Pickler. */
  1049. static int
  1050. _Unpickler_SetInputEncoding(UnpicklerObject *self,
  1051. const char *encoding,
  1052. const char *errors)
  1053. {
  1054. if (encoding == NULL)
  1055. encoding = "ASCII";
  1056. if (errors == NULL)
  1057. errors = "strict";
  1058. self->encoding = _PyMem_Strdup(encoding);
  1059. self->errors = _PyMem_Strdup(errors);
  1060. if (self->encoding == NULL || self->errors == NULL) {
  1061. PyErr_NoMemory();
  1062. return -1;
  1063. }
  1064. return 0;
  1065. }
  1066. /* Generate a GET opcode for an object stored in the memo. */
  1067. static int
  1068. memo_get(PicklerObject *self, PyObject *key)
  1069. {
  1070. Py_ssize_t *value;
  1071. char pdata[30];
  1072. Py_ssize_t len;
  1073. value = PyMemoTable_Get(self->memo, key);
  1074. if (value == NULL) {
  1075. PyErr_SetObject(PyExc_KeyError, key);
  1076. return -1;
  1077. }
  1078. if (!self->bin) {
  1079. pdata[0] = GET;
  1080. PyOS_snprintf(pdata + 1, sizeof(pdata) - 1,
  1081. "%" PY_FORMAT_SIZE_T "d\n", *value);
  1082. len = strlen(pdata);
  1083. }
  1084. else {
  1085. if (*value < 256) {
  1086. pdata[0] = BINGET;
  1087. pdata[1] = (unsigned char)(*value & 0xff);
  1088. len = 2;
  1089. }
  1090. else if (*value <= 0xffffffffL) {
  1091. pdata[0] = LONG_BINGET;
  1092. pdata[1] = (unsigned char)(*value & 0xff);
  1093. pdata[2] = (unsigned char)((*value >> 8) & 0xff);
  1094. pdata[3] = (unsigned char)((*value >> 16) & 0xff);
  1095. pdata[4] = (unsigned char)((*value >> 24) & 0xff);
  1096. len = 5;
  1097. }
  1098. else { /* unlikely */
  1099. PyErr_SetString(PicklingError,
  1100. "memo id too large for LONG_BINGET");
  1101. return -1;
  1102. }
  1103. }
  1104. if (_Pickler_Write(self, pdata, len) < 0)
  1105. return -1;
  1106. return 0;
  1107. }
  1108. /* Store an object in the memo, assign it a new unique ID based on the number
  1109. of objects currently stored in the memo and generate a PUT opcode. */
  1110. static int
  1111. memo_put(PicklerObject *self, PyObject *obj)
  1112. {
  1113. Py_ssize_t x;
  1114. char pdata[30];
  1115. Py_ssize_t len;
  1116. int status = 0;
  1117. if (self->fast)
  1118. return 0;
  1119. x = PyMemoTable_Size(self->memo);
  1120. if (PyMemoTable_Set(self->memo, obj, x) < 0)
  1121. goto error;
  1122. if (!self->bin) {
  1123. pdata[0] = PUT;
  1124. PyOS_snprintf(pdata + 1, sizeof(pdata) - 1,
  1125. "%" PY_FORMAT_SIZE_T "d\n", x);
  1126. len = strlen(pdata);
  1127. }
  1128. else {
  1129. if (x < 256) {
  1130. pdata[0] = BINPUT;
  1131. pdata[1] = (unsigned char)x;
  1132. len = 2;
  1133. }
  1134. else if (x <= 0xffffffffL) {
  1135. pdata[0] = LONG_BINPUT;
  1136. pdata[1] = (unsigned char)(x & 0xff);
  1137. pdata[2] = (unsigned char)((x >> 8) & 0xff);
  1138. pdata[3] = (unsigned char)((x >> 16) & 0xff);
  1139. pdata[4] = (unsigned char)((x >> 24) & 0xff);
  1140. len = 5;
  1141. }
  1142. else { /* unlikely */
  1143. PyErr_SetString(PicklingError,
  1144. "memo id too large for LONG_BINPUT");
  1145. return -1;
  1146. }
  1147. }
  1148. if (_Pickler_Write(self, pdata, len) < 0)
  1149. goto error;
  1150. if (0) {
  1151. error:
  1152. status = -1;
  1153. }
  1154. return status;
  1155. }
  1156. static PyObject *
  1157. whichmodule(PyObject *global, PyObject *global_name)
  1158. {
  1159. Py_ssize_t i, j;
  1160. static PyObject *module_str = NULL;
  1161. static PyObject *main_str = NULL;
  1162. PyObject *module_name;
  1163. PyObject *modules_dict;
  1164. PyObject *module;
  1165. PyObject *obj;
  1166. if (module_str == NULL) {
  1167. module_str = PyUnicode_InternFromString("__module__");
  1168. if (module_str == NULL)
  1169. return NULL;
  1170. main_str = PyUnicode_InternFromString("__main__");
  1171. if (main_str == NULL)
  1172. return NULL;
  1173. }
  1174. module_name = PyObject_GetAttr(global, module_str);
  1175. /* In some rare cases (e.g., bound methods of extension types),
  1176. __module__ can be None. If it is so, then search sys.modules
  1177. for the module of global. */
  1178. if (module_name == Py_None) {
  1179. Py_DECREF(module_name);
  1180. goto search;
  1181. }
  1182. if (module_name) {
  1183. return module_name;
  1184. }
  1185. if (PyErr_ExceptionMatches(PyExc_AttributeError))
  1186. PyErr_Clear();
  1187. else
  1188. return NULL;
  1189. search:
  1190. modules_dict = PySys_GetObject("modules");
  1191. if (modules_dict == NULL) {
  1192. PyErr_SetString(PyExc_RuntimeError, "unable to get sys.modules");
  1193. return NULL;
  1194. }
  1195. i = 0;
  1196. module_name = NULL;
  1197. while ((j = PyDict_Next(modules_dict, &i, &module_name, &module))) {
  1198. if (PyObject_RichCompareBool(module_name, main_str, Py_EQ) == 1)
  1199. continue;
  1200. obj = PyObject_GetAttr(module, global_name);
  1201. if (obj == NULL) {
  1202. if (PyErr_ExceptionMatches(PyExc_AttributeError))
  1203. PyErr_Clear();
  1204. else
  1205. return NULL;
  1206. continue;
  1207. }
  1208. if (obj != global) {
  1209. Py_DECREF(obj);
  1210. continue;
  1211. }
  1212. Py_DECREF(obj);
  1213. break;
  1214. }
  1215. /* If no module is found, use __main__. */
  1216. if (!j) {
  1217. module_name = main_str;
  1218. }
  1219. Py_INCREF(module_name);
  1220. return module_name;
  1221. }
  1222. /* fast_save_enter() and fast_save_leave() are guards against recursive
  1223. objects when Pickler is used with the "fast mode" (i.e., with object
  1224. memoization disabled). If the nesting of a list or dict object exceed
  1225. FAST_NESTING_LIMIT, these guards will start keeping an internal
  1226. reference to the seen list or dict objects and check whether these objects
  1227. are recursive. These are not strictly necessary, since save() has a
  1228. hard-coded recursion limit, but they give a nicer error message than the
  1229. typical RuntimeError. */
  1230. static int
  1231. fast_save_enter(PicklerObject *self, PyObject *obj)
  1232. {
  1233. /* if fast_nesting < 0, we're doing an error exit. */
  1234. if (++self->fast_nesting >= FAST_NESTING_LIMIT) {
  1235. PyObject *key = NULL;
  1236. if (self->fast_memo == NULL) {
  1237. self->fast_memo = PyDict_New();
  1238. if (self->fast_memo == NULL) {
  1239. self->fast_nesting = -1;
  1240. return 0;
  1241. }
  1242. }
  1243. key = PyLong_FromVoidPtr(obj);
  1244. if (key == NULL)
  1245. return 0;
  1246. if (PyDict_GetItem(self->fast_memo, key)) {
  1247. Py_DECREF(key);
  1248. PyErr_Format(PyExc_ValueError,
  1249. "fast mode: can't pickle cyclic objects "
  1250. "including object type %.200s at %p",
  1251. obj->ob_type->tp_name, obj);
  1252. self->fast_nesting = -1;
  1253. return 0;
  1254. }
  1255. if (PyDict_SetItem(self->fast_memo, key, Py_None) < 0) {
  1256. Py_DECREF(key);
  1257. self->fast_nesting = -1;
  1258. return 0;
  1259. }
  1260. Py_DECREF(key);
  1261. }
  1262. return 1;
  1263. }
  1264. static int
  1265. fast_save_leave(PicklerObject *self, PyObject *obj)
  1266. {
  1267. if (self->fast_nesting-- >= FAST_NESTING_LIMIT) {
  1268. PyObject *key = PyLong_FromVoidPtr(obj);
  1269. if (key == NULL)
  1270. return 0;
  1271. if (PyDict_DelItem(self->fast_memo, key) < 0) {
  1272. Py_DECREF(key);
  1273. return 0;
  1274. }
  1275. Py_DECREF(key);
  1276. }
  1277. return 1;
  1278. }
  1279. static int
  1280. save_none(PicklerObject *self, PyObject *obj)
  1281. {
  1282. const char none_op = NONE;
  1283. if (_Pickler_Write(self, &none_op, 1) < 0)
  1284. return -1;
  1285. return 0;
  1286. }
  1287. static int
  1288. save_bool(PicklerObject *self, PyObject *obj)
  1289. {
  1290. static const char *buf[2] = { FALSE, TRUE };
  1291. const char len[2] = {sizeof(FALSE) - 1, sizeof(TRUE) - 1};
  1292. int p = (obj == Py_True);
  1293. if (self->proto >= 2) {
  1294. const char bool_op = p ? NEWTRUE : NEWFALSE;
  1295. if (_Pickler_Write(self, &bool_op, 1) < 0)
  1296. return -1;
  1297. }
  1298. else if (_Pickler_Write(self, buf[p], len[p]) < 0)
  1299. return -1;
  1300. return 0;
  1301. }
  1302. static int
  1303. save_int(PicklerObject *self, long x)
  1304. {
  1305. char pdata[32];
  1306. Py_ssize_t len = 0;
  1307. if (!self->bin
  1308. #if SIZEOF_LONG > 4
  1309. || x > 0x7fffffffL || x < -0x80000000L
  1310. #endif
  1311. ) {
  1312. /* Text-mode pickle, or long too big to fit in the 4-byte
  1313. * signed BININT format: store as a string.
  1314. */
  1315. pdata[0] = LONG; /* use LONG for consistency with pickle.py */
  1316. PyOS_snprintf(pdata + 1, sizeof(pdata) - 1, "%ldL\n", x);
  1317. if (_Pickler_Write(self, pdata, strlen(pdata)) < 0)
  1318. return -1;
  1319. }
  1320. else {
  1321. /* Binary pickle and x fits in a signed 4-byte int. */
  1322. pdata[1] = (unsigned char)(x & 0xff);
  1323. pdata[2] = (unsigned char)((x >> 8) & 0xff);
  1324. pdata[3] = (unsigned char)((x >> 16) & 0xff);
  1325. pdata[4] = (unsigned char)((x >> 24) & 0xff);
  1326. if ((pdata[4] == 0) && (pdata[3] == 0)) {
  1327. if (pdata[2] == 0) {
  1328. pdata[0] = BININT1;
  1329. len = 2;
  1330. }
  1331. else {
  1332. pdata[0] = BININT2;
  1333. len = 3;
  1334. }
  1335. }
  1336. else {
  1337. pdata[0] = BININT;
  1338. len = 5;
  1339. }
  1340. if (_Pickler_Write(self, pdata, len) < 0)
  1341. return -1;
  1342. }
  1343. return 0;
  1344. }
  1345. static int
  1346. save_long(PicklerObject *self, PyObject *obj)
  1347. {
  1348. PyObject *repr = NULL;
  1349. Py_ssize_t size;
  1350. long val = PyLong_AsLong(obj);
  1351. int status = 0;
  1352. const char long_op = LONG;
  1353. if (val == -1 && PyErr_Occurred()) {
  1354. /* out of range for int pickling */
  1355. PyErr_Clear();
  1356. }
  1357. else
  1358. #if SIZEOF_LONG > 4
  1359. if (val <= 0x7fffffffL && val >= -0x80000000L)
  1360. #endif
  1361. return save_int(self, val);
  1362. if (self->proto >= 2) {
  1363. /* Linear-time pickling. */
  1364. size_t nbits;
  1365. size_t nbytes;
  1366. unsigned char *pdata;
  1367. char header[5];
  1368. int i;
  1369. int sign = _PyLong_Sign(obj);
  1370. if (sign == 0) {
  1371. header[0] = LONG1;
  1372. header[1] = 0; /* It's 0 -- an empty bytestring. */
  1373. if (_Pickler_Write(self, header, 2) < 0)
  1374. goto error;
  1375. return 0;
  1376. }
  1377. nbits = _PyLong_NumBits(obj);
  1378. if (nbits == (size_t)-1 && PyErr_Occurred())
  1379. goto error;
  1380. /* How many bytes do we need? There are nbits >> 3 full
  1381. * bytes of data, and nbits & 7 leftover bits. If there
  1382. * are any leftover bits, then we clearly need another
  1383. * byte. Wnat's not so obvious is that we *probably*
  1384. * need another byte even if there aren't any leftovers:
  1385. * the most-significant bit of the most-significant byte
  1386. * acts like a sign bit, and it's usually got a sense
  1387. * opposite of the one we need. The exception is longs
  1388. * of the form -(2**(8*j-1)) for j > 0. Such a long is
  1389. * its own 256's-complement, so has the right sign bit
  1390. * even without the extra byte. That's a pain to check
  1391. * for in advance, though, so we always grab an extra
  1392. * byte at the start, and cut it back later if possible.
  1393. */
  1394. nbytes = (nbits >> 3) + 1;
  1395. if (nbytes > 0x7fffffffL) {
  1396. PyErr_SetString(PyExc_OverflowError,
  1397. "long too large to pickle");
  1398. goto error;
  1399. }
  1400. repr = PyBytes_FromStringAndSize(NULL, (Py_ssize_t)nbytes);
  1401. if (repr == NULL)
  1402. goto error;
  1403. pdata = (unsigned char *)PyBytes_AS_STRING(repr);
  1404. i = _PyLong_AsByteArray((PyLongObject *)obj,
  1405. pdata, nbytes,
  1406. 1 /* little endian */ , 1 /* signed */ );
  1407. if (i < 0)
  1408. goto error;
  1409. /* If the long is negative, this may be a byte more than
  1410. * needed. This is so iff the MSB is all redundant sign
  1411. * bits.
  1412. */
  1413. if (sign < 0 &&
  1414. nbytes > 1 &&
  1415. pdata[nbytes - 1] == 0xff &&
  1416. (pdata[nbytes - 2] & 0x80) != 0) {
  1417. nbytes--;
  1418. }
  1419. if (nbytes < 256) {
  1420. header[0] = LONG1;
  1421. header[1] = (unsigned char)nbytes;
  1422. size = 2;
  1423. }
  1424. else {
  1425. header[0] = LONG4;
  1426. size = (Py_ssize_t) nbytes;
  1427. for (i = 1; i < 5; i++) {
  1428. header[i] = (unsigned char)(size & 0xff);
  1429. size >>= 8;
  1430. }
  1431. size = 5;
  1432. }
  1433. if (_Pickler_Write(self, header, size) < 0 ||
  1434. _Pickler_Write(self, (char *)pdata, (int)nbytes) < 0)
  1435. goto error;
  1436. }
  1437. else {
  1438. char *string;
  1439. /* proto < 2: write the repr and newline. This is quadratic-time (in
  1440. the number of digits), in both directions. We add a trailing 'L'
  1441. to the repr, for compatibility with Python 2.x. */
  1442. repr = PyObject_Repr(obj);
  1443. if (repr == NULL)
  1444. goto error;
  1445. string = _PyUnicode_AsStringAndSize(repr, &size);
  1446. if (string == NULL)
  1447. goto error;
  1448. if (_Pickler_Write(self, &long_op, 1) < 0 ||
  1449. _Pickler_Write(self, string, size) < 0 ||
  1450. _Pickler_Write(self, "L\n", 2) < 0)
  1451. goto error;
  1452. }
  1453. if (0) {
  1454. error:
  1455. status = -1;
  1456. }
  1457. Py_XDECREF(repr);
  1458. return status;
  1459. }
  1460. static int
  1461. save_float(PicklerObject *self, PyObject *obj)
  1462. {
  1463. double x = PyFloat_AS_DOUBLE((PyFloatObject *)obj);
  1464. if (self->bin) {
  1465. char pdata[9];
  1466. pdata[0] = BINFLOAT;
  1467. if (_PyFloat_Pack8(x, (unsigned char *)&pdata[1], 0) < 0)
  1468. return -1;
  1469. if (_Pickler_Write(self, pdata, 9) < 0)
  1470. return -1;
  1471. }
  1472. else {
  1473. int result = -1;
  1474. char *buf = NULL;
  1475. char op = FLOAT;
  1476. if (_Pickler_Write(self, &op, 1) < 0)
  1477. goto done;
  1478. buf = PyOS_double_to_string(x, 'g', 17, 0, NULL);
  1479. if (!buf) {
  1480. PyErr_NoMemory();
  1481. goto done;
  1482. }
  1483. if (_Pickler_Write(self, buf, strlen(buf)) < 0)
  1484. goto done;
  1485. if (_Pickler_Write(self, "\n", 1) < 0)
  1486. goto done;
  1487. result = 0;
  1488. done:
  1489. PyMem_Free(buf);
  1490. return result;
  1491. }
  1492. return 0;
  1493. }
  1494. static int
  1495. save_bytes(PicklerObject *self, PyObject *obj)
  1496. {
  1497. if (self->proto < 3) {
  1498. /* Older pickle protocols do not have an opcode for pickling bytes
  1499. objects. Therefore, we need to fake the copy protocol (i.e.,
  1500. the __reduce__ method) to permit bytes object unpickling.
  1501. Here we use a hack to be compatible with Python 2. Since in Python
  1502. 2 'bytes' is just an alias for 'str' (which has different
  1503. parameters than the actual bytes object), we use codecs.encode
  1504. to create the appropriate 'str' object when unpickled using
  1505. Python 2 *and* the appropriate 'bytes' object when unpickled
  1506. using Python 3. Again this is a hack and we don't need to do this
  1507. with newer protocols. */
  1508. static PyObject *codecs_encode = NULL;
  1509. PyObject *reduce_value = NULL;
  1510. int status;
  1511. if (codecs_encode == NULL) {
  1512. PyObject *codecs_module = PyImport_ImportModule("codecs");
  1513. if (codecs_module == NULL) {
  1514. return -1;
  1515. }
  1516. codecs_encode = PyObject_GetAttrString(codecs_module, "encode");
  1517. Py_DECREF(codecs_module);
  1518. if (codecs_encode == NULL) {
  1519. return -1;
  1520. }
  1521. }
  1522. if (PyBytes_GET_SIZE(obj) == 0) {
  1523. reduce_value = Py_BuildValue("(O())", (PyObject*)&PyBytes_Type);
  1524. }
  1525. else {
  1526. static PyObject *latin1 = NULL;
  1527. PyObject *unicode_str =
  1528. PyUnicode_DecodeLatin1(PyBytes_AS_STRING(obj),
  1529. PyBytes_GET_SIZE(obj),
  1530. "strict");
  1531. if (unicode_str == NULL)
  1532. return -1;
  1533. if (latin1 == NULL) {
  1534. latin1 = PyUnicode_InternFromString("latin1");
  1535. if (latin1 == NULL) {
  1536. Py_DECREF(unicode_str);
  1537. return -1;
  1538. }
  1539. }
  1540. reduce_value = Py_BuildValue("(O(OO))",
  1541. codecs_encode, unicode_str, latin1);
  1542. Py_DECREF(unicode_str);
  1543. }
  1544. if (reduce_value == NULL)
  1545. return -1;
  1546. /* save_reduce() will memoize the object automatically. */
  1547. status = save_reduce(self, reduce_value, obj);
  1548. Py_DECREF(reduce_value);
  1549. return status;
  1550. }
  1551. else {
  1552. Py_ssize_t size;
  1553. char header[5];
  1554. Py_ssize_t len;
  1555. size = PyBytes_GET_SIZE(obj);
  1556. if (size < 0)
  1557. return -1;
  1558. if (size < 256) {
  1559. header[0] = SHORT_BINBYTES;
  1560. header[1] = (unsigned char)size;
  1561. len = 2;
  1562. }
  1563. else if (size <= 0xffffffffL) {
  1564. header[0] = BINBYTES;
  1565. header[1] = (unsigned char)(size & 0xff);
  1566. header[2] = (unsigned char)((size >> 8) & 0xff);
  1567. header[3] = (unsigned char)((size >> 16) & 0xff);
  1568. header[4] = (unsigned char)((size >> 24) & 0xff);
  1569. len = 5;
  1570. }
  1571. else {
  1572. PyErr_SetString(PyExc_OverflowError,
  1573. "cannot serialize a bytes object larger than 4 GiB");
  1574. return -1; /* string too large */
  1575. }
  1576. if (_Pickler_Write(self, header, len) < 0)
  1577. return -1;
  1578. if (_Pickler_Write(self, PyBytes_AS_STRING(obj), size) < 0)
  1579. return -1;
  1580. if (memo_put(self, obj) < 0)
  1581. return -1;
  1582. return 0;
  1583. }
  1584. }
  1585. /* A copy of PyUnicode_EncodeRawUnicodeEscape() that also translates
  1586. backslash and newline characters to \uXXXX escapes. */
  1587. static PyObject *
  1588. raw_unicode_escape(PyObject *obj)
  1589. {
  1590. PyObject *repr, *result;
  1591. char *p;
  1592. Py_ssize_t i, size, expandsize;
  1593. void *data;
  1594. unsigned int kind;
  1595. if (PyUnicode_READY(obj))
  1596. return NULL;
  1597. size = PyUnicode_GET_LENGTH(obj);
  1598. data = PyUnicode_DATA(obj);
  1599. kind = PyUnicode_KIND(obj);
  1600. if (kind == PyUnicode_4BYTE_KIND)
  1601. expandsize = 10;
  1602. else
  1603. expandsize = 6;
  1604. if (size > PY_SSIZE_T_MAX / expandsize)
  1605. return PyErr_NoMemory();
  1606. repr = PyByteArray_FromStringAndSize(NULL, expandsize * size);
  1607. if (repr == NULL)
  1608. return NULL;
  1609. if (size == 0)
  1610. goto done;
  1611. p = PyByteArray_AS_STRING(repr);
  1612. for (i=0; i < size; i++) {
  1613. Py_UCS4 ch = PyUnicode_READ(kind, data, i);
  1614. /* Map 32-bit characters to '\Uxxxxxxxx' */
  1615. if (ch >= 0x10000) {
  1616. *p++ = '\\';
  1617. *p++ = 'U';
  1618. *p++ = Py_hexdigits[(ch >> 28) & 0xf];
  1619. *p++ = Py_hexdigits[(ch >> 24) & 0xf];
  1620. *p++ = Py_hexdigits[(ch >> 20) & 0xf];
  1621. *p++ = Py_hexdigits[(ch >> 16) & 0xf];
  1622. *p++ = Py_hexdigits[(ch >> 12) & 0xf];
  1623. *p++ = Py_hexdigits[(ch >> 8) & 0xf];
  1624. *p++ = Py_hexdigits[(ch >> 4) & 0xf];
  1625. *p++ = Py_hexdigits[ch & 15];
  1626. }
  1627. /* Map 16-bit characters to '\uxxxx' */
  1628. else if (ch >= 256 || ch == '\\' || ch == '\n') {
  1629. *p++ = '\\';
  1630. *p++ = 'u';
  1631. *p++ = Py_hexdigits[(ch >> 12) & 0xf];
  1632. *p++ = Py_hexdigits[(ch >> 8) & 0xf];
  1633. *p++ = Py_hexdigits[(ch >> 4) & 0xf];
  1634. *p++ = Py_hexdigits[ch & 15];
  1635. }
  1636. /* Copy everything else as-is */
  1637. else
  1638. *p++ = (char) ch;
  1639. }
  1640. size = p - PyByteArray_AS_STRING(repr);
  1641. done:
  1642. result = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(repr), size);
  1643. Py_DECREF(repr);
  1644. return result;
  1645. }
  1646. static int
  1647. write_utf8(PicklerObject *self, char *data, Py_ssize_t size)
  1648. {
  1649. char pdata[5];
  1650. #if SIZEOF_SIZE_T > 4
  1651. if (size > 0xffffffffUL) {
  1652. /* string too large */
  1653. PyErr_SetString(PyExc_OverflowError,
  1654. "cannot serialize a string larger than 4GiB");
  1655. return -1;
  1656. }
  1657. #endif
  1658. pdata[0] = BINUNICODE;
  1659. pdata[1] = (unsigned char)(size & 0xff);
  1660. pdata[2] = (unsigned char)((size >> 8) & 0xff);
  1661. pdata[3] = (unsigned char)((size >> 16) & 0xff);
  1662. pdata[4] = (unsigned char)((size >> 24) & 0xff);
  1663. if (_Pickler_Write(self, pdata, sizeof(pdata)) < 0)
  1664. return -1;
  1665. if (_Pickler_Write(self, data, size) < 0)
  1666. return -1;
  1667. return 0;
  1668. }
  1669. static int
  1670. write_unicode_binary(PicklerObject *self, PyObject *obj)
  1671. {
  1672. PyObject *encoded = NULL;
  1673. Py_ssize_t size;
  1674. char *data;
  1675. int r;
  1676. if (PyUnicode_READY(obj))
  1677. return -1;
  1678. data = PyUnicode_AsUTF8AndSize(obj, &size);
  1679. if (data != NULL)
  1680. return write_utf8(self, data, size);
  1681. /* Issue #8383: for strings with lone surrogates, fallback on the
  1682. "surrogatepass" error handler. */
  1683. PyErr_Clear();
  1684. encoded = PyUnicode_AsEncodedString(obj, "utf-8", "surrogatepass");
  1685. if (encoded == NULL)
  1686. return -1;
  1687. r = write_utf8(self, PyBytes_AS_STRING(encoded),
  1688. PyBytes_GET_SIZE(encoded));
  1689. Py_DECREF(encoded);
  1690. return r;
  1691. }
  1692. static int
  1693. save_unicode(PicklerObject *self, PyObject *obj)
  1694. {
  1695. if (self->bin) {
  1696. if (write_unicode_binary(self, obj) < 0)
  1697. return -1;
  1698. }
  1699. else {
  1700. PyObject *encoded;
  1701. Py_ssize_t size;
  1702. const char unicode_op = UNICODE;
  1703. encoded = raw_unicode_escape(obj);
  1704. if (encoded == NULL)
  1705. return -1;
  1706. if (_Pickler_Write(self, &unicode_op, 1) < 0) {
  1707. Py_DECREF(encoded);
  1708. return -1;
  1709. }
  1710. size = PyBytes_GET_SIZE(encoded);
  1711. if (_Pickler_Write(self, PyBytes_AS_STRING(encoded), size) < 0) {
  1712. Py_DECREF(encoded);
  1713. return -1;
  1714. }
  1715. Py_DECREF(encoded);
  1716. if (_Pickler_Write(self, "\n", 1) < 0)
  1717. return -1;
  1718. }
  1719. if (memo_put(self, obj) < 0)
  1720. return -1;
  1721. return 0;
  1722. }
  1723. /* A helper for save_tuple. Push the len elements in tuple t on the stack. */
  1724. static int
  1725. store_tuple_elements(PicklerObject *self, PyObject *t, Py_ssize_t len)
  1726. {
  1727. Py_ssize_t i;
  1728. assert(PyTuple_Size(t) == len);
  1729. for (i = 0; i < len; i++) {
  1730. PyObject *element = PyTuple_GET_ITEM(t, i);
  1731. if (element == NULL)
  1732. return -1;
  1733. if (save(self, element, 0) < 0)
  1734. return -1;
  1735. }
  1736. return 0;
  1737. }
  1738. /* Tuples are ubiquitous in the pickle protocols, so many techniques are
  1739. * used across protocols to minimize the space needed to pickle them.
  1740. * Tuples are also the only builtin immutable type that can be recursive
  1741. * (a tuple can be reached from itself), and that requires some subtle
  1742. * magic so that it works in all cases. IOW, this is a long routine.
  1743. */
  1744. static int
  1745. save_tuple(PicklerObject *self, PyObject *obj)
  1746. {
  1747. Py_ssize_t len, i;
  1748. const char mark_op = MARK;
  1749. const char tuple_op = TUPLE;
  1750. const char pop_op = POP;
  1751. const char pop_mark_op = POP_MARK;
  1752. const char len2opcode[] = {EMPTY_TUPLE, TUPLE1, TUPLE2, TUPLE3};
  1753. if ((len = PyTuple_Size(obj)) < 0)
  1754. return -1;
  1755. if (len == 0) {
  1756. char pdata[2];
  1757. if (self->proto) {
  1758. pdata[0] = EMPTY_TUPLE;
  1759. len = 1;
  1760. }
  1761. else {
  1762. pdata[0] = MARK;
  1763. pdata[1] = TUPLE;
  1764. len = 2;
  1765. }
  1766. if (_Pickler_Write(self, pdata, len) < 0)
  1767. return -1;
  1768. return 0;
  1769. }
  1770. /* The tuple isn't in the memo now. If it shows up there after
  1771. * saving the tuple elements, the tuple must be recursive, in
  1772. * which case we'll pop everything we put on the stack, and fetch
  1773. * its value from the memo.
  1774. */
  1775. if (len <= 3 && self->proto >= 2) {
  1776. /* Use TUPLE{1,2,3} opcodes. */
  1777. if (store_tuple_elements(self, obj, len) < 0)
  1778. return -1;
  1779. if (PyMemoTable_Get(self->memo, obj)) {
  1780. /* pop the len elements */
  1781. for (i = 0; i < len; i++)
  1782. if (_Pickler_Write(self, &pop_op, 1) < 0)
  1783. return -1;
  1784. /* fetch from memo */
  1785. if (memo_get(self, obj) < 0)
  1786. return -1;
  1787. return 0;
  1788. }
  1789. else { /* Not recursive. */
  1790. if (_Pickler_Write(self, len2opcode + len, 1) < 0)
  1791. return -1;
  1792. }
  1793. goto memoize;
  1794. }
  1795. /* proto < 2 and len > 0, or proto >= 2 and len > 3.
  1796. * Generate MARK e1 e2 ... TUPLE
  1797. */
  1798. if (_Pickler_Write(self, &mark_op, 1) < 0)
  1799. return -1;
  1800. if (store_tuple_elements(self, obj, len) < 0)
  1801. return -1;
  1802. if (PyMemoTable_Get(self->memo, obj)) {
  1803. /* pop the stack stuff we pushed */
  1804. if (self->bin) {
  1805. if (_Pickler_Write(self, &pop_mark_op, 1) < 0)
  1806. return -1;
  1807. }
  1808. else {
  1809. /* Note that we pop one more than len, to remove
  1810. * the MARK too.
  1811. */
  1812. for (i = 0; i <= len; i++)
  1813. if (_Pickler_Write(self, &pop_op, 1) < 0)
  1814. return -1;
  1815. }
  1816. /* fetch from memo */
  1817. if (memo_get(self, obj) < 0)
  1818. return -1;
  1819. return 0;
  1820. }
  1821. else { /* Not recursive. */
  1822. if (_Pickler_Write(self, &tuple_op, 1) < 0)
  1823. return -1;
  1824. }
  1825. memoize:
  1826. if (memo_put(self, obj) < 0)
  1827. return -1;
  1828. return 0;
  1829. }
  1830. /* iter is an iterator giving items, and we batch up chunks of
  1831. * MARK item item ... item APPENDS
  1832. * opcode sequences. Calling code should have arranged to first create an
  1833. * empty list, or list-like object, for the APPENDS to operate on.
  1834. * Returns 0 on success, <0 on error.
  1835. */
  1836. static int
  1837. batch_list(PicklerObject *self, PyObject *iter)
  1838. {
  1839. PyObject *obj = NULL;
  1840. PyObject *firstitem = NULL;
  1841. int i, n;
  1842. const char mark_op = MARK;
  1843. const char append_op = APPEND;
  1844. const char appends_op = APPENDS;
  1845. assert(iter != NULL);
  1846. /* XXX: I think this function could be made faster by avoiding the
  1847. iterator interface and fetching objects directly from list using
  1848. PyList_GET_ITEM.
  1849. */
  1850. if (self->proto == 0) {
  1851. /* APPENDS isn't available; do one at a time. */
  1852. for (;;) {
  1853. obj = PyIter_Next(iter);
  1854. if (obj == NULL) {
  1855. if (PyErr_Occurred())
  1856. return -1;
  1857. break;
  1858. }
  1859. i = save(self, obj, 0);
  1860. Py_DECREF(obj);
  1861. if (i < 0)
  1862. return -1;
  1863. if (_Pickler_Write(self, &append_op, 1) < 0)
  1864. return -1;
  1865. }
  1866. return 0;
  1867. }
  1868. /* proto > 0: write in batches of BATCHSIZE. */
  1869. do {
  1870. /* Get first item */
  1871. firstitem = PyIter_Next(iter);
  1872. if (firstitem == NULL) {
  1873. if (PyErr_Occurred())
  1874. goto error;
  1875. /* nothing more to add */
  1876. break;
  1877. }
  1878. /* Try to get a second item */
  1879. obj = PyIter_Next(iter);
  1880. if (obj == NULL) {
  1881. if (PyErr_Occurred())
  1882. goto error;
  1883. /* Only one item to write */
  1884. if (save(self, firstitem, 0) < 0)
  1885. goto error;
  1886. if (_Pickler_Write(self, &append_op, 1) < 0)
  1887. goto error;
  1888. Py_CLEAR(firstitem);
  1889. break;
  1890. }
  1891. /* More than one item to write */
  1892. /* Pump out MARK, items, APPENDS. */
  1893. if (_Pickler_Write(self, &mark_op, 1) < 0)
  1894. goto error;
  1895. if (save(self, firstitem, 0) < 0)
  1896. goto error;
  1897. Py_CLEAR(firstitem);
  1898. n = 1;
  1899. /* Fetch and save up to BATCHSIZE items */
  1900. while (obj) {
  1901. if (save(self, obj, 0) < 0)
  1902. goto error;
  1903. Py_CLEAR(obj);
  1904. n += 1;
  1905. if (n == BATCHSIZE)
  1906. break;
  1907. obj = PyIter_Next(iter);
  1908. if (obj == NULL) {
  1909. if (PyErr_Occurred())
  1910. goto error;
  1911. break;
  1912. }
  1913. }
  1914. if (_Pickler_Write(self, &appends_op, 1) < 0)
  1915. goto error;
  1916. } while (n == BATCHSIZE);
  1917. return 0;
  1918. error:
  1919. Py_XDECREF(firstitem);
  1920. Py_XDECREF(obj);
  1921. return -1;
  1922. }
  1923. /* This is a variant of batch_list() above, specialized for lists (with no
  1924. * support for list subclasses). Like batch_list(), we batch up chunks of
  1925. * MARK item item ... item APPENDS
  1926. * opcode sequences. Calling code should have arranged to first create an
  1927. * empty list, or list-like object, for the APPENDS to operate on.
  1928. * Returns 0 on success, -1 on error.
  1929. *
  1930. * This version is considerably faster than batch_list(), if less general.
  1931. *
  1932. * Note that this only works for protocols > 0.
  1933. */
  1934. static int
  1935. batch_list_exact(PicklerObject *self, PyObject *obj)
  1936. {
  1937. PyObject *item = NULL;
  1938. Py_ssize_t this_batch, total;
  1939. const char append_op = APPEND;
  1940. const char appends_op = APPENDS;
  1941. const char mark_op = MARK;
  1942. assert(obj != NULL);
  1943. assert(self->proto > 0);
  1944. assert(PyList_CheckExact(obj));
  1945. if (PyList_GET_SIZE(obj) == 1) {
  1946. item = PyList_GET_ITEM(obj, 0);
  1947. if (save(self, item, 0) < 0)
  1948. return -1;
  1949. if (_Pickler_Write(self, &append_op, 1) < 0)
  1950. return -1;
  1951. return 0;
  1952. }
  1953. /* Write in batches of BATCHSIZE. */
  1954. total = 0;
  1955. do {
  1956. this_batch = 0;
  1957. if (_Pickler_Write(self, &mark_op, 1) < 0)
  1958. return -1;
  1959. while (total < PyList_GET_SIZE(obj)) {
  1960. item = PyList_GET_ITEM(obj, total);
  1961. if (save(self, item, 0) < 0)
  1962. return -1;
  1963. total++;
  1964. if (++this_batch == BATCHSIZE)
  1965. break;
  1966. }
  1967. if (_Pickler_Write(self, &appends_op, 1) < 0)
  1968. return -1;
  1969. } while (total < PyList_GET_SIZE(obj));
  1970. return 0;
  1971. }
  1972. static int
  1973. save_list(PicklerObject *self, PyObject *obj)
  1974. {
  1975. char header[3];
  1976. Py_ssize_t len;
  1977. int status = 0;
  1978. if (self->fast && !fast_save_enter(self, obj))
  1979. goto error;
  1980. /* Create an empty list. */
  1981. if (self->bin) {
  1982. header[0] = EMPTY_LIST;
  1983. len = 1;
  1984. }
  1985. else {
  1986. header[0] = MARK;
  1987. header[1] = LIST;
  1988. len = 2;
  1989. }
  1990. if (_Pickler_Write(self, header, len) < 0)
  1991. goto error;
  1992. /* Get list length, and bow out early if empty. */
  1993. if ((len = PyList_Size(obj)) < 0)
  1994. goto error;
  1995. if (memo_put(self, obj) < 0)
  1996. goto error;
  1997. if (len != 0) {
  1998. /* Materialize the list elements. */
  1999. if (PyList_CheckExact(obj) && self->proto > 0) {
  2000. if (Py_EnterRecursiveCall(" while pickling an object"))
  2001. goto error;
  2002. status = batch_list_exact(self, obj);
  2003. Py_LeaveRecursiveCall();
  2004. } else {
  2005. PyObject *iter = PyObject_GetIter(obj);
  2006. if (iter == NULL)
  2007. goto error;
  2008. if (Py_EnterRecursiveCall(" while pickling an object")) {
  2009. Py_DECREF(iter);
  2010. goto error;
  2011. }
  2012. status = batch_list(self, iter);
  2013. Py_LeaveRecursiveCall();
  2014. Py_DECREF(iter);
  2015. }
  2016. }
  2017. if (0) {
  2018. error:
  2019. status = -1;
  2020. }
  2021. if (self->fast && !fast_save_leave(self, obj))
  2022. status = -1;
  2023. return status;
  2024. }
  2025. /* iter is an iterator giving (key, value) pairs, and we batch up chunks of
  2026. * MARK key value ... key value SETITEMS
  2027. * opcode sequences. Calling code should have arranged to first create an
  2028. * empty dict, or dict-like object, for the SETITEMS to operate on.
  2029. * Returns 0 on success, <0 on error.
  2030. *
  2031. * This is very much like batch_list(). The difference between saving
  2032. * elements directly, and picking apart two-tuples, is so long-winded at
  2033. * the C level, though, that attempts to combine these routines were too
  2034. * ugly to bear.
  2035. */
  2036. static int
  2037. batch_dict(PicklerObject *self, PyObject *iter)
  2038. {
  2039. PyObject *obj = NULL;
  2040. PyObject *firstitem = NULL;
  2041. int i, n;
  2042. const char mark_op = MARK;
  2043. const char setitem_op = SETITEM;
  2044. const char setitems_op = SETITEMS;
  2045. assert(iter != NULL);
  2046. if (self->proto == 0) {
  2047. /* SETITEMS isn't available; do one at a time. */
  2048. for (;;) {
  2049. obj = PyIter_Next(iter);
  2050. if (obj == NULL) {
  2051. if (PyErr_Occurred())
  2052. return -1;
  2053. break;
  2054. }
  2055. if (!PyTuple_Check(obj) || PyTuple_Size(obj) != 2) {
  2056. PyErr_SetString(PyExc_TypeError, "dict items "
  2057. "iterator must return 2-tuples");
  2058. return -1;
  2059. }
  2060. i = save(self, PyTuple_GET_ITEM(obj, 0), 0);
  2061. if (i >= 0)
  2062. i = save(self, PyTuple_GET_ITEM(obj, 1), 0);
  2063. Py_DECREF(obj);
  2064. if (i < 0)
  2065. return -1;
  2066. if (_Pickler_Write(self, &setitem_op, 1) < 0)
  2067. return -1;
  2068. }
  2069. return 0;
  2070. }
  2071. /* proto > 0: write in batches of BATCHSIZE. */
  2072. do {
  2073. /* Get first item */
  2074. firstitem = PyIter_Next(iter);
  2075. if (firstitem == NULL) {
  2076. if (PyErr_Occurred())
  2077. goto error;
  2078. /* nothing more to add */
  2079. break;
  2080. }
  2081. if (!PyTuple_Check(firstitem) || PyTuple_Size(firstitem) != 2) {
  2082. PyErr_SetString(PyExc_TypeError, "dict items "
  2083. "iterator must return 2-tuples");
  2084. goto error;
  2085. }
  2086. /* Try to get a second item */
  2087. obj = PyIter_Next(iter);
  2088. if (obj == NULL) {
  2089. if (PyErr_Occurred())
  2090. goto error;
  2091. /* Only one item to write */
  2092. if (save(self, PyTuple_GET_ITEM(firstitem, 0), 0) < 0)
  2093. goto error;
  2094. if (save(self, PyTuple_GET_ITEM(firstitem, 1), 0) < 0)
  2095. goto error;
  2096. if (_Pickler_Write(self, &setitem_op, 1) < 0)
  2097. goto error;
  2098. Py_CLEAR(firstitem);
  2099. break;
  2100. }
  2101. /* More than one item to write */
  2102. /* Pump out MARK, items, SETITEMS. */
  2103. if (_Pickler_Write(self, &mark_op, 1) < 0)
  2104. goto error;
  2105. if (save(self, PyTuple_GET_ITEM(firstitem, 0), 0) < 0)
  2106. goto error;
  2107. if (save(self, PyTuple_GET_ITEM(firstitem, 1), 0) < 0)
  2108. goto error;
  2109. Py_CLEAR(firstitem);
  2110. n = 1;
  2111. /* Fetch and save up to BATCHSIZE items */
  2112. while (obj) {
  2113. if (!PyTuple_Check(obj) || PyTuple_Size(obj) != 2) {
  2114. PyErr_SetString(PyExc_TypeError, "dict items "
  2115. "iterator must return 2-tuples");
  2116. goto error;
  2117. }
  2118. if (save(self, PyTuple_GET_ITEM(obj, 0), 0) < 0 ||
  2119. save(self, PyTuple_GET_ITEM(obj, 1), 0) < 0)
  2120. goto error;
  2121. Py_CLEAR(obj);
  2122. n += 1;
  2123. if (n == BATCHSIZE)
  2124. break;
  2125. obj = PyIter_Next(iter);
  2126. if (obj == NULL) {
  2127. if (PyErr_Occurred())
  2128. goto error;
  2129. break;
  2130. }
  2131. }
  2132. if (_Pickler_Write(self, &setitems_op, 1) < 0)
  2133. goto error;
  2134. } while (n == BATCHSIZE);
  2135. return 0;
  2136. error:
  2137. Py_XDECREF(firstitem);
  2138. Py_XDECREF(obj);
  2139. return -1;
  2140. }
  2141. /* This is a variant of batch_dict() above that specializes for dicts, with no
  2142. * support for dict subclasses. Like batch_dict(), we batch up chunks of
  2143. * MARK key value ... key value SETITEMS
  2144. * opcode sequences. Calling code should have arranged to first create an
  2145. * empty dict, or dict-like object, for the SETITEMS to operate on.
  2146. * Returns 0 on success, -1 on error.
  2147. *
  2148. * Note that this currently doesn't work for protocol 0.
  2149. */
  2150. static int
  2151. batch_dict_exact(PicklerObject *self, PyObject *obj)
  2152. {
  2153. PyObject *key = NULL, *value = NULL;
  2154. int i;
  2155. Py_ssize_t dict_size, ppos = 0;
  2156. const char mark_op = MARK;
  2157. const char setitem_op = SETITEM;
  2158. const char setitems_op = SETITEMS;
  2159. assert(obj != NULL);
  2160. assert(self->proto > 0);
  2161. dict_size = PyDict_Size(obj);
  2162. /* Special-case len(d) == 1 to save space. */
  2163. if (dict_size == 1) {
  2164. PyDict_Next(obj, &ppos, &key, &value);
  2165. if (save(self, key, 0) < 0)
  2166. return -1;
  2167. if (save(self, value, 0) < 0)
  2168. return -1;
  2169. if (_Pickler_Write(self, &setitem_op, 1) < 0)
  2170. return -1;
  2171. return 0;
  2172. }
  2173. /* Write in batches of BATCHSIZE. */
  2174. do {
  2175. i = 0;
  2176. if (_Pickler_Write(self, &mark_op, 1) < 0)
  2177. return -1;
  2178. while (PyDict_Next(obj, &ppos, &key, &value)) {
  2179. if (save(self, key, 0) < 0)
  2180. return -1;
  2181. if (save(self, value, 0) < 0)
  2182. return -1;
  2183. if (++i == BATCHSIZE)
  2184. break;
  2185. }
  2186. if (_Pickler_Write(self, &setitems_op, 1) < 0)
  2187. return -1;
  2188. if (PyDict_Size(obj) != dict_size) {
  2189. PyErr_Format(
  2190. PyExc_RuntimeError,
  2191. "dictionary changed size during iteration");
  2192. return -1;
  2193. }
  2194. } while (i == BATCHSIZE);
  2195. return 0;
  2196. }
  2197. static int
  2198. save_dict(PicklerObject *self, PyObject *obj)
  2199. {
  2200. PyObject *items, *iter;
  2201. char header[3];
  2202. Py_ssize_t len;
  2203. int status = 0;
  2204. if (self->fast && !fast_save_enter(self, obj))
  2205. goto error;
  2206. /* Create an empty dict. */
  2207. if (self->bin) {
  2208. header[0] = EMPTY_DICT;
  2209. len = 1;
  2210. }
  2211. else {
  2212. header[0] = MARK;
  2213. header[1] = DICT;
  2214. len = 2;
  2215. }
  2216. if (_Pickler_Write(self, header, len) < 0)
  2217. goto error;
  2218. /* Get dict size, and bow out early if empty. */
  2219. if ((len = PyDict_Size(obj)) < 0)
  2220. goto error;
  2221. if (memo_put(self, obj) < 0)
  2222. goto error;
  2223. if (len != 0) {
  2224. /* Save the dict items. */
  2225. if (PyDict_CheckExact(obj) && self->proto > 0) {
  2226. /* We can take certain shortcuts if we know this is a dict and
  2227. not a dict subclass. */
  2228. if (Py_EnterRecursiveCall(" while pickling an object"))
  2229. goto error;
  2230. status = batch_dict_exact(self, obj);
  2231. Py_LeaveRecursiveCall();
  2232. } else {
  2233. _Py_IDENTIFIER(items);
  2234. items = _PyObject_CallMethodId(obj, &PyId_items, "()");
  2235. if (items == NULL)
  2236. goto error;
  2237. iter = PyObject_GetIter(items);
  2238. Py_DECREF(items);
  2239. if (iter == NULL)
  2240. goto error;
  2241. if (Py_EnterRecursiveCall(" while pickling an object")) {
  2242. Py_DECREF(iter);
  2243. goto error;
  2244. }
  2245. status = batch_dict(self, iter);
  2246. Py_LeaveRecursiveCall();
  2247. Py_DECREF(iter);
  2248. }
  2249. }
  2250. if (0) {
  2251. error:
  2252. status = -1;
  2253. }
  2254. if (self->fast && !fast_save_leave(self, obj))
  2255. status = -1;
  2256. return status;
  2257. }
  2258. static int
  2259. save_global(PicklerObject *self, PyObject *obj, PyObject *name)
  2260. {
  2261. static PyObject *name_str = NULL;
  2262. PyObject *global_name = NULL;
  2263. PyObject *module_name = NULL;
  2264. PyObject *module = NULL;
  2265. PyObject *cls;
  2266. int status = 0;
  2267. const char global_op = GLOBAL;
  2268. if (name_str == NULL) {
  2269. name_str = PyUnicode_InternFromString("__name__");
  2270. if (name_str == NULL)
  2271. goto error;
  2272. }
  2273. if (name) {
  2274. global_name = name;
  2275. Py_INCREF(global_name);
  2276. }
  2277. else {
  2278. global_name = PyObject_GetAttr(obj, name_str);
  2279. if (global_name == NULL)
  2280. goto error;
  2281. }
  2282. module_name = whichmodule(obj, global_name);
  2283. if (module_name == NULL)
  2284. goto error;
  2285. /* XXX: Change to use the import C API directly with level=0 to disallow
  2286. relative imports.
  2287. XXX: PyImport_ImportModuleLevel could be used. However, this bypasses
  2288. builtins.__import__. Therefore, _pickle, unlike pickle.py, will ignore
  2289. custom import functions (IMHO, this would be a nice security
  2290. feature). The import C API would need to be extended to support the
  2291. extra parameters of __import__ to fix that. */
  2292. module = PyImport_Import(module_name);
  2293. if (module == NULL) {
  2294. PyErr_Format(PicklingError,
  2295. "Can't pickle %R: import of module %R failed",
  2296. obj, module_name);
  2297. goto error;
  2298. }
  2299. cls = PyObject_GetAttr(module, global_name);
  2300. if (cls == NULL) {
  2301. PyErr_Format(PicklingError,
  2302. "Can't pickle %R: attribute lookup %S.%S failed",
  2303. obj, module_name, global_name);
  2304. goto error;
  2305. }
  2306. if (cls != obj) {
  2307. Py_DECREF(cls);
  2308. PyErr_Format(PicklingError,
  2309. "Can't pickle %R: it's not the same object as %S.%S",
  2310. obj, module_name, global_name);
  2311. goto error;
  2312. }
  2313. Py_DECREF(cls);
  2314. if (self->proto >= 2) {
  2315. /* See whether this is in the extension registry, and if
  2316. * so generate an EXT opcode.
  2317. */
  2318. PyObject *code_obj; /* extension code as Python object */
  2319. long code; /* extension code as C value */
  2320. char pdata[5];
  2321. Py_ssize_t n;
  2322. PyTuple_SET_ITEM(two_tuple, 0, module_name);
  2323. PyTuple_SET_ITEM(two_tuple, 1, global_name);
  2324. code_obj = PyDict_GetItem(extension_registry, two_tuple);
  2325. /* The object is not registered in the extension registry.
  2326. This is the most likely code path. */
  2327. if (code_obj == NULL)
  2328. goto gen_global;
  2329. /* XXX: pickle.py doesn't check neither the type, nor the range
  2330. of the value returned by the extension_registry. It should for
  2331. consistency. */
  2332. /* Verify code_obj has the right type and value. */
  2333. if (!PyLong_Check(code_obj)) {
  2334. PyErr_Format(PicklingError,
  2335. "Can't pickle %R: extension code %R isn't an integer",
  2336. obj, code_obj);
  2337. goto error;
  2338. }
  2339. code = PyLong_AS_LONG(code_obj);
  2340. if (code <= 0 || code > 0x7fffffffL) {
  2341. if (!PyErr_Occurred())
  2342. PyErr_Format(PicklingError,
  2343. "Can't pickle %R: extension code %ld is out of range",
  2344. obj, code);
  2345. goto error;
  2346. }
  2347. /* Generate an EXT opcode. */
  2348. if (code <= 0xff) {
  2349. pdata[0] = EXT1;
  2350. pdata[1] = (unsigned char)code;
  2351. n = 2;
  2352. }
  2353. else if (code <= 0xffff) {
  2354. pdata[0] = EXT2;
  2355. pdata[1] = (unsigned char)(code & 0xff);
  2356. pdata[2] = (unsigned char)((code >> 8) & 0xff);
  2357. n = 3;
  2358. }
  2359. else {
  2360. pdata[0] = EXT4;
  2361. pdata[1] = (unsigned char)(code & 0xff);
  2362. pdata[2] = (unsigned char)((code >> 8) & 0xff);
  2363. pdata[3] = (unsigned char)((code >> 16) & 0xff);
  2364. pdata[4] = (unsigned char)((code >> 24) & 0xff);
  2365. n = 5;
  2366. }
  2367. if (_Pickler_Write(self, pdata, n) < 0)
  2368. goto error;
  2369. }
  2370. else {
  2371. /* Generate a normal global opcode if we are using a pickle
  2372. protocol <= 2, or if the object is not registered in the
  2373. extension registry. */
  2374. PyObject *encoded;
  2375. PyObject *(*unicode_encoder)(PyObject *);
  2376. gen_global:
  2377. if (_Pickler_Write(self, &global_op, 1) < 0)
  2378. goto error;
  2379. /* Since Python 3.0 now supports non-ASCII identifiers, we encode both
  2380. the module name and the global name using UTF-8. We do so only when
  2381. we are using the pickle protocol newer than version 3. This is to
  2382. ensure compatibility with older Unpickler running on Python 2.x. */
  2383. if (self->proto >= 3) {
  2384. unicode_encoder = PyUnicode_AsUTF8String;
  2385. }
  2386. else {
  2387. unicode_encoder = PyUnicode_AsASCIIString;
  2388. }
  2389. /* For protocol < 3 and if the user didn't request against doing so,
  2390. we convert module names to the old 2.x module names. */
  2391. if (self->fix_imports) {
  2392. PyObject *key;
  2393. PyObject *item;
  2394. key = PyTuple_Pack(2, module_name, global_name);
  2395. if (key == NULL)
  2396. goto error;
  2397. item = PyDict_GetItemWithError(name_mapping_3to2, key);
  2398. Py_DECREF(key);
  2399. if (item) {
  2400. if (!PyTuple_Check(item) || PyTuple_GET_SIZE(item) != 2) {
  2401. PyErr_Format(PyExc_RuntimeError,
  2402. "_compat_pickle.REVERSE_NAME_MAPPING values "
  2403. "should be 2-tuples, not %.200s",
  2404. Py_TYPE(item)->tp_name);
  2405. goto error;
  2406. }
  2407. Py_CLEAR(module_name);
  2408. Py_CLEAR(global_name);
  2409. module_name = PyTuple_GET_ITEM(item, 0);
  2410. global_name = PyTuple_GET_ITEM(item, 1);
  2411. if (!PyUnicode_Check(module_name) ||
  2412. !PyUnicode_Check(global_name)) {
  2413. PyErr_Format(PyExc_RuntimeError,
  2414. "_compat_pickle.REVERSE_NAME_MAPPING values "
  2415. "should be pairs of str, not (%.200s, %.200s)",
  2416. Py_TYPE(module_name)->tp_name,
  2417. Py_TYPE(global_name)->tp_name);
  2418. goto error;
  2419. }
  2420. Py_INCREF(module_name);
  2421. Py_INCREF(global_name);
  2422. }
  2423. else if (PyErr_Occurred()) {
  2424. goto error;
  2425. }
  2426. item = PyDict_GetItemWithError(import_mapping_3to2, module_name);
  2427. if (item) {
  2428. if (!PyUnicode_Check(item)) {
  2429. PyErr_Format(PyExc_RuntimeError,
  2430. "_compat_pickle.REVERSE_IMPORT_MAPPING values "
  2431. "should be strings, not %.200s",
  2432. Py_TYPE(item)->tp_name);
  2433. goto error;
  2434. }
  2435. Py_CLEAR(module_name);
  2436. module_name = item;
  2437. Py_INCREF(module_name);
  2438. }
  2439. else if (PyErr_Occurred()) {
  2440. goto error;
  2441. }
  2442. }
  2443. /* Save the name of the module. */
  2444. encoded = unicode_encoder(module_name);
  2445. if (encoded == NULL) {
  2446. if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError))
  2447. PyErr_Format(PicklingError,
  2448. "can't pickle module identifier '%S' using "
  2449. "pickle protocol %i", module_name, self->proto);
  2450. goto error;
  2451. }
  2452. if (_Pickler_Write(self, PyBytes_AS_STRING(encoded),
  2453. PyBytes_GET_SIZE(encoded)) < 0) {
  2454. Py_DECREF(encoded);
  2455. goto error;
  2456. }
  2457. Py_DECREF(encoded);
  2458. if(_Pickler_Write(self, "\n", 1) < 0)
  2459. goto error;
  2460. /* Save the name of the module. */
  2461. encoded = unicode_encoder(global_name);
  2462. if (encoded == NULL) {
  2463. if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError))
  2464. PyErr_Format(PicklingError,
  2465. "can't pickle global identifier '%S' using "
  2466. "pickle protocol %i", global_name, self->proto);
  2467. goto error;
  2468. }
  2469. if (_Pickler_Write(self, PyBytes_AS_STRING(encoded),
  2470. PyBytes_GET_SIZE(encoded)) < 0) {
  2471. Py_DECREF(encoded);
  2472. goto error;
  2473. }
  2474. Py_DECREF(encoded);
  2475. if(_Pickler_Write(self, "\n", 1) < 0)
  2476. goto error;
  2477. /* Memoize the object. */
  2478. if (memo_put(self, obj) < 0)
  2479. goto error;
  2480. }
  2481. if (0) {
  2482. error:
  2483. status = -1;
  2484. }
  2485. Py_XDECREF(module_name);
  2486. Py_XDECREF(global_name);
  2487. Py_XDECREF(module);
  2488. return status;
  2489. }
  2490. static int
  2491. save_ellipsis(PicklerObject *self, PyObject *obj)
  2492. {
  2493. PyObject *str = PyUnicode_FromString("Ellipsis");
  2494. int res;
  2495. if (str == NULL)
  2496. return -1;
  2497. res = save_global(self, Py_Ellipsis, str);
  2498. Py_DECREF(str);
  2499. return res;
  2500. }
  2501. static int
  2502. save_notimplemented(PicklerObject *self, PyObject *obj)
  2503. {
  2504. PyObject *str = PyUnicode_FromString("NotImplemented");
  2505. int res;
  2506. if (str == NULL)
  2507. return -1;
  2508. res = save_global(self, Py_NotImplemented, str);
  2509. Py_DECREF(str);
  2510. return res;
  2511. }
  2512. static int
  2513. save_pers(PicklerObject *self, PyObject *obj, PyObject *func)
  2514. {
  2515. PyObject *pid = NULL;
  2516. int status = 0;
  2517. const char persid_op = PERSID;
  2518. const char binpersid_op = BINPERSID;
  2519. Py_INCREF(obj);
  2520. pid = _Pickler_FastCall(self, func, obj);
  2521. if (pid == NULL)
  2522. return -1;
  2523. if (pid != Py_None) {
  2524. if (self->bin) {
  2525. if (save(self, pid, 1) < 0 ||
  2526. _Pickler_Write(self, &binpersid_op, 1) < 0)
  2527. goto error;
  2528. }
  2529. else {
  2530. PyObject *pid_str = NULL;
  2531. char *pid_ascii_bytes;
  2532. Py_ssize_t size;
  2533. pid_str = PyObject_Str(pid);
  2534. if (pid_str == NULL)
  2535. goto error;
  2536. /* XXX: Should it check whether the persistent id only contains
  2537. ASCII characters? And what if the pid contains embedded
  2538. newlines? */
  2539. pid_ascii_bytes = _PyUnicode_AsStringAndSize(pid_str, &size);
  2540. Py_DECREF(pid_str);
  2541. if (pid_ascii_bytes == NULL)
  2542. goto error;
  2543. if (_Pickler_Write(self, &persid_op, 1) < 0 ||
  2544. _Pickler_Write(self, pid_ascii_bytes, size) < 0 ||
  2545. _Pickler_Write(self, "\n", 1) < 0)
  2546. goto error;
  2547. }
  2548. status = 1;
  2549. }
  2550. if (0) {
  2551. error:
  2552. status = -1;
  2553. }
  2554. Py_XDECREF(pid);
  2555. return status;
  2556. }
  2557. static PyObject *
  2558. get_class(PyObject *obj)
  2559. {
  2560. PyObject *cls;
  2561. static PyObject *str_class;
  2562. if (str_class == NULL) {
  2563. str_class = PyUnicode_InternFromString("__class__");
  2564. if (str_class == NULL)
  2565. return NULL;
  2566. }
  2567. cls = PyObject_GetAttr(obj, str_class);
  2568. if (cls == NULL) {
  2569. if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
  2570. PyErr_Clear();
  2571. cls = (PyObject *) Py_TYPE(obj);
  2572. Py_INCREF(cls);
  2573. }
  2574. }
  2575. return cls;
  2576. }
  2577. /* We're saving obj, and args is the 2-thru-5 tuple returned by the
  2578. * appropriate __reduce__ method for obj.
  2579. */
  2580. static int
  2581. save_reduce(PicklerObject *self, PyObject *args, PyObject *obj)
  2582. {
  2583. PyObject *callable;
  2584. PyObject *argtup;
  2585. PyObject *state = NULL;
  2586. PyObject *listitems = Py_None;
  2587. PyObject *dictitems = Py_None;
  2588. Py_ssize_t size;
  2589. int use_newobj = self->proto >= 2;
  2590. const char reduce_op = REDUCE;
  2591. const char build_op = BUILD;
  2592. const char newobj_op = NEWOBJ;
  2593. size = PyTuple_Size(args);
  2594. if (size < 2 || size > 5) {
  2595. PyErr_SetString(PicklingError, "tuple returned by "
  2596. "__reduce__ must contain 2 through 5 elements");
  2597. return -1;
  2598. }
  2599. if (!PyArg_UnpackTuple(args, "save_reduce", 2, 5,
  2600. &callable, &argtup, &state, &listitems, &dictitems))
  2601. return -1;
  2602. if (!PyCallable_Check(callable)) {
  2603. PyErr_SetString(PicklingError, "first item of the tuple "
  2604. "returned by __reduce__ must be callable");
  2605. return -1;
  2606. }
  2607. if (!PyTuple_Check(argtup)) {
  2608. PyErr_SetString(PicklingError, "second item of the tuple "
  2609. "returned by __reduce__ must be a tuple");
  2610. return -1;
  2611. }
  2612. if (state == Py_None)
  2613. state = NULL;
  2614. if (listitems == Py_None)
  2615. listitems = NULL;
  2616. else if (!PyIter_Check(listitems)) {
  2617. PyErr_Format(PicklingError, "fourth element of the tuple "
  2618. "returned by __reduce__ must be an iterator, not %s",
  2619. Py_TYPE(listitems)->tp_name);
  2620. return -1;
  2621. }
  2622. if (dictitems == Py_None)
  2623. dictitems = NULL;
  2624. else if (!PyIter_Check(dictitems)) {
  2625. PyErr_Format(PicklingError, "fifth element of the tuple "
  2626. "returned by __reduce__ must be an iterator, not %s",
  2627. Py_TYPE(dictitems)->tp_name);
  2628. return -1;
  2629. }
  2630. /* Protocol 2 special case: if callable's name is __newobj__, use
  2631. NEWOBJ. */
  2632. if (use_newobj) {
  2633. static PyObject *newobj_str = NULL, *name_str = NULL;
  2634. PyObject *name;
  2635. if (newobj_str == NULL) {
  2636. newobj_str = PyUnicode_InternFromString("__newobj__");
  2637. name_str = PyUnicode_InternFromString("__name__");
  2638. if (newobj_str == NULL || name_str == NULL)
  2639. return -1;
  2640. }
  2641. name = PyObject_GetAttr(callable, name_str);
  2642. if (name == NULL) {
  2643. if (PyErr_ExceptionMatches(PyExc_AttributeError))
  2644. PyErr_Clear();
  2645. else
  2646. return -1;
  2647. use_newobj = 0;
  2648. }
  2649. else {
  2650. use_newobj = PyUnicode_Check(name) &&
  2651. PyUnicode_Compare(name, newobj_str) == 0;
  2652. Py_DECREF(name);
  2653. }
  2654. }
  2655. if (use_newobj) {
  2656. PyObject *cls;
  2657. PyObject *newargtup;
  2658. PyObject *obj_class;
  2659. int p;
  2660. /* Sanity checks. */
  2661. if (Py_SIZE(argtup) < 1) {
  2662. PyErr_SetString(PicklingError, "__newobj__ arglist is empty");
  2663. return -1;
  2664. }
  2665. cls = PyTuple_GET_ITEM(argtup, 0);
  2666. if (!PyType_Check(cls)) {
  2667. PyErr_SetString(PicklingError, "args[0] from "
  2668. "__newobj__ args is not a type");
  2669. return -1;
  2670. }
  2671. if (obj != NULL) {
  2672. obj_class = get_class(obj);
  2673. p = obj_class != cls; /* true iff a problem */
  2674. Py_DECREF(obj_class);
  2675. if (p) {
  2676. PyErr_SetString(PicklingError, "args[0] from "
  2677. "__newobj__ args has the wrong class");
  2678. return -1;
  2679. }
  2680. }
  2681. /* XXX: These calls save() are prone to infinite recursion. Imagine
  2682. what happen if the value returned by the __reduce__() method of
  2683. some extension type contains another object of the same type. Ouch!
  2684. Here is a quick example, that I ran into, to illustrate what I
  2685. mean:
  2686. >>> import pickle, copyreg
  2687. >>> copyreg.dispatch_table.pop(complex)
  2688. >>> pickle.dumps(1+2j)
  2689. Traceback (most recent call last):
  2690. ...
  2691. RuntimeError: maximum recursion depth exceeded
  2692. Removing the complex class from copyreg.dispatch_table made the
  2693. __reduce_ex__() method emit another complex object:
  2694. >>> (1+1j).__reduce_ex__(2)
  2695. (<function __newobj__ at 0xb7b71c3c>,
  2696. (<class 'complex'>, (1+1j)), None, None, None)
  2697. Thus when save() was called on newargstup (the 2nd item) recursion
  2698. ensued. Of course, the bug was in the complex class which had a
  2699. broken __getnewargs__() that emitted another complex object. But,
  2700. the point, here, is it is quite easy to end up with a broken reduce
  2701. function. */
  2702. /* Save the class and its __new__ arguments. */
  2703. if (save(self, cls, 0) < 0)
  2704. return -1;
  2705. newargtup = PyTuple_GetSlice(argtup, 1, Py_SIZE(argtup));
  2706. if (newargtup == NULL)
  2707. return -1;
  2708. p = save(self, newargtup, 0);
  2709. Py_DECREF(newargtup);
  2710. if (p < 0)
  2711. return -1;
  2712. /* Add NEWOBJ opcode. */
  2713. if (_Pickler_Write(self, &newobj_op, 1) < 0)
  2714. return -1;
  2715. }
  2716. else { /* Not using NEWOBJ. */
  2717. if (save(self, callable, 0) < 0 ||
  2718. save(self, argtup, 0) < 0 ||
  2719. _Pickler_Write(self, &reduce_op, 1) < 0)
  2720. return -1;
  2721. }
  2722. /* obj can be NULL when save_reduce() is used directly. A NULL obj means
  2723. the caller do not want to memoize the object. Not particularly useful,
  2724. but that is to mimic the behavior save_reduce() in pickle.py when
  2725. obj is None. */
  2726. if (obj && memo_put(self, obj) < 0)
  2727. return -1;
  2728. if (listitems && batch_list(self, listitems) < 0)
  2729. return -1;
  2730. if (dictitems && batch_dict(self, dictitems) < 0)
  2731. return -1;
  2732. if (state) {
  2733. if (save(self, state, 0) < 0 ||
  2734. _Pickler_Write(self, &build_op, 1) < 0)
  2735. return -1;
  2736. }
  2737. return 0;
  2738. }
  2739. static int
  2740. save(PicklerObject *self, PyObject *obj, int pers_save)
  2741. {
  2742. PyTypeObject *type;
  2743. PyObject *reduce_func = NULL;
  2744. PyObject *reduce_value = NULL;
  2745. int status = 0;
  2746. if (Py_EnterRecursiveCall(" while pickling an object"))
  2747. return -1;
  2748. /* The extra pers_save argument is necessary to avoid calling save_pers()
  2749. on its returned object. */
  2750. if (!pers_save && self->pers_func) {
  2751. /* save_pers() returns:
  2752. -1 to signal an error;
  2753. 0 if it did nothing successfully;
  2754. 1 if a persistent id was saved.
  2755. */
  2756. if ((status = save_pers(self, obj, self->pers_func)) != 0)
  2757. goto done;
  2758. }
  2759. type = Py_TYPE(obj);
  2760. /* The old cPickle had an optimization that used switch-case statement
  2761. dispatching on the first letter of the type name. This has was removed
  2762. since benchmarks shown that this optimization was actually slowing
  2763. things down. */
  2764. /* Atom types; these aren't memoized, so don't check the memo. */
  2765. if (obj == Py_None) {
  2766. status = save_none(self, obj);
  2767. goto done;
  2768. }
  2769. else if (obj == Py_Ellipsis) {
  2770. status = save_ellipsis(self, obj);
  2771. goto done;
  2772. }
  2773. else if (obj == Py_NotImplemented) {
  2774. status = save_notimplemented(self, obj);
  2775. goto done;
  2776. }
  2777. else if (obj == Py_False || obj == Py_True) {
  2778. status = save_bool(self, obj);
  2779. goto done;
  2780. }
  2781. else if (type == &PyLong_Type) {
  2782. status = save_long(self, obj);
  2783. goto done;
  2784. }
  2785. else if (type == &PyFloat_Type) {
  2786. status = save_float(self, obj);
  2787. goto done;
  2788. }
  2789. /* Check the memo to see if it has the object. If so, generate
  2790. a GET (or BINGET) opcode, instead of pickling the object
  2791. once again. */
  2792. if (PyMemoTable_Get(self->memo, obj)) {
  2793. if (memo_get(self, obj) < 0)
  2794. goto error;
  2795. goto done;
  2796. }
  2797. if (type == &PyBytes_Type) {
  2798. status = save_bytes(self, obj);
  2799. goto done;
  2800. }
  2801. else if (type == &PyUnicode_Type) {
  2802. status = save_unicode(self, obj);
  2803. goto done;
  2804. }
  2805. else if (type == &PyDict_Type) {
  2806. status = save_dict(self, obj);
  2807. goto done;
  2808. }
  2809. else if (type == &PyList_Type) {
  2810. status = save_list(self, obj);
  2811. goto done;
  2812. }
  2813. else if (type == &PyTuple_Type) {
  2814. status = save_tuple(self, obj);
  2815. goto done;
  2816. }
  2817. else if (type == &PyType_Type) {
  2818. status = save_global(self, obj, NULL);
  2819. goto done;
  2820. }
  2821. else if (type == &PyFunction_Type) {
  2822. status = save_global(self, obj, NULL);
  2823. if (status < 0 && PyErr_ExceptionMatches(PickleError)) {
  2824. /* fall back to reduce */
  2825. PyErr_Clear();
  2826. }
  2827. else {
  2828. goto done;
  2829. }
  2830. }
  2831. else if (type == &PyCFunction_Type) {
  2832. status = save_global(self, obj, NULL);
  2833. goto done;
  2834. }
  2835. /* XXX: This part needs some unit tests. */
  2836. /* Get a reduction callable, and call it. This may come from
  2837. * self.dispatch_table, copyreg.dispatch_table, the object's
  2838. * __reduce_ex__ method, or the object's __reduce__ method.
  2839. */
  2840. if (self->dispatch_table == NULL) {
  2841. reduce_func = PyDict_GetItem(dispatch_table, (PyObject *)type);
  2842. /* PyDict_GetItem() unlike PyObject_GetItem() and
  2843. PyObject_GetAttr() returns a borrowed ref */
  2844. Py_XINCREF(reduce_func);
  2845. } else {
  2846. reduce_func = PyObject_GetItem(self->dispatch_table, (PyObject *)type);
  2847. if (reduce_func == NULL) {
  2848. if (PyErr_ExceptionMatches(PyExc_KeyError))
  2849. PyErr_Clear();
  2850. else
  2851. goto error;
  2852. }
  2853. }
  2854. if (reduce_func != NULL) {
  2855. Py_INCREF(obj);
  2856. reduce_value = _Pickler_FastCall(self, reduce_func, obj);
  2857. }
  2858. else if (PyType_IsSubtype(type, &PyType_Type)) {
  2859. status = save_global(self, obj, NULL);
  2860. goto done;
  2861. }
  2862. else {
  2863. static PyObject *reduce_str = NULL;
  2864. static PyObject *reduce_ex_str = NULL;
  2865. /* Cache the name of the reduce methods. */
  2866. if (reduce_str == NULL) {
  2867. reduce_str = PyUnicode_InternFromString("__reduce__");
  2868. if (reduce_str == NULL)
  2869. goto error;
  2870. reduce_ex_str = PyUnicode_InternFromString("__reduce_ex__");
  2871. if (reduce_ex_str == NULL)
  2872. goto error;
  2873. }
  2874. /* XXX: If the __reduce__ method is defined, __reduce_ex__ is
  2875. automatically defined as __reduce__. While this is convenient, this
  2876. make it impossible to know which method was actually called. Of
  2877. course, this is not a big deal. But still, it would be nice to let
  2878. the user know which method was called when something go
  2879. wrong. Incidentally, this means if __reduce_ex__ is not defined, we
  2880. don't actually have to check for a __reduce__ method. */
  2881. /* Check for a __reduce_ex__ method. */
  2882. reduce_func = PyObject_GetAttr(obj, reduce_ex_str);
  2883. if (reduce_func != NULL) {
  2884. PyObject *proto;
  2885. proto = PyLong_FromLong(self->proto);
  2886. if (proto != NULL) {
  2887. reduce_value = _Pickler_FastCall(self, reduce_func, proto);
  2888. }
  2889. }
  2890. else {
  2891. if (PyErr_ExceptionMatches(PyExc_AttributeError))
  2892. PyErr_Clear();
  2893. else
  2894. goto error;
  2895. /* Check for a __reduce__ method. */
  2896. reduce_func = PyObject_GetAttr(obj, reduce_str);
  2897. if (reduce_func != NULL) {
  2898. reduce_value = PyObject_Call(reduce_func, empty_tuple, NULL);
  2899. }
  2900. else {
  2901. PyErr_Format(PicklingError, "can't pickle '%.200s' object: %R",
  2902. type->tp_name, obj);
  2903. goto error;
  2904. }
  2905. }
  2906. }
  2907. if (reduce_value == NULL)
  2908. goto error;
  2909. if (PyUnicode_Check(reduce_value)) {
  2910. status = save_global(self, obj, reduce_value);
  2911. goto done;
  2912. }
  2913. if (!PyTuple_Check(reduce_value)) {
  2914. PyErr_SetString(PicklingError,
  2915. "__reduce__ must return a string or tuple");
  2916. goto error;
  2917. }
  2918. status = save_reduce(self, reduce_value, obj);
  2919. if (0) {
  2920. error:
  2921. status = -1;
  2922. }
  2923. done:
  2924. Py_LeaveRecursiveCall();
  2925. Py_XDECREF(reduce_func);
  2926. Py_XDECREF(reduce_value);
  2927. return status;
  2928. }
  2929. static int
  2930. dump(PicklerObject *self, PyObject *obj)
  2931. {
  2932. const char stop_op = STOP;
  2933. if (self->proto >= 2) {
  2934. char header[2];
  2935. header[0] = PROTO;
  2936. assert(self->proto >= 0 && self->proto < 256);
  2937. header[1] = (unsigned char)self->proto;
  2938. if (_Pickler_Write(self, header, 2) < 0)
  2939. return -1;
  2940. }
  2941. if (save(self, obj, 0) < 0 ||
  2942. _Pickler_Write(self, &stop_op, 1) < 0)
  2943. return -1;
  2944. return 0;
  2945. }
  2946. PyDoc_STRVAR(Pickler_clear_memo_doc,
  2947. "clear_memo() -> None. Clears the pickler's \"memo\"."
  2948. "\n"
  2949. "The memo is the data structure that remembers which objects the\n"
  2950. "pickler has already seen, so that shared or recursive objects are\n"
  2951. "pickled by reference and not by value. This method is useful when\n"
  2952. "re-using picklers.");
  2953. static PyObject *
  2954. Pickler_clear_memo(PicklerObject *self)
  2955. {
  2956. if (self->memo)
  2957. PyMemoTable_Clear(self->memo);
  2958. Py_RETURN_NONE;
  2959. }
  2960. PyDoc_STRVAR(Pickler_dump_doc,
  2961. "dump(obj) -> None. Write a pickled representation of obj to the open file.");
  2962. static PyObject *
  2963. Pickler_dump(PicklerObject *self, PyObject *args)
  2964. {
  2965. PyObject *obj;
  2966. /* Check whether the Pickler was initialized correctly (issue3664).
  2967. Developers often forget to call __init__() in their subclasses, which
  2968. would trigger a segfault without this check. */
  2969. if (self->write == NULL) {
  2970. PyErr_Format(PicklingError,
  2971. "Pickler.__init__() was not called by %s.__init__()",
  2972. Py_TYPE(self)->tp_name);
  2973. return NULL;
  2974. }
  2975. if (!PyArg_ParseTuple(args, "O:dump", &obj))
  2976. return NULL;
  2977. if (_Pickler_ClearBuffer(self) < 0)
  2978. return NULL;
  2979. if (dump(self, obj) < 0)
  2980. return NULL;
  2981. if (_Pickler_FlushToFile(self) < 0)
  2982. return NULL;
  2983. Py_RETURN_NONE;
  2984. }
  2985. static struct PyMethodDef Pickler_methods[] = {
  2986. {"dump", (PyCFunction)Pickler_dump, METH_VARARGS,
  2987. Pickler_dump_doc},
  2988. {"clear_memo", (PyCFunction)Pickler_clear_memo, METH_NOARGS,
  2989. Pickler_clear_memo_doc},
  2990. {NULL, NULL} /* sentinel */
  2991. };
  2992. static void
  2993. Pickler_dealloc(PicklerObject *self)
  2994. {
  2995. PyObject_GC_UnTrack(self);
  2996. Py_XDECREF(self->output_buffer);
  2997. Py_XDECREF(self->write);
  2998. Py_XDECREF(self->pers_func);
  2999. Py_XDECREF(self->dispatch_table);
  3000. Py_XDECREF(self->arg);
  3001. Py_XDECREF(self->fast_memo);
  3002. PyMemoTable_Del(self->memo);
  3003. Py_TYPE(self)->tp_free((PyObject *)self);
  3004. }
  3005. static int
  3006. Pickler_traverse(PicklerObject *self, visitproc visit, void *arg)
  3007. {
  3008. Py_VISIT(self->write);
  3009. Py_VISIT(self->pers_func);
  3010. Py_VISIT(self->dispatch_table);
  3011. Py_VISIT(self->arg);
  3012. Py_VISIT(self->fast_memo);
  3013. return 0;
  3014. }
  3015. static int
  3016. Pickler_clear(PicklerObject *self)
  3017. {
  3018. Py_CLEAR(self->output_buffer);
  3019. Py_CLEAR(self->write);
  3020. Py_CLEAR(self->pers_func);
  3021. Py_CLEAR(self->dispatch_table);
  3022. Py_CLEAR(self->arg);
  3023. Py_CLEAR(self->fast_memo);
  3024. if (self->memo != NULL) {
  3025. PyMemoTable *memo = self->memo;
  3026. self->memo = NULL;
  3027. PyMemoTable_Del(memo);
  3028. }
  3029. return 0;
  3030. }
  3031. PyDoc_STRVAR(Pickler_doc,
  3032. "Pickler(file, protocol=None)"
  3033. "\n"
  3034. "This takes a binary file for writing a pickle data stream.\n"
  3035. "\n"
  3036. "The optional protocol argument tells the pickler to use the\n"
  3037. "given protocol; supported protocols are 0, 1, 2, 3. The default\n"
  3038. "protocol is 3; a backward-incompatible protocol designed for\n"
  3039. "Python 3.0.\n"
  3040. "\n"
  3041. "Specifying a negative protocol version selects the highest\n"
  3042. "protocol version supported. The higher the protocol used, the\n"
  3043. "more recent the version of Python needed to read the pickle\n"
  3044. "produced.\n"
  3045. "\n"
  3046. "The file argument must have a write() method that accepts a single\n"
  3047. "bytes argument. It can thus be a file object opened for binary\n"
  3048. "writing, a io.BytesIO instance, or any other custom object that\n"
  3049. "meets this interface.\n"
  3050. "\n"
  3051. "If fix_imports is True and protocol is less than 3, pickle will try to\n"
  3052. "map the new Python 3.x names to the old module names used in Python\n"
  3053. "2.x, so that the pickle data stream is readable with Python 2.x.\n");
  3054. static int
  3055. Pickler_init(PicklerObject *self, PyObject *args, PyObject *kwds)
  3056. {
  3057. static char *kwlist[] = {"file", "protocol", "fix_imports", 0};
  3058. PyObject *file;
  3059. PyObject *proto_obj = NULL;
  3060. PyObject *fix_imports = Py_True;
  3061. _Py_IDENTIFIER(persistent_id);
  3062. _Py_IDENTIFIER(dispatch_table);
  3063. if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OO:Pickler",
  3064. kwlist, &file, &proto_obj, &fix_imports))
  3065. return -1;
  3066. /* In case of multiple __init__() calls, clear previous content. */
  3067. if (self->write != NULL)
  3068. (void)Pickler_clear(self);
  3069. if (_Pickler_SetProtocol(self, proto_obj, fix_imports) < 0)
  3070. return -1;
  3071. if (_Pickler_SetOutputStream(self, file) < 0)
  3072. return -1;
  3073. /* memo and output_buffer may have already been created in _Pickler_New */
  3074. if (self->memo == NULL) {
  3075. self->memo = PyMemoTable_New();
  3076. if (self->memo == NULL)
  3077. return -1;
  3078. }
  3079. self->output_len = 0;
  3080. if (self->output_buffer == NULL) {
  3081. self->max_output_len = WRITE_BUF_SIZE;
  3082. self->output_buffer = PyBytes_FromStringAndSize(NULL,
  3083. self->max_output_len);
  3084. if (self->output_buffer == NULL)
  3085. return -1;
  3086. }
  3087. self->arg = NULL;
  3088. self->fast = 0;
  3089. self->fast_nesting = 0;
  3090. self->fast_memo = NULL;
  3091. self->pers_func = NULL;
  3092. if (_PyObject_HasAttrId((PyObject *)self, &PyId_persistent_id)) {
  3093. self->pers_func = _PyObject_GetAttrId((PyObject *)self,
  3094. &PyId_persistent_id);
  3095. if (self->pers_func == NULL)
  3096. return -1;
  3097. }
  3098. self->dispatch_table = NULL;
  3099. if (_PyObject_HasAttrId((PyObject *)self, &PyId_dispatch_table)) {
  3100. self->dispatch_table = _PyObject_GetAttrId((PyObject *)self,
  3101. &PyId_dispatch_table);
  3102. if (self->dispatch_table == NULL)
  3103. return -1;
  3104. }
  3105. return 0;
  3106. }
  3107. /* Define a proxy object for the Pickler's internal memo object. This is to
  3108. * avoid breaking code like:
  3109. * pickler.memo.clear()
  3110. * and
  3111. * pickler.memo = saved_memo
  3112. * Is this a good idea? Not really, but we don't want to break code that uses
  3113. * it. Note that we don't implement the entire mapping API here. This is
  3114. * intentional, as these should be treated as black-box implementation details.
  3115. */
  3116. typedef struct {
  3117. PyObject_HEAD
  3118. PicklerObject *pickler; /* Pickler whose memo table we're proxying. */
  3119. } PicklerMemoProxyObject;
  3120. PyDoc_STRVAR(pmp_clear_doc,
  3121. "memo.clear() -> None. Remove all items from memo.");
  3122. static PyObject *
  3123. pmp_clear(PicklerMemoProxyObject *self)
  3124. {
  3125. if (self->pickler->memo)
  3126. PyMemoTable_Clear(self->pickler->memo);
  3127. Py_RETURN_NONE;
  3128. }
  3129. PyDoc_STRVAR(pmp_copy_doc,
  3130. "memo.copy() -> new_memo. Copy the memo to a new object.");
  3131. static PyObject *
  3132. pmp_copy(PicklerMemoProxyObject *self)
  3133. {
  3134. Py_ssize_t i;
  3135. PyMemoTable *memo;
  3136. PyObject *new_memo = PyDict_New();
  3137. if (new_memo == NULL)
  3138. return NULL;
  3139. memo = self->pickler->memo;
  3140. for (i = 0; i < memo->mt_allocated; ++i) {
  3141. PyMemoEntry entry = memo->mt_table[i];
  3142. if (entry.me_key != NULL) {
  3143. int status;
  3144. PyObject *key, *value;
  3145. key = PyLong_FromVoidPtr(entry.me_key);
  3146. value = Py_BuildValue("nO", entry.me_value, entry.me_key);
  3147. if (key == NULL || value == NULL) {
  3148. Py_XDECREF(key);
  3149. Py_XDECREF(value);
  3150. goto error;
  3151. }
  3152. status = PyDict_SetItem(new_memo, key, value);
  3153. Py_DECREF(key);
  3154. Py_DECREF(value);
  3155. if (status < 0)
  3156. goto error;
  3157. }
  3158. }
  3159. return new_memo;
  3160. error:
  3161. Py_XDECREF(new_memo);
  3162. return NULL;
  3163. }
  3164. PyDoc_STRVAR(pmp_reduce_doc,
  3165. "memo.__reduce__(). Pickling support.");
  3166. static PyObject *
  3167. pmp_reduce(PicklerMemoProxyObject *self, PyObject *args)
  3168. {
  3169. PyObject *reduce_value, *dict_args;
  3170. PyObject *contents = pmp_copy(self);
  3171. if (contents == NULL)
  3172. return NULL;
  3173. reduce_value = PyTuple_New(2);
  3174. if (reduce_value == NULL) {
  3175. Py_DECREF(contents);
  3176. return NULL;
  3177. }
  3178. dict_args = PyTuple_New(1);
  3179. if (dict_args == NULL) {
  3180. Py_DECREF(contents);
  3181. Py_DECREF(reduce_value);
  3182. return NULL;
  3183. }
  3184. PyTuple_SET_ITEM(dict_args, 0, contents);
  3185. Py_INCREF((PyObject *)&PyDict_Type);
  3186. PyTuple_SET_ITEM(reduce_value, 0, (PyObject *)&PyDict_Type);
  3187. PyTuple_SET_ITEM(reduce_value, 1, dict_args);
  3188. return reduce_value;
  3189. }
  3190. static PyMethodDef picklerproxy_methods[] = {
  3191. {"clear", (PyCFunction)pmp_clear, METH_NOARGS, pmp_clear_doc},
  3192. {"copy", (PyCFunction)pmp_copy, METH_NOARGS, pmp_copy_doc},
  3193. {"__reduce__", (PyCFunction)pmp_reduce, METH_VARARGS, pmp_reduce_doc},
  3194. {NULL, NULL} /* sentinel */
  3195. };
  3196. static void
  3197. PicklerMemoProxy_dealloc(PicklerMemoProxyObject *self)
  3198. {
  3199. PyObject_GC_UnTrack(self);
  3200. Py_XDECREF(self->pickler);
  3201. PyObject_GC_Del((PyObject *)self);
  3202. }
  3203. static int
  3204. PicklerMemoProxy_traverse(PicklerMemoProxyObject *self,
  3205. visitproc visit, void *arg)
  3206. {
  3207. Py_VISIT(self->pickler);
  3208. return 0;
  3209. }
  3210. static int
  3211. PicklerMemoProxy_clear(PicklerMemoProxyObject *self)
  3212. {
  3213. Py_CLEAR(self->pickler);
  3214. return 0;
  3215. }
  3216. static PyTypeObject PicklerMemoProxyType = {
  3217. PyVarObject_HEAD_INIT(NULL, 0)
  3218. "_pickle.PicklerMemoProxy", /*tp_name*/
  3219. sizeof(PicklerMemoProxyObject), /*tp_basicsize*/
  3220. 0,
  3221. (destructor)PicklerMemoProxy_dealloc, /* tp_dealloc */
  3222. 0, /* tp_print */
  3223. 0, /* tp_getattr */
  3224. 0, /* tp_setattr */
  3225. 0, /* tp_compare */
  3226. 0, /* tp_repr */
  3227. 0, /* tp_as_number */
  3228. 0, /* tp_as_sequence */
  3229. 0, /* tp_as_mapping */
  3230. PyObject_HashNotImplemented, /* tp_hash */
  3231. 0, /* tp_call */
  3232. 0, /* tp_str */
  3233. PyObject_GenericGetAttr, /* tp_getattro */
  3234. PyObject_GenericSetAttr, /* tp_setattro */
  3235. 0, /* tp_as_buffer */
  3236. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
  3237. 0, /* tp_doc */
  3238. (traverseproc)PicklerMemoProxy_traverse, /* tp_traverse */
  3239. (inquiry)PicklerMemoProxy_clear, /* tp_clear */
  3240. 0, /* tp_richcompare */
  3241. 0, /* tp_weaklistoffset */
  3242. 0, /* tp_iter */
  3243. 0, /* tp_iternext */
  3244. picklerproxy_methods, /* tp_methods */
  3245. };
  3246. static PyObject *
  3247. PicklerMemoProxy_New(PicklerObject *pickler)
  3248. {
  3249. PicklerMemoProxyObject *self;
  3250. self = PyObject_GC_New(PicklerMemoProxyObject, &PicklerMemoProxyType);
  3251. if (self == NULL)
  3252. return NULL;
  3253. Py_INCREF(pickler);
  3254. self->pickler = pickler;
  3255. PyObject_GC_Track(self);
  3256. return (PyObject *)self;
  3257. }
  3258. /*****************************************************************************/
  3259. static PyObject *
  3260. Pickler_get_memo(PicklerObject *self)
  3261. {
  3262. return PicklerMemoProxy_New(self);
  3263. }
  3264. static int
  3265. Pickler_set_memo(PicklerObject *self, PyObject *obj)
  3266. {
  3267. PyMemoTable *new_memo = NULL;
  3268. if (obj == NULL) {
  3269. PyErr_SetString(PyExc_TypeError,
  3270. "attribute deletion is not supported");
  3271. return -1;
  3272. }
  3273. if (Py_TYPE(obj) == &PicklerMemoProxyType) {
  3274. PicklerObject *pickler =
  3275. ((PicklerMemoProxyObject *)obj)->pickler;
  3276. new_memo = PyMemoTable_Copy(pickler->memo);
  3277. if (new_memo == NULL)
  3278. return -1;
  3279. }
  3280. else if (PyDict_Check(obj)) {
  3281. Py_ssize_t i = 0;
  3282. PyObject *key, *value;
  3283. new_memo = PyMemoTable_New();
  3284. if (new_memo == NULL)
  3285. return -1;
  3286. while (PyDict_Next(obj, &i, &key, &value)) {
  3287. Py_ssize_t memo_id;
  3288. PyObject *memo_obj;
  3289. if (!PyTuple_Check(value) || Py_SIZE(value) != 2) {
  3290. PyErr_SetString(PyExc_TypeError,
  3291. "'memo' values must be 2-item tuples");
  3292. goto error;
  3293. }
  3294. memo_id = PyLong_AsSsize_t(PyTuple_GET_ITEM(value, 0));
  3295. if (memo_id == -1 && PyErr_Occurred())
  3296. goto error;
  3297. memo_obj = PyTuple_GET_ITEM(value, 1);
  3298. if (PyMemoTable_Set(new_memo, memo_obj, memo_id) < 0)
  3299. goto error;
  3300. }
  3301. }
  3302. else {
  3303. PyErr_Format(PyExc_TypeError,
  3304. "'memo' attribute must be an PicklerMemoProxy object"
  3305. "or dict, not %.200s", Py_TYPE(obj)->tp_name);
  3306. return -1;
  3307. }
  3308. PyMemoTable_Del(self->memo);
  3309. self->memo = new_memo;
  3310. return 0;
  3311. error:
  3312. if (new_memo)
  3313. PyMemoTable_Del(new_memo);
  3314. return -1;
  3315. }
  3316. static PyObject *
  3317. Pickler_get_persid(PicklerObject *self)
  3318. {
  3319. if (self->pers_func == NULL)
  3320. PyErr_SetString(PyExc_AttributeError, "persistent_id");
  3321. else
  3322. Py_INCREF(self->pers_func);
  3323. return self->pers_func;
  3324. }
  3325. static int
  3326. Pickler_set_persid(PicklerObject *self, PyObject *value)
  3327. {
  3328. PyObject *tmp;
  3329. if (value == NULL) {
  3330. PyErr_SetString(PyExc_TypeError,
  3331. "attribute deletion is not supported");
  3332. return -1;
  3333. }
  3334. if (!PyCallable_Check(value)) {
  3335. PyErr_SetString(PyExc_TypeError,
  3336. "persistent_id must be a callable taking one argument");
  3337. return -1;
  3338. }
  3339. tmp = self->pers_func;
  3340. Py_INCREF(value);
  3341. self->pers_func = value;
  3342. Py_XDECREF(tmp); /* self->pers_func can be NULL, so be careful. */
  3343. return 0;
  3344. }
  3345. static PyMemberDef Pickler_members[] = {
  3346. {"bin", T_INT, offsetof(PicklerObject, bin)},
  3347. {"fast", T_INT, offsetof(PicklerObject, fast)},
  3348. {"dispatch_table", T_OBJECT_EX, offsetof(PicklerObject, dispatch_table)},
  3349. {NULL}
  3350. };
  3351. static PyGetSetDef Pickler_getsets[] = {
  3352. {"memo", (getter)Pickler_get_memo,
  3353. (setter)Pickler_set_memo},
  3354. {"persistent_id", (getter)Pickler_get_persid,
  3355. (setter)Pickler_set_persid},
  3356. {NULL}
  3357. };
  3358. static PyTypeObject Pickler_Type = {
  3359. PyVarObject_HEAD_INIT(NULL, 0)
  3360. "_pickle.Pickler" , /*tp_name*/
  3361. sizeof(PicklerObject), /*tp_basicsize*/
  3362. 0, /*tp_itemsize*/
  3363. (destructor)Pickler_dealloc, /*tp_dealloc*/
  3364. 0, /*tp_print*/
  3365. 0, /*tp_getattr*/
  3366. 0, /*tp_setattr*/
  3367. 0, /*tp_reserved*/
  3368. 0, /*tp_repr*/
  3369. 0, /*tp_as_number*/
  3370. 0, /*tp_as_sequence*/
  3371. 0, /*tp_as_mapping*/
  3372. 0, /*tp_hash*/
  3373. 0, /*tp_call*/
  3374. 0, /*tp_str*/
  3375. 0, /*tp_getattro*/
  3376. 0, /*tp_setattro*/
  3377. 0, /*tp_as_buffer*/
  3378. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
  3379. Pickler_doc, /*tp_doc*/
  3380. (traverseproc)Pickler_traverse, /*tp_traverse*/
  3381. (inquiry)Pickler_clear, /*tp_clear*/
  3382. 0, /*tp_richcompare*/
  3383. 0, /*tp_weaklistoffset*/
  3384. 0, /*tp_iter*/
  3385. 0, /*tp_iternext*/
  3386. Pickler_methods, /*tp_methods*/
  3387. Pickler_members, /*tp_members*/
  3388. Pickler_getsets, /*tp_getset*/
  3389. 0, /*tp_base*/
  3390. 0, /*tp_dict*/
  3391. 0, /*tp_descr_get*/
  3392. 0, /*tp_descr_set*/
  3393. 0, /*tp_dictoffset*/
  3394. (initproc)Pickler_init, /*tp_init*/
  3395. PyType_GenericAlloc, /*tp_alloc*/
  3396. PyType_GenericNew, /*tp_new*/
  3397. PyObject_GC_Del, /*tp_free*/
  3398. 0, /*tp_is_gc*/
  3399. };
  3400. /* Temporary helper for calling self.find_class().
  3401. XXX: It would be nice to able to avoid Python function call overhead, by
  3402. using directly the C version of find_class(), when find_class() is not
  3403. overridden by a subclass. Although, this could become rather hackish. A
  3404. simpler optimization would be to call the C function when self is not a
  3405. subclass instance. */
  3406. static PyObject *
  3407. find_class(UnpicklerObject *self, PyObject *module_name, PyObject *global_name)
  3408. {
  3409. _Py_IDENTIFIER(find_class);
  3410. return _PyObject_CallMethodId((PyObject *)self, &PyId_find_class, "OO",
  3411. module_name, global_name);
  3412. }
  3413. static Py_ssize_t
  3414. marker(UnpicklerObject *self)
  3415. {
  3416. if (self->num_marks < 1) {
  3417. PyErr_SetString(UnpicklingError, "could not find MARK");
  3418. return -1;
  3419. }
  3420. return self->marks[--self->num_marks];
  3421. }
  3422. static int
  3423. load_none(UnpicklerObject *self)
  3424. {
  3425. PDATA_APPEND(self->stack, Py_None, -1);
  3426. return 0;
  3427. }
  3428. static int
  3429. bad_readline(void)
  3430. {
  3431. PyErr_SetString(UnpicklingError, "pickle data was truncated");
  3432. return -1;
  3433. }
  3434. static int
  3435. load_int(UnpicklerObject *self)
  3436. {
  3437. PyObject *value;
  3438. char *endptr, *s;
  3439. Py_ssize_t len;
  3440. long x;
  3441. if ((len = _Unpickler_Readline(self, &s)) < 0)
  3442. return -1;
  3443. if (len < 2)
  3444. return bad_readline();
  3445. errno = 0;
  3446. /* XXX: Should the base argument of strtol() be explicitly set to 10?
  3447. XXX(avassalotti): Should this uses PyOS_strtol()? */
  3448. x = strtol(s, &endptr, 0);
  3449. if (errno || (*endptr != '\n' && *endptr != '\0')) {
  3450. /* Hm, maybe we've got something long. Let's try reading
  3451. * it as a Python long object. */
  3452. errno = 0;
  3453. /* XXX: Same thing about the base here. */
  3454. value = PyLong_FromString(s, NULL, 0);
  3455. if (value == NULL) {
  3456. PyErr_SetString(PyExc_ValueError,
  3457. "could not convert string to int");
  3458. return -1;
  3459. }
  3460. }
  3461. else {
  3462. if (len == 3 && (x == 0 || x == 1)) {
  3463. if ((value = PyBool_FromLong(x)) == NULL)
  3464. return -1;
  3465. }
  3466. else {
  3467. if ((value = PyLong_FromLong(x)) == NULL)
  3468. return -1;
  3469. }
  3470. }
  3471. PDATA_PUSH(self->stack, value, -1);
  3472. return 0;
  3473. }
  3474. static int
  3475. load_bool(UnpicklerObject *self, PyObject *boolean)
  3476. {
  3477. assert(boolean == Py_True || boolean == Py_False);
  3478. PDATA_APPEND(self->stack, boolean, -1);
  3479. return 0;
  3480. }
  3481. /* s contains x bytes of an unsigned little-endian integer. Return its value
  3482. * as a C Py_ssize_t, or -1 if it's higher than PY_SSIZE_T_MAX.
  3483. */
  3484. static Py_ssize_t
  3485. calc_binsize(char *bytes, int size)
  3486. {
  3487. unsigned char *s = (unsigned char *)bytes;
  3488. size_t x = 0;
  3489. assert(size == 4);
  3490. x = (size_t) s[0];
  3491. x |= (size_t) s[1] << 8;
  3492. x |= (size_t) s[2] << 16;
  3493. x |= (size_t) s[3] << 24;
  3494. if (x > PY_SSIZE_T_MAX)
  3495. return -1;
  3496. else
  3497. return (Py_ssize_t) x;
  3498. }
  3499. /* s contains x bytes of a little-endian integer. Return its value as a
  3500. * C int. Obscure: when x is 1 or 2, this is an unsigned little-endian
  3501. * int, but when x is 4 it's a signed one. This is an historical source
  3502. * of x-platform bugs.
  3503. */
  3504. static long
  3505. calc_binint(char *bytes, int size)
  3506. {
  3507. unsigned char *s = (unsigned char *)bytes;
  3508. int i = size;
  3509. long x = 0;
  3510. for (i = 0; i < size; i++) {
  3511. x |= (long)s[i] << (i * 8);
  3512. }
  3513. /* Unlike BININT1 and BININT2, BININT (more accurately BININT4)
  3514. * is signed, so on a box with longs bigger than 4 bytes we need
  3515. * to extend a BININT's sign bit to the full width.
  3516. */
  3517. if (SIZEOF_LONG > 4 && size == 4) {
  3518. x |= -(x & (1L << 31));
  3519. }
  3520. return x;
  3521. }
  3522. static int
  3523. load_binintx(UnpicklerObject *self, char *s, int size)
  3524. {
  3525. PyObject *value;
  3526. long x;
  3527. x = calc_binint(s, size);
  3528. if ((value = PyLong_FromLong(x)) == NULL)
  3529. return -1;
  3530. PDATA_PUSH(self->stack, value, -1);
  3531. return 0;
  3532. }
  3533. static int
  3534. load_binint(UnpicklerObject *self)
  3535. {
  3536. char *s;
  3537. if (_Unpickler_Read(self, &s, 4) < 0)
  3538. return -1;
  3539. return load_binintx(self, s, 4);
  3540. }
  3541. static int
  3542. load_binint1(UnpicklerObject *self)
  3543. {
  3544. char *s;
  3545. if (_Unpickler_Read(self, &s, 1) < 0)
  3546. return -1;
  3547. return load_binintx(self, s, 1);
  3548. }
  3549. static int
  3550. load_binint2(UnpicklerObject *self)
  3551. {
  3552. char *s;
  3553. if (_Unpickler_Read(self, &s, 2) < 0)
  3554. return -1;
  3555. return load_binintx(self, s, 2);
  3556. }
  3557. static int
  3558. load_long(UnpicklerObject *self)
  3559. {
  3560. PyObject *value;
  3561. char *s;
  3562. Py_ssize_t len;
  3563. if ((len = _Unpickler_Readline(self, &s)) < 0)
  3564. return -1;
  3565. if (len < 2)
  3566. return bad_readline();
  3567. /* s[len-2] will usually be 'L' (and s[len-1] is '\n'); we need to remove
  3568. the 'L' before calling PyLong_FromString. In order to maintain
  3569. compatibility with Python 3.0.0, we don't actually *require*
  3570. the 'L' to be present. */
  3571. if (s[len-2] == 'L')
  3572. s[len-2] = '\0';
  3573. /* XXX: Should the base argument explicitly set to 10? */
  3574. value = PyLong_FromString(s, NULL, 0);
  3575. if (value == NULL)
  3576. return -1;
  3577. PDATA_PUSH(self->stack, value, -1);
  3578. return 0;
  3579. }
  3580. /* 'size' bytes contain the # of bytes of little-endian 256's-complement
  3581. * data following.
  3582. */
  3583. static int
  3584. load_counted_long(UnpicklerObject *self, int size)
  3585. {
  3586. PyObject *value;
  3587. char *nbytes;
  3588. char *pdata;
  3589. assert(size == 1 || size == 4);
  3590. if (_Unpickler_Read(self, &nbytes, size) < 0)
  3591. return -1;
  3592. size = calc_binint(nbytes, size);
  3593. if (size < 0) {
  3594. /* Corrupt or hostile pickle -- we never write one like this */
  3595. PyErr_SetString(UnpicklingError,
  3596. "LONG pickle has negative byte count");
  3597. return -1;
  3598. }
  3599. if (size == 0)
  3600. value = PyLong_FromLong(0L);
  3601. else {
  3602. /* Read the raw little-endian bytes and convert. */
  3603. if (_Unpickler_Read(self, &pdata, size) < 0)
  3604. return -1;
  3605. value = _PyLong_FromByteArray((unsigned char *)pdata, (size_t)size,
  3606. 1 /* little endian */ , 1 /* signed */ );
  3607. }
  3608. if (value == NULL)
  3609. return -1;
  3610. PDATA_PUSH(self->stack, value, -1);
  3611. return 0;
  3612. }
  3613. static int
  3614. load_float(UnpicklerObject *self)
  3615. {
  3616. PyObject *value;
  3617. char *endptr, *s;
  3618. Py_ssize_t len;
  3619. double d;
  3620. if ((len = _Unpickler_Readline(self, &s)) < 0)
  3621. return -1;
  3622. if (len < 2)
  3623. return bad_readline();
  3624. errno = 0;
  3625. d = PyOS_string_to_double(s, &endptr, PyExc_OverflowError);
  3626. if (d == -1.0 && PyErr_Occurred())
  3627. return -1;
  3628. if ((endptr[0] != '\n') && (endptr[0] != '\0')) {
  3629. PyErr_SetString(PyExc_ValueError, "could not convert string to float");
  3630. return -1;
  3631. }
  3632. value = PyFloat_FromDouble(d);
  3633. if (value == NULL)
  3634. return -1;
  3635. PDATA_PUSH(self->stack, value, -1);
  3636. return 0;
  3637. }
  3638. static int
  3639. load_binfloat(UnpicklerObject *self)
  3640. {
  3641. PyObject *value;
  3642. double x;
  3643. char *s;
  3644. if (_Unpickler_Read(self, &s, 8) < 0)
  3645. return -1;
  3646. x = _PyFloat_Unpack8((unsigned char *)s, 0);
  3647. if (x == -1.0 && PyErr_Occurred())
  3648. return -1;
  3649. if ((value = PyFloat_FromDouble(x)) == NULL)
  3650. return -1;
  3651. PDATA_PUSH(self->stack, value, -1);
  3652. return 0;
  3653. }
  3654. static int
  3655. load_string(UnpicklerObject *self)
  3656. {
  3657. PyObject *bytes;
  3658. PyObject *str = NULL;
  3659. Py_ssize_t len;
  3660. char *s, *p;
  3661. if ((len = _Unpickler_Readline(self, &s)) < 0)
  3662. return -1;
  3663. /* Strip the newline */
  3664. len--;
  3665. /* Strip outermost quotes */
  3666. if (len >= 2 && s[0] == s[len - 1] && (s[0] == '\'' || s[0] == '"')) {
  3667. p = s + 1;
  3668. len -= 2;
  3669. }
  3670. else {
  3671. PyErr_SetString(UnpicklingError,
  3672. "the STRING opcode argument must be quoted");
  3673. return -1;
  3674. }
  3675. assert(len >= 0);
  3676. /* Use the PyBytes API to decode the string, since that is what is used
  3677. to encode, and then coerce the result to Unicode. */
  3678. bytes = PyBytes_DecodeEscape(p, len, NULL, 0, NULL);
  3679. if (bytes == NULL)
  3680. return -1;
  3681. str = PyUnicode_FromEncodedObject(bytes, self->encoding, self->errors);
  3682. Py_DECREF(bytes);
  3683. if (str == NULL)
  3684. return -1;
  3685. PDATA_PUSH(self->stack, str, -1);
  3686. return 0;
  3687. }
  3688. static int
  3689. load_binbytes(UnpicklerObject *self)
  3690. {
  3691. PyObject *bytes;
  3692. Py_ssize_t x;
  3693. char *s;
  3694. if (_Unpickler_Read(self, &s, 4) < 0)
  3695. return -1;
  3696. x = calc_binsize(s, 4);
  3697. if (x < 0) {
  3698. PyErr_Format(PyExc_OverflowError,
  3699. "BINBYTES exceeds system's maximum size of %zd bytes",
  3700. PY_SSIZE_T_MAX);
  3701. return -1;
  3702. }
  3703. if (_Unpickler_Read(self, &s, x) < 0)
  3704. return -1;
  3705. bytes = PyBytes_FromStringAndSize(s, x);
  3706. if (bytes == NULL)
  3707. return -1;
  3708. PDATA_PUSH(self->stack, bytes, -1);
  3709. return 0;
  3710. }
  3711. static int
  3712. load_short_binbytes(UnpicklerObject *self)
  3713. {
  3714. PyObject *bytes;
  3715. Py_ssize_t x;
  3716. char *s;
  3717. if (_Unpickler_Read(self, &s, 1) < 0)
  3718. return -1;
  3719. x = (unsigned char)s[0];
  3720. if (_Unpickler_Read(self, &s, x) < 0)
  3721. return -1;
  3722. bytes = PyBytes_FromStringAndSize(s, x);
  3723. if (bytes == NULL)
  3724. return -1;
  3725. PDATA_PUSH(self->stack, bytes, -1);
  3726. return 0;
  3727. }
  3728. static int
  3729. load_binstring(UnpicklerObject *self)
  3730. {
  3731. PyObject *str;
  3732. Py_ssize_t x;
  3733. char *s;
  3734. if (_Unpickler_Read(self, &s, 4) < 0)
  3735. return -1;
  3736. x = calc_binint(s, 4);
  3737. if (x < 0) {
  3738. PyErr_SetString(UnpicklingError,
  3739. "BINSTRING pickle has negative byte count");
  3740. return -1;
  3741. }
  3742. if (_Unpickler_Read(self, &s, x) < 0)
  3743. return -1;
  3744. /* Convert Python 2.x strings to unicode. */
  3745. str = PyUnicode_Decode(s, x, self->encoding, self->errors);
  3746. if (str == NULL)
  3747. return -1;
  3748. PDATA_PUSH(self->stack, str, -1);
  3749. return 0;
  3750. }
  3751. static int
  3752. load_short_binstring(UnpicklerObject *self)
  3753. {
  3754. PyObject *str;
  3755. Py_ssize_t x;
  3756. char *s;
  3757. if (_Unpickler_Read(self, &s, 1) < 0)
  3758. return -1;
  3759. x = (unsigned char)s[0];
  3760. if (_Unpickler_Read(self, &s, x) < 0)
  3761. return -1;
  3762. /* Convert Python 2.x strings to unicode. */
  3763. str = PyUnicode_Decode(s, x, self->encoding, self->errors);
  3764. if (str == NULL)
  3765. return -1;
  3766. PDATA_PUSH(self->stack, str, -1);
  3767. return 0;
  3768. }
  3769. static int
  3770. load_unicode(UnpicklerObject *self)
  3771. {
  3772. PyObject *str;
  3773. Py_ssize_t len;
  3774. char *s;
  3775. if ((len = _Unpickler_Readline(self, &s)) < 0)
  3776. return -1;
  3777. if (len < 1)
  3778. return bad_readline();
  3779. str = PyUnicode_DecodeRawUnicodeEscape(s, len - 1, NULL);
  3780. if (str == NULL)
  3781. return -1;
  3782. PDATA_PUSH(self->stack, str, -1);
  3783. return 0;
  3784. }
  3785. static int
  3786. load_binunicode(UnpicklerObject *self)
  3787. {
  3788. PyObject *str;
  3789. Py_ssize_t size;
  3790. char *s;
  3791. if (_Unpickler_Read(self, &s, 4) < 0)
  3792. return -1;
  3793. size = calc_binsize(s, 4);
  3794. if (size < 0) {
  3795. PyErr_Format(PyExc_OverflowError,
  3796. "BINUNICODE exceeds system's maximum size of %zd bytes",
  3797. PY_SSIZE_T_MAX);
  3798. return -1;
  3799. }
  3800. if (_Unpickler_Read(self, &s, size) < 0)
  3801. return -1;
  3802. str = PyUnicode_DecodeUTF8(s, size, "surrogatepass");
  3803. if (str == NULL)
  3804. return -1;
  3805. PDATA_PUSH(self->stack, str, -1);
  3806. return 0;
  3807. }
  3808. static int
  3809. load_tuple(UnpicklerObject *self)
  3810. {
  3811. PyObject *tuple;
  3812. Py_ssize_t i;
  3813. if ((i = marker(self)) < 0)
  3814. return -1;
  3815. tuple = Pdata_poptuple(self->stack, i);
  3816. if (tuple == NULL)
  3817. return -1;
  3818. PDATA_PUSH(self->stack, tuple, -1);
  3819. return 0;
  3820. }
  3821. static int
  3822. load_counted_tuple(UnpicklerObject *self, int len)
  3823. {
  3824. PyObject *tuple;
  3825. tuple = PyTuple_New(len);
  3826. if (tuple == NULL)
  3827. return -1;
  3828. while (--len >= 0) {
  3829. PyObject *item;
  3830. PDATA_POP(self->stack, item);
  3831. if (item == NULL)
  3832. return -1;
  3833. PyTuple_SET_ITEM(tuple, len, item);
  3834. }
  3835. PDATA_PUSH(self->stack, tuple, -1);
  3836. return 0;
  3837. }
  3838. static int
  3839. load_empty_list(UnpicklerObject *self)
  3840. {
  3841. PyObject *list;
  3842. if ((list = PyList_New(0)) == NULL)
  3843. return -1;
  3844. PDATA_PUSH(self->stack, list, -1);
  3845. return 0;
  3846. }
  3847. static int
  3848. load_empty_dict(UnpicklerObject *self)
  3849. {
  3850. PyObject *dict;
  3851. if ((dict = PyDict_New()) == NULL)
  3852. return -1;
  3853. PDATA_PUSH(self->stack, dict, -1);
  3854. return 0;
  3855. }
  3856. static int
  3857. load_list(UnpicklerObject *self)
  3858. {
  3859. PyObject *list;
  3860. Py_ssize_t i;
  3861. if ((i = marker(self)) < 0)
  3862. return -1;
  3863. list = Pdata_poplist(self->stack, i);
  3864. if (list == NULL)
  3865. return -1;
  3866. PDATA_PUSH(self->stack, list, -1);
  3867. return 0;
  3868. }
  3869. static int
  3870. load_dict(UnpicklerObject *self)
  3871. {
  3872. PyObject *dict, *key, *value;
  3873. Py_ssize_t i, j, k;
  3874. if ((i = marker(self)) < 0)
  3875. return -1;
  3876. j = Py_SIZE(self->stack);
  3877. if ((dict = PyDict_New()) == NULL)
  3878. return -1;
  3879. for (k = i + 1; k < j; k += 2) {
  3880. key = self->stack->data[k - 1];
  3881. value = self->stack->data[k];
  3882. if (PyDict_SetItem(dict, key, value) < 0) {
  3883. Py_DECREF(dict);
  3884. return -1;
  3885. }
  3886. }
  3887. Pdata_clear(self->stack, i);
  3888. PDATA_PUSH(self->stack, dict, -1);
  3889. return 0;
  3890. }
  3891. static PyObject *
  3892. instantiate(PyObject *cls, PyObject *args)
  3893. {
  3894. PyObject *result = NULL;
  3895. _Py_IDENTIFIER(__getinitargs__);
  3896. /* Caller must assure args are a tuple. Normally, args come from
  3897. Pdata_poptuple which packs objects from the top of the stack
  3898. into a newly created tuple. */
  3899. assert(PyTuple_Check(args));
  3900. if (Py_SIZE(args) > 0 || !PyType_Check(cls) ||
  3901. _PyObject_HasAttrId(cls, &PyId___getinitargs__)) {
  3902. result = PyObject_CallObject(cls, args);
  3903. }
  3904. else {
  3905. _Py_IDENTIFIER(__new__);
  3906. result = _PyObject_CallMethodId(cls, &PyId___new__, "O", cls);
  3907. }
  3908. return result;
  3909. }
  3910. static int
  3911. load_obj(UnpicklerObject *self)
  3912. {
  3913. PyObject *cls, *args, *obj = NULL;
  3914. Py_ssize_t i;
  3915. if ((i = marker(self)) < 0)
  3916. return -1;
  3917. args = Pdata_poptuple(self->stack, i + 1);
  3918. if (args == NULL)
  3919. return -1;
  3920. PDATA_POP(self->stack, cls);
  3921. if (cls) {
  3922. obj = instantiate(cls, args);
  3923. Py_DECREF(cls);
  3924. }
  3925. Py_DECREF(args);
  3926. if (obj == NULL)
  3927. return -1;
  3928. PDATA_PUSH(self->stack, obj, -1);
  3929. return 0;
  3930. }
  3931. static int
  3932. load_inst(UnpicklerObject *self)
  3933. {
  3934. PyObject *cls = NULL;
  3935. PyObject *args = NULL;
  3936. PyObject *obj = NULL;
  3937. PyObject *module_name;
  3938. PyObject *class_name;
  3939. Py_ssize_t len;
  3940. Py_ssize_t i;
  3941. char *s;
  3942. if ((i = marker(self)) < 0)
  3943. return -1;
  3944. if ((len = _Unpickler_Readline(self, &s)) < 0)
  3945. return -1;
  3946. if (len < 2)
  3947. return bad_readline();
  3948. /* Here it is safe to use PyUnicode_DecodeASCII(), even though non-ASCII
  3949. identifiers are permitted in Python 3.0, since the INST opcode is only
  3950. supported by older protocols on Python 2.x. */
  3951. module_name = PyUnicode_DecodeASCII(s, len - 1, "strict");
  3952. if (module_name == NULL)
  3953. return -1;
  3954. if ((len = _Unpickler_Readline(self, &s)) >= 0) {
  3955. if (len < 2)
  3956. return bad_readline();
  3957. class_name = PyUnicode_DecodeASCII(s, len - 1, "strict");
  3958. if (class_name != NULL) {
  3959. cls = find_class(self, module_name, class_name);
  3960. Py_DECREF(class_name);
  3961. }
  3962. }
  3963. Py_DECREF(module_name);
  3964. if (cls == NULL)
  3965. return -1;
  3966. if ((args = Pdata_poptuple(self->stack, i)) != NULL) {
  3967. obj = instantiate(cls, args);
  3968. Py_DECREF(args);
  3969. }
  3970. Py_DECREF(cls);
  3971. if (obj == NULL)
  3972. return -1;
  3973. PDATA_PUSH(self->stack, obj, -1);
  3974. return 0;
  3975. }
  3976. static int
  3977. load_newobj(UnpicklerObject *self)
  3978. {
  3979. PyObject *args = NULL;
  3980. PyObject *clsraw = NULL;
  3981. PyTypeObject *cls; /* clsraw cast to its true type */
  3982. PyObject *obj;
  3983. /* Stack is ... cls argtuple, and we want to call
  3984. * cls.__new__(cls, *argtuple).
  3985. */
  3986. PDATA_POP(self->stack, args);
  3987. if (args == NULL)
  3988. goto error;
  3989. if (!PyTuple_Check(args)) {
  3990. PyErr_SetString(UnpicklingError, "NEWOBJ expected an arg " "tuple.");
  3991. goto error;
  3992. }
  3993. PDATA_POP(self->stack, clsraw);
  3994. cls = (PyTypeObject *)clsraw;
  3995. if (cls == NULL)
  3996. goto error;
  3997. if (!PyType_Check(cls)) {
  3998. PyErr_SetString(UnpicklingError, "NEWOBJ class argument "
  3999. "isn't a type object");
  4000. goto error;
  4001. }
  4002. if (cls->tp_new == NULL) {
  4003. PyErr_SetString(UnpicklingError, "NEWOBJ class argument "
  4004. "has NULL tp_new");
  4005. goto error;
  4006. }
  4007. /* Call __new__. */
  4008. obj = cls->tp_new(cls, args, NULL);
  4009. if (obj == NULL)
  4010. goto error;
  4011. Py_DECREF(args);
  4012. Py_DECREF(clsraw);
  4013. PDATA_PUSH(self->stack, obj, -1);
  4014. return 0;
  4015. error:
  4016. Py_XDECREF(args);
  4017. Py_XDECREF(clsraw);
  4018. return -1;
  4019. }
  4020. static int
  4021. load_global(UnpicklerObject *self)
  4022. {
  4023. PyObject *global = NULL;
  4024. PyObject *module_name;
  4025. PyObject *global_name;
  4026. Py_ssize_t len;
  4027. char *s;
  4028. if ((len = _Unpickler_Readline(self, &s)) < 0)
  4029. return -1;
  4030. if (len < 2)
  4031. return bad_readline();
  4032. module_name = PyUnicode_DecodeUTF8(s, len - 1, "strict");
  4033. if (!module_name)
  4034. return -1;
  4035. if ((len = _Unpickler_Readline(self, &s)) >= 0) {
  4036. if (len < 2) {
  4037. Py_DECREF(module_name);
  4038. return bad_readline();
  4039. }
  4040. global_name = PyUnicode_DecodeUTF8(s, len - 1, "strict");
  4041. if (global_name) {
  4042. global = find_class(self, module_name, global_name);
  4043. Py_DECREF(global_name);
  4044. }
  4045. }
  4046. Py_DECREF(module_name);
  4047. if (global == NULL)
  4048. return -1;
  4049. PDATA_PUSH(self->stack, global, -1);
  4050. return 0;
  4051. }
  4052. static int
  4053. load_persid(UnpicklerObject *self)
  4054. {
  4055. PyObject *pid;
  4056. Py_ssize_t len;
  4057. char *s;
  4058. if (self->pers_func) {
  4059. if ((len = _Unpickler_Readline(self, &s)) < 0)
  4060. return -1;
  4061. if (len < 2)
  4062. return bad_readline();
  4063. pid = PyBytes_FromStringAndSize(s, len - 1);
  4064. if (pid == NULL)
  4065. return -1;
  4066. /* Ugh... this does not leak since _Unpickler_FastCall() steals the
  4067. reference to pid first. */
  4068. pid = _Unpickler_FastCall(self, self->pers_func, pid);
  4069. if (pid == NULL)
  4070. return -1;
  4071. PDATA_PUSH(self->stack, pid, -1);
  4072. return 0;
  4073. }
  4074. else {
  4075. PyErr_SetString(UnpicklingError,
  4076. "A load persistent id instruction was encountered,\n"
  4077. "but no persistent_load function was specified.");
  4078. return -1;
  4079. }
  4080. }
  4081. static int
  4082. load_binpersid(UnpicklerObject *self)
  4083. {
  4084. PyObject *pid;
  4085. if (self->pers_func) {
  4086. PDATA_POP(self->stack, pid);
  4087. if (pid == NULL)
  4088. return -1;
  4089. /* Ugh... this does not leak since _Unpickler_FastCall() steals the
  4090. reference to pid first. */
  4091. pid = _Unpickler_FastCall(self, self->pers_func, pid);
  4092. if (pid == NULL)
  4093. return -1;
  4094. PDATA_PUSH(self->stack, pid, -1);
  4095. return 0;
  4096. }
  4097. else {
  4098. PyErr_SetString(UnpicklingError,
  4099. "A load persistent id instruction was encountered,\n"
  4100. "but no persistent_load function was specified.");
  4101. return -1;
  4102. }
  4103. }
  4104. static int
  4105. load_pop(UnpicklerObject *self)
  4106. {
  4107. Py_ssize_t len = Py_SIZE(self->stack);
  4108. /* Note that we split the (pickle.py) stack into two stacks,
  4109. * an object stack and a mark stack. We have to be clever and
  4110. * pop the right one. We do this by looking at the top of the
  4111. * mark stack first, and only signalling a stack underflow if
  4112. * the object stack is empty and the mark stack doesn't match
  4113. * our expectations.
  4114. */
  4115. if (self->num_marks > 0 && self->marks[self->num_marks - 1] == len) {
  4116. self->num_marks--;
  4117. } else if (len > 0) {
  4118. len--;
  4119. Py_DECREF(self->stack->data[len]);
  4120. Py_SIZE(self->stack) = len;
  4121. } else {
  4122. return stack_underflow();
  4123. }
  4124. return 0;
  4125. }
  4126. static int
  4127. load_pop_mark(UnpicklerObject *self)
  4128. {
  4129. Py_ssize_t i;
  4130. if ((i = marker(self)) < 0)
  4131. return -1;
  4132. Pdata_clear(self->stack, i);
  4133. return 0;
  4134. }
  4135. static int
  4136. load_dup(UnpicklerObject *self)
  4137. {
  4138. PyObject *last;
  4139. Py_ssize_t len;
  4140. if ((len = Py_SIZE(self->stack)) <= 0)
  4141. return stack_underflow();
  4142. last = self->stack->data[len - 1];
  4143. PDATA_APPEND(self->stack, last, -1);
  4144. return 0;
  4145. }
  4146. static int
  4147. load_get(UnpicklerObject *self)
  4148. {
  4149. PyObject *key, *value;
  4150. Py_ssize_t idx;
  4151. Py_ssize_t len;
  4152. char *s;
  4153. if ((len = _Unpickler_Readline(self, &s)) < 0)
  4154. return -1;
  4155. if (len < 2)
  4156. return bad_readline();
  4157. key = PyLong_FromString(s, NULL, 10);
  4158. if (key == NULL)
  4159. return -1;
  4160. idx = PyLong_AsSsize_t(key);
  4161. if (idx == -1 && PyErr_Occurred()) {
  4162. Py_DECREF(key);
  4163. return -1;
  4164. }
  4165. value = _Unpickler_MemoGet(self, idx);
  4166. if (value == NULL) {
  4167. if (!PyErr_Occurred())
  4168. PyErr_SetObject(PyExc_KeyError, key);
  4169. Py_DECREF(key);
  4170. return -1;
  4171. }
  4172. Py_DECREF(key);
  4173. PDATA_APPEND(self->stack, value, -1);
  4174. return 0;
  4175. }
  4176. static int
  4177. load_binget(UnpicklerObject *self)
  4178. {
  4179. PyObject *value;
  4180. Py_ssize_t idx;
  4181. char *s;
  4182. if (_Unpickler_Read(self, &s, 1) < 0)
  4183. return -1;
  4184. idx = Py_CHARMASK(s[0]);
  4185. value = _Unpickler_MemoGet(self, idx);
  4186. if (value == NULL) {
  4187. PyObject *key = PyLong_FromSsize_t(idx);
  4188. if (key != NULL) {
  4189. PyErr_SetObject(PyExc_KeyError, key);
  4190. Py_DECREF(key);
  4191. }
  4192. return -1;
  4193. }
  4194. PDATA_APPEND(self->stack, value, -1);
  4195. return 0;
  4196. }
  4197. static int
  4198. load_long_binget(UnpicklerObject *self)
  4199. {
  4200. PyObject *value;
  4201. Py_ssize_t idx;
  4202. char *s;
  4203. if (_Unpickler_Read(self, &s, 4) < 0)
  4204. return -1;
  4205. idx = calc_binsize(s, 4);
  4206. value = _Unpickler_MemoGet(self, idx);
  4207. if (value == NULL) {
  4208. PyObject *key = PyLong_FromSsize_t(idx);
  4209. if (key != NULL) {
  4210. PyErr_SetObject(PyExc_KeyError, key);
  4211. Py_DECREF(key);
  4212. }
  4213. return -1;
  4214. }
  4215. PDATA_APPEND(self->stack, value, -1);
  4216. return 0;
  4217. }
  4218. /* Push an object from the extension registry (EXT[124]). nbytes is
  4219. * the number of bytes following the opcode, holding the index (code) value.
  4220. */
  4221. static int
  4222. load_extension(UnpicklerObject *self, int nbytes)
  4223. {
  4224. char *codebytes; /* the nbytes bytes after the opcode */
  4225. long code; /* calc_binint returns long */
  4226. PyObject *py_code; /* code as a Python int */
  4227. PyObject *obj; /* the object to push */
  4228. PyObject *pair; /* (module_name, class_name) */
  4229. PyObject *module_name, *class_name;
  4230. assert(nbytes == 1 || nbytes == 2 || nbytes == 4);
  4231. if (_Unpickler_Read(self, &codebytes, nbytes) < 0)
  4232. return -1;
  4233. code = calc_binint(codebytes, nbytes);
  4234. if (code <= 0) { /* note that 0 is forbidden */
  4235. /* Corrupt or hostile pickle. */
  4236. PyErr_SetString(UnpicklingError, "EXT specifies code <= 0");
  4237. return -1;
  4238. }
  4239. /* Look for the code in the cache. */
  4240. py_code = PyLong_FromLong(code);
  4241. if (py_code == NULL)
  4242. return -1;
  4243. obj = PyDict_GetItem(extension_cache, py_code);
  4244. if (obj != NULL) {
  4245. /* Bingo. */
  4246. Py_DECREF(py_code);
  4247. PDATA_APPEND(self->stack, obj, -1);
  4248. return 0;
  4249. }
  4250. /* Look up the (module_name, class_name) pair. */
  4251. pair = PyDict_GetItem(inverted_registry, py_code);
  4252. if (pair == NULL) {
  4253. Py_DECREF(py_code);
  4254. PyErr_Format(PyExc_ValueError, "unregistered extension "
  4255. "code %ld", code);
  4256. return -1;
  4257. }
  4258. /* Since the extension registry is manipulable via Python code,
  4259. * confirm that pair is really a 2-tuple of strings.
  4260. */
  4261. if (!PyTuple_Check(pair) || PyTuple_Size(pair) != 2 ||
  4262. !PyUnicode_Check(module_name = PyTuple_GET_ITEM(pair, 0)) ||
  4263. !PyUnicode_Check(class_name = PyTuple_GET_ITEM(pair, 1))) {
  4264. Py_DECREF(py_code);
  4265. PyErr_Format(PyExc_ValueError, "_inverted_registry[%ld] "
  4266. "isn't a 2-tuple of strings", code);
  4267. return -1;
  4268. }
  4269. /* Load the object. */
  4270. obj = find_class(self, module_name, class_name);
  4271. if (obj == NULL) {
  4272. Py_DECREF(py_code);
  4273. return -1;
  4274. }
  4275. /* Cache code -> obj. */
  4276. code = PyDict_SetItem(extension_cache, py_code, obj);
  4277. Py_DECREF(py_code);
  4278. if (code < 0) {
  4279. Py_DECREF(obj);
  4280. return -1;
  4281. }
  4282. PDATA_PUSH(self->stack, obj, -1);
  4283. return 0;
  4284. }
  4285. static int
  4286. load_put(UnpicklerObject *self)
  4287. {
  4288. PyObject *key, *value;
  4289. Py_ssize_t idx;
  4290. Py_ssize_t len;
  4291. char *s;
  4292. if ((len = _Unpickler_Readline(self, &s)) < 0)
  4293. return -1;
  4294. if (len < 2)
  4295. return bad_readline();
  4296. if (Py_SIZE(self->stack) <= 0)
  4297. return stack_underflow();
  4298. value = self->stack->data[Py_SIZE(self->stack) - 1];
  4299. key = PyLong_FromString(s, NULL, 10);
  4300. if (key == NULL)
  4301. return -1;
  4302. idx = PyLong_AsSsize_t(key);
  4303. Py_DECREF(key);
  4304. if (idx < 0) {
  4305. if (!PyErr_Occurred())
  4306. PyErr_SetString(PyExc_ValueError,
  4307. "negative PUT argument");
  4308. return -1;
  4309. }
  4310. return _Unpickler_MemoPut(self, idx, value);
  4311. }
  4312. static int
  4313. load_binput(UnpicklerObject *self)
  4314. {
  4315. PyObject *value;
  4316. Py_ssize_t idx;
  4317. char *s;
  4318. if (_Unpickler_Read(self, &s, 1) < 0)
  4319. return -1;
  4320. if (Py_SIZE(self->stack) <= 0)
  4321. return stack_underflow();
  4322. value = self->stack->data[Py_SIZE(self->stack) - 1];
  4323. idx = Py_CHARMASK(s[0]);
  4324. return _Unpickler_MemoPut(self, idx, value);
  4325. }
  4326. static int
  4327. load_long_binput(UnpicklerObject *self)
  4328. {
  4329. PyObject *value;
  4330. Py_ssize_t idx;
  4331. char *s;
  4332. if (_Unpickler_Read(self, &s, 4) < 0)
  4333. return -1;
  4334. if (Py_SIZE(self->stack) <= 0)
  4335. return stack_underflow();
  4336. value = self->stack->data[Py_SIZE(self->stack) - 1];
  4337. idx = calc_binsize(s, 4);
  4338. if (idx < 0) {
  4339. PyErr_SetString(PyExc_ValueError,
  4340. "negative LONG_BINPUT argument");
  4341. return -1;
  4342. }
  4343. return _Unpickler_MemoPut(self, idx, value);
  4344. }
  4345. static int
  4346. do_append(UnpicklerObject *self, Py_ssize_t x)
  4347. {
  4348. PyObject *value;
  4349. PyObject *list;
  4350. Py_ssize_t len, i;
  4351. len = Py_SIZE(self->stack);
  4352. if (x > len || x <= 0)
  4353. return stack_underflow();
  4354. if (len == x) /* nothing to do */
  4355. return 0;
  4356. list = self->stack->data[x - 1];
  4357. if (PyList_Check(list)) {
  4358. PyObject *slice;
  4359. Py_ssize_t list_len;
  4360. int ret;
  4361. slice = Pdata_poplist(self->stack, x);
  4362. if (!slice)
  4363. return -1;
  4364. list_len = PyList_GET_SIZE(list);
  4365. ret = PyList_SetSlice(list, list_len, list_len, slice);
  4366. Py_DECREF(slice);
  4367. return ret;
  4368. }
  4369. else {
  4370. PyObject *append_func;
  4371. _Py_IDENTIFIER(append);
  4372. append_func = _PyObject_GetAttrId(list, &PyId_append);
  4373. if (append_func == NULL)
  4374. return -1;
  4375. for (i = x; i < len; i++) {
  4376. PyObject *result;
  4377. value = self->stack->data[i];
  4378. result = _Unpickler_FastCall(self, append_func, value);
  4379. if (result == NULL) {
  4380. Pdata_clear(self->stack, i + 1);
  4381. Py_SIZE(self->stack) = x;
  4382. Py_DECREF(append_func);
  4383. return -1;
  4384. }
  4385. Py_DECREF(result);
  4386. }
  4387. Py_SIZE(self->stack) = x;
  4388. Py_DECREF(append_func);
  4389. }
  4390. return 0;
  4391. }
  4392. static int
  4393. load_append(UnpicklerObject *self)
  4394. {
  4395. return do_append(self, Py_SIZE(self->stack) - 1);
  4396. }
  4397. static int
  4398. load_appends(UnpicklerObject *self)
  4399. {
  4400. return do_append(self, marker(self));
  4401. }
  4402. static int
  4403. do_setitems(UnpicklerObject *self, Py_ssize_t x)
  4404. {
  4405. PyObject *value, *key;
  4406. PyObject *dict;
  4407. Py_ssize_t len, i;
  4408. int status = 0;
  4409. len = Py_SIZE(self->stack);
  4410. if (x > len || x <= 0)
  4411. return stack_underflow();
  4412. if (len == x) /* nothing to do */
  4413. return 0;
  4414. if ((len - x) % 2 != 0) {
  4415. /* Currupt or hostile pickle -- we never write one like this. */
  4416. PyErr_SetString(UnpicklingError, "odd number of items for SETITEMS");
  4417. return -1;
  4418. }
  4419. /* Here, dict does not actually need to be a PyDict; it could be anything
  4420. that supports the __setitem__ attribute. */
  4421. dict = self->stack->data[x - 1];
  4422. for (i = x + 1; i < len; i += 2) {
  4423. key = self->stack->data[i - 1];
  4424. value = self->stack->data[i];
  4425. if (PyObject_SetItem(dict, key, value) < 0) {
  4426. status = -1;
  4427. break;
  4428. }
  4429. }
  4430. Pdata_clear(self->stack, x);
  4431. return status;
  4432. }
  4433. static int
  4434. load_setitem(UnpicklerObject *self)
  4435. {
  4436. return do_setitems(self, Py_SIZE(self->stack) - 2);
  4437. }
  4438. static int
  4439. load_setitems(UnpicklerObject *self)
  4440. {
  4441. return do_setitems(self, marker(self));
  4442. }
  4443. static int
  4444. load_build(UnpicklerObject *self)
  4445. {
  4446. PyObject *state, *inst, *slotstate;
  4447. PyObject *setstate;
  4448. int status = 0;
  4449. _Py_IDENTIFIER(__setstate__);
  4450. /* Stack is ... instance, state. We want to leave instance at
  4451. * the stack top, possibly mutated via instance.__setstate__(state).
  4452. */
  4453. if (Py_SIZE(self->stack) < 2)
  4454. return stack_underflow();
  4455. PDATA_POP(self->stack, state);
  4456. if (state == NULL)
  4457. return -1;
  4458. inst = self->stack->data[Py_SIZE(self->stack) - 1];
  4459. setstate = _PyObject_GetAttrId(inst, &PyId___setstate__);
  4460. if (setstate == NULL) {
  4461. if (PyErr_ExceptionMatches(PyExc_AttributeError))
  4462. PyErr_Clear();
  4463. else {
  4464. Py_DECREF(state);
  4465. return -1;
  4466. }
  4467. }
  4468. else {
  4469. PyObject *result;
  4470. /* The explicit __setstate__ is responsible for everything. */
  4471. /* Ugh... this does not leak since _Unpickler_FastCall() steals the
  4472. reference to state first. */
  4473. result = _Unpickler_FastCall(self, setstate, state);
  4474. Py_DECREF(setstate);
  4475. if (result == NULL)
  4476. return -1;
  4477. Py_DECREF(result);
  4478. return 0;
  4479. }
  4480. /* A default __setstate__. First see whether state embeds a
  4481. * slot state dict too (a proto 2 addition).
  4482. */
  4483. if (PyTuple_Check(state) && Py_SIZE(state) == 2) {
  4484. PyObject *tmp = state;
  4485. state = PyTuple_GET_ITEM(tmp, 0);
  4486. slotstate = PyTuple_GET_ITEM(tmp, 1);
  4487. Py_INCREF(state);
  4488. Py_INCREF(slotstate);
  4489. Py_DECREF(tmp);
  4490. }
  4491. else
  4492. slotstate = NULL;
  4493. /* Set inst.__dict__ from the state dict (if any). */
  4494. if (state != Py_None) {
  4495. PyObject *dict;
  4496. PyObject *d_key, *d_value;
  4497. Py_ssize_t i;
  4498. _Py_IDENTIFIER(__dict__);
  4499. if (!PyDict_Check(state)) {
  4500. PyErr_SetString(UnpicklingError, "state is not a dictionary");
  4501. goto error;
  4502. }
  4503. dict = _PyObject_GetAttrId(inst, &PyId___dict__);
  4504. if (dict == NULL)
  4505. goto error;
  4506. i = 0;
  4507. while (PyDict_Next(state, &i, &d_key, &d_value)) {
  4508. /* normally the keys for instance attributes are
  4509. interned. we should try to do that here. */
  4510. Py_INCREF(d_key);
  4511. if (PyUnicode_CheckExact(d_key))
  4512. PyUnicode_InternInPlace(&d_key);
  4513. if (PyObject_SetItem(dict, d_key, d_value) < 0) {
  4514. Py_DECREF(d_key);
  4515. goto error;
  4516. }
  4517. Py_DECREF(d_key);
  4518. }
  4519. Py_DECREF(dict);
  4520. }
  4521. /* Also set instance attributes from the slotstate dict (if any). */
  4522. if (slotstate != NULL) {
  4523. PyObject *d_key, *d_value;
  4524. Py_ssize_t i;
  4525. if (!PyDict_Check(slotstate)) {
  4526. PyErr_SetString(UnpicklingError,
  4527. "slot state is not a dictionary");
  4528. goto error;
  4529. }
  4530. i = 0;
  4531. while (PyDict_Next(slotstate, &i, &d_key, &d_value)) {
  4532. if (PyObject_SetAttr(inst, d_key, d_value) < 0)
  4533. goto error;
  4534. }
  4535. }
  4536. if (0) {
  4537. error:
  4538. status = -1;
  4539. }
  4540. Py_DECREF(state);
  4541. Py_XDECREF(slotstate);
  4542. return status;
  4543. }
  4544. static int
  4545. load_mark(UnpicklerObject *self)
  4546. {
  4547. /* Note that we split the (pickle.py) stack into two stacks, an
  4548. * object stack and a mark stack. Here we push a mark onto the
  4549. * mark stack.
  4550. */
  4551. if ((self->num_marks + 1) >= self->marks_size) {
  4552. size_t alloc;
  4553. Py_ssize_t *marks;
  4554. /* Use the size_t type to check for overflow. */
  4555. alloc = ((size_t)self->num_marks << 1) + 20;
  4556. if (alloc > (PY_SSIZE_T_MAX / sizeof(Py_ssize_t)) ||
  4557. alloc <= ((size_t)self->num_marks + 1)) {
  4558. PyErr_NoMemory();
  4559. return -1;
  4560. }
  4561. if (self->marks == NULL)
  4562. marks = (Py_ssize_t *) PyMem_Malloc(alloc * sizeof(Py_ssize_t));
  4563. else
  4564. marks = (Py_ssize_t *) PyMem_Realloc(self->marks,
  4565. alloc * sizeof(Py_ssize_t));
  4566. if (marks == NULL) {
  4567. PyErr_NoMemory();
  4568. return -1;
  4569. }
  4570. self->marks = marks;
  4571. self->marks_size = (Py_ssize_t)alloc;
  4572. }
  4573. self->marks[self->num_marks++] = Py_SIZE(self->stack);
  4574. return 0;
  4575. }
  4576. static int
  4577. load_reduce(UnpicklerObject *self)
  4578. {
  4579. PyObject *callable = NULL;
  4580. PyObject *argtup = NULL;
  4581. PyObject *obj = NULL;
  4582. PDATA_POP(self->stack, argtup);
  4583. if (argtup == NULL)
  4584. return -1;
  4585. PDATA_POP(self->stack, callable);
  4586. if (callable) {
  4587. obj = PyObject_CallObject(callable, argtup);
  4588. Py_DECREF(callable);
  4589. }
  4590. Py_DECREF(argtup);
  4591. if (obj == NULL)
  4592. return -1;
  4593. PDATA_PUSH(self->stack, obj, -1);
  4594. return 0;
  4595. }
  4596. /* Just raises an error if we don't know the protocol specified. PROTO
  4597. * is the first opcode for protocols >= 2.
  4598. */
  4599. static int
  4600. load_proto(UnpicklerObject *self)
  4601. {
  4602. char *s;
  4603. int i;
  4604. if (_Unpickler_Read(self, &s, 1) < 0)
  4605. return -1;
  4606. i = (unsigned char)s[0];
  4607. if (i <= HIGHEST_PROTOCOL) {
  4608. self->proto = i;
  4609. return 0;
  4610. }
  4611. PyErr_Format(PyExc_ValueError, "unsupported pickle protocol: %d", i);
  4612. return -1;
  4613. }
  4614. static PyObject *
  4615. load(UnpicklerObject *self)
  4616. {
  4617. PyObject *err;
  4618. PyObject *value = NULL;
  4619. char *s;
  4620. self->num_marks = 0;
  4621. if (Py_SIZE(self->stack))
  4622. Pdata_clear(self->stack, 0);
  4623. /* Convenient macros for the dispatch while-switch loop just below. */
  4624. #define OP(opcode, load_func) \
  4625. case opcode: if (load_func(self) < 0) break; continue;
  4626. #define OP_ARG(opcode, load_func, arg) \
  4627. case opcode: if (load_func(self, (arg)) < 0) break; continue;
  4628. while (1) {
  4629. if (_Unpickler_Read(self, &s, 1) < 0)
  4630. break;
  4631. switch ((enum opcode)s[0]) {
  4632. OP(NONE, load_none)
  4633. OP(BININT, load_binint)
  4634. OP(BININT1, load_binint1)
  4635. OP(BININT2, load_binint2)
  4636. OP(INT, load_int)
  4637. OP(LONG, load_long)
  4638. OP_ARG(LONG1, load_counted_long, 1)
  4639. OP_ARG(LONG4, load_counted_long, 4)
  4640. OP(FLOAT, load_float)
  4641. OP(BINFLOAT, load_binfloat)
  4642. OP(BINBYTES, load_binbytes)
  4643. OP(SHORT_BINBYTES, load_short_binbytes)
  4644. OP(BINSTRING, load_binstring)
  4645. OP(SHORT_BINSTRING, load_short_binstring)
  4646. OP(STRING, load_string)
  4647. OP(UNICODE, load_unicode)
  4648. OP(BINUNICODE, load_binunicode)
  4649. OP_ARG(EMPTY_TUPLE, load_counted_tuple, 0)
  4650. OP_ARG(TUPLE1, load_counted_tuple, 1)
  4651. OP_ARG(TUPLE2, load_counted_tuple, 2)
  4652. OP_ARG(TUPLE3, load_counted_tuple, 3)
  4653. OP(TUPLE, load_tuple)
  4654. OP(EMPTY_LIST, load_empty_list)
  4655. OP(LIST, load_list)
  4656. OP(EMPTY_DICT, load_empty_dict)
  4657. OP(DICT, load_dict)
  4658. OP(OBJ, load_obj)
  4659. OP(INST, load_inst)
  4660. OP(NEWOBJ, load_newobj)
  4661. OP(GLOBAL, load_global)
  4662. OP(APPEND, load_append)
  4663. OP(APPENDS, load_appends)
  4664. OP(BUILD, load_build)
  4665. OP(DUP, load_dup)
  4666. OP(BINGET, load_binget)
  4667. OP(LONG_BINGET, load_long_binget)
  4668. OP(GET, load_get)
  4669. OP(MARK, load_mark)
  4670. OP(BINPUT, load_binput)
  4671. OP(LONG_BINPUT, load_long_binput)
  4672. OP(PUT, load_put)
  4673. OP(POP, load_pop)
  4674. OP(POP_MARK, load_pop_mark)
  4675. OP(SETITEM, load_setitem)
  4676. OP(SETITEMS, load_setitems)
  4677. OP(PERSID, load_persid)
  4678. OP(BINPERSID, load_binpersid)
  4679. OP(REDUCE, load_reduce)
  4680. OP(PROTO, load_proto)
  4681. OP_ARG(EXT1, load_extension, 1)
  4682. OP_ARG(EXT2, load_extension, 2)
  4683. OP_ARG(EXT4, load_extension, 4)
  4684. OP_ARG(NEWTRUE, load_bool, Py_True)
  4685. OP_ARG(NEWFALSE, load_bool, Py_False)
  4686. case STOP:
  4687. break;
  4688. default:
  4689. if (s[0] == '\0')
  4690. PyErr_SetNone(PyExc_EOFError);
  4691. else
  4692. PyErr_Format(UnpicklingError,
  4693. "invalid load key, '%c'.", s[0]);
  4694. return NULL;
  4695. }
  4696. break; /* and we are done! */
  4697. }
  4698. if (_Unpickler_SkipConsumed(self) < 0)
  4699. return NULL;
  4700. /* XXX: It is not clear what this is actually for. */
  4701. if ((err = PyErr_Occurred())) {
  4702. if (err == PyExc_EOFError) {
  4703. PyErr_SetNone(PyExc_EOFError);
  4704. }
  4705. return NULL;
  4706. }
  4707. PDATA_POP(self->stack, value);
  4708. return value;
  4709. }
  4710. PyDoc_STRVAR(Unpickler_load_doc,
  4711. "load() -> object. Load a pickle."
  4712. "\n"
  4713. "Read a pickled object representation from the open file object given in\n"
  4714. "the constructor, and return the reconstituted object hierarchy specified\n"
  4715. "therein.\n");
  4716. static PyObject *
  4717. Unpickler_load(UnpicklerObject *self)
  4718. {
  4719. /* Check whether the Unpickler was initialized correctly. This prevents
  4720. segfaulting if a subclass overridden __init__ with a function that does
  4721. not call Unpickler.__init__(). Here, we simply ensure that self->read
  4722. is not NULL. */
  4723. if (self->read == NULL) {
  4724. PyErr_Format(UnpicklingError,
  4725. "Unpickler.__init__() was not called by %s.__init__()",
  4726. Py_TYPE(self)->tp_name);
  4727. return NULL;
  4728. }
  4729. return load(self);
  4730. }
  4731. /* The name of find_class() is misleading. In newer pickle protocols, this
  4732. function is used for loading any global (i.e., functions), not just
  4733. classes. The name is kept only for backward compatibility. */
  4734. PyDoc_STRVAR(Unpickler_find_class_doc,
  4735. "find_class(module_name, global_name) -> object.\n"
  4736. "\n"
  4737. "Return an object from a specified module, importing the module if\n"
  4738. "necessary. Subclasses may override this method (e.g. to restrict\n"
  4739. "unpickling of arbitrary classes and functions).\n"
  4740. "\n"
  4741. "This method is called whenever a class or a function object is\n"
  4742. "needed. Both arguments passed are str objects.\n");
  4743. static PyObject *
  4744. Unpickler_find_class(UnpicklerObject *self, PyObject *args)
  4745. {
  4746. PyObject *global;
  4747. PyObject *modules_dict;
  4748. PyObject *module;
  4749. PyObject *module_name, *global_name;
  4750. if (!PyArg_UnpackTuple(args, "find_class", 2, 2,
  4751. &module_name, &global_name))
  4752. return NULL;
  4753. /* Try to map the old names used in Python 2.x to the new ones used in
  4754. Python 3.x. We do this only with old pickle protocols and when the
  4755. user has not disabled the feature. */
  4756. if (self->proto < 3 && self->fix_imports) {
  4757. PyObject *key;
  4758. PyObject *item;
  4759. /* Check if the global (i.e., a function or a class) was renamed
  4760. or moved to another module. */
  4761. key = PyTuple_Pack(2, module_name, global_name);
  4762. if (key == NULL)
  4763. return NULL;
  4764. item = PyDict_GetItemWithError(name_mapping_2to3, key);
  4765. Py_DECREF(key);
  4766. if (item) {
  4767. if (!PyTuple_Check(item) || PyTuple_GET_SIZE(item) != 2) {
  4768. PyErr_Format(PyExc_RuntimeError,
  4769. "_compat_pickle.NAME_MAPPING values should be "
  4770. "2-tuples, not %.200s", Py_TYPE(item)->tp_name);
  4771. return NULL;
  4772. }
  4773. module_name = PyTuple_GET_ITEM(item, 0);
  4774. global_name = PyTuple_GET_ITEM(item, 1);
  4775. if (!PyUnicode_Check(module_name) ||
  4776. !PyUnicode_Check(global_name)) {
  4777. PyErr_Format(PyExc_RuntimeError,
  4778. "_compat_pickle.NAME_MAPPING values should be "
  4779. "pairs of str, not (%.200s, %.200s)",
  4780. Py_TYPE(module_name)->tp_name,
  4781. Py_TYPE(global_name)->tp_name);
  4782. return NULL;
  4783. }
  4784. }
  4785. else if (PyErr_Occurred()) {
  4786. return NULL;
  4787. }
  4788. /* Check if the module was renamed. */
  4789. item = PyDict_GetItemWithError(import_mapping_2to3, module_name);
  4790. if (item) {
  4791. if (!PyUnicode_Check(item)) {
  4792. PyErr_Format(PyExc_RuntimeError,
  4793. "_compat_pickle.IMPORT_MAPPING values should be "
  4794. "strings, not %.200s", Py_TYPE(item)->tp_name);
  4795. return NULL;
  4796. }
  4797. module_name = item;
  4798. }
  4799. else if (PyErr_Occurred()) {
  4800. return NULL;
  4801. }
  4802. }
  4803. modules_dict = PySys_GetObject("modules");
  4804. if (modules_dict == NULL) {
  4805. PyErr_SetString(PyExc_RuntimeError, "unable to get sys.modules");
  4806. return NULL;
  4807. }
  4808. module = PyDict_GetItemWithError(modules_dict, module_name);
  4809. if (module == NULL) {
  4810. if (PyErr_Occurred())
  4811. return NULL;
  4812. module = PyImport_Import(module_name);
  4813. if (module == NULL)
  4814. return NULL;
  4815. global = PyObject_GetAttr(module, global_name);
  4816. Py_DECREF(module);
  4817. }
  4818. else {
  4819. global = PyObject_GetAttr(module, global_name);
  4820. }
  4821. return global;
  4822. }
  4823. static struct PyMethodDef Unpickler_methods[] = {
  4824. {"load", (PyCFunction)Unpickler_load, METH_NOARGS,
  4825. Unpickler_load_doc},
  4826. {"find_class", (PyCFunction)Unpickler_find_class, METH_VARARGS,
  4827. Unpickler_find_class_doc},
  4828. {NULL, NULL} /* sentinel */
  4829. };
  4830. static void
  4831. Unpickler_dealloc(UnpicklerObject *self)
  4832. {
  4833. PyObject_GC_UnTrack((PyObject *)self);
  4834. Py_XDECREF(self->readline);
  4835. Py_XDECREF(self->read);
  4836. Py_XDECREF(self->peek);
  4837. Py_XDECREF(self->stack);
  4838. Py_XDECREF(self->pers_func);
  4839. Py_XDECREF(self->arg);
  4840. if (self->buffer.buf != NULL) {
  4841. PyBuffer_Release(&self->buffer);
  4842. self->buffer.buf = NULL;
  4843. }
  4844. _Unpickler_MemoCleanup(self);
  4845. PyMem_Free(self->marks);
  4846. PyMem_Free(self->input_line);
  4847. PyMem_Free(self->encoding);
  4848. PyMem_Free(self->errors);
  4849. Py_TYPE(self)->tp_free((PyObject *)self);
  4850. }
  4851. static int
  4852. Unpickler_traverse(UnpicklerObject *self, visitproc visit, void *arg)
  4853. {
  4854. Py_VISIT(self->readline);
  4855. Py_VISIT(self->read);
  4856. Py_VISIT(self->peek);
  4857. Py_VISIT(self->stack);
  4858. Py_VISIT(self->pers_func);
  4859. Py_VISIT(self->arg);
  4860. return 0;
  4861. }
  4862. static int
  4863. Unpickler_clear(UnpicklerObject *self)
  4864. {
  4865. Py_CLEAR(self->readline);
  4866. Py_CLEAR(self->read);
  4867. Py_CLEAR(self->peek);
  4868. Py_CLEAR(self->stack);
  4869. Py_CLEAR(self->pers_func);
  4870. Py_CLEAR(self->arg);
  4871. if (self->buffer.buf != NULL) {
  4872. PyBuffer_Release(&self->buffer);
  4873. self->buffer.buf = NULL;
  4874. }
  4875. _Unpickler_MemoCleanup(self);
  4876. PyMem_Free(self->marks);
  4877. self->marks = NULL;
  4878. PyMem_Free(self->input_line);
  4879. self->input_line = NULL;
  4880. PyMem_Free(self->encoding);
  4881. self->encoding = NULL;
  4882. PyMem_Free(self->errors);
  4883. self->errors = NULL;
  4884. return 0;
  4885. }
  4886. PyDoc_STRVAR(Unpickler_doc,
  4887. "Unpickler(file, *, encoding='ASCII', errors='strict')"
  4888. "\n"
  4889. "This takes a binary file for reading a pickle data stream.\n"
  4890. "\n"
  4891. "The protocol version of the pickle is detected automatically, so no\n"
  4892. "proto argument is needed.\n"
  4893. "\n"
  4894. "The file-like object must have two methods, a read() method\n"
  4895. "that takes an integer argument, and a readline() method that\n"
  4896. "requires no arguments. Both methods should return bytes.\n"
  4897. "Thus file-like object can be a binary file object opened for\n"
  4898. "reading, a BytesIO object, or any other custom object that\n"
  4899. "meets this interface.\n"
  4900. "\n"
  4901. "Optional keyword arguments are *fix_imports*, *encoding* and *errors*,\n"
  4902. "which are used to control compatiblity support for pickle stream\n"
  4903. "generated by Python 2.x. If *fix_imports* is True, pickle will try to\n"
  4904. "map the old Python 2.x names to the new names used in Python 3.x. The\n"
  4905. "*encoding* and *errors* tell pickle how to decode 8-bit string\n"
  4906. "instances pickled by Python 2.x; these default to 'ASCII' and\n"
  4907. "'strict', respectively.\n");
  4908. static int
  4909. Unpickler_init(UnpicklerObject *self, PyObject *args, PyObject *kwds)
  4910. {
  4911. static char *kwlist[] = {"file", "fix_imports", "encoding", "errors", 0};
  4912. PyObject *file;
  4913. PyObject *fix_imports = Py_True;
  4914. char *encoding = NULL;
  4915. char *errors = NULL;
  4916. _Py_IDENTIFIER(persistent_load);
  4917. /* XXX: That is an horrible error message. But, I don't know how to do
  4918. better... */
  4919. if (Py_SIZE(args) != 1) {
  4920. PyErr_Format(PyExc_TypeError,
  4921. "%s takes exactly one positional argument (%zd given)",
  4922. Py_TYPE(self)->tp_name, Py_SIZE(args));
  4923. return -1;
  4924. }
  4925. /* Arguments parsing needs to be done in the __init__() method to allow
  4926. subclasses to define their own __init__() method, which may (or may
  4927. not) support Unpickler arguments. However, this means we need to be
  4928. extra careful in the other Unpickler methods, since a subclass could
  4929. forget to call Unpickler.__init__() thus breaking our internal
  4930. invariants. */
  4931. if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oss:Unpickler", kwlist,
  4932. &file, &fix_imports, &encoding, &errors))
  4933. return -1;
  4934. /* In case of multiple __init__() calls, clear previous content. */
  4935. if (self->read != NULL)
  4936. (void)Unpickler_clear(self);
  4937. if (_Unpickler_SetInputStream(self, file) < 0)
  4938. return -1;
  4939. if (_Unpickler_SetInputEncoding(self, encoding, errors) < 0)
  4940. return -1;
  4941. self->fix_imports = PyObject_IsTrue(fix_imports);
  4942. if (self->fix_imports == -1)
  4943. return -1;
  4944. if (_PyObject_HasAttrId((PyObject *)self, &PyId_persistent_load)) {
  4945. self->pers_func = _PyObject_GetAttrId((PyObject *)self,
  4946. &PyId_persistent_load);
  4947. if (self->pers_func == NULL)
  4948. return -1;
  4949. }
  4950. else {
  4951. self->pers_func = NULL;
  4952. }
  4953. self->stack = (Pdata *)Pdata_New();
  4954. if (self->stack == NULL)
  4955. return -1;
  4956. self->memo_size = 32;
  4957. self->memo = _Unpickler_NewMemo(self->memo_size);
  4958. if (self->memo == NULL)
  4959. return -1;
  4960. self->arg = NULL;
  4961. self->proto = 0;
  4962. return 0;
  4963. }
  4964. /* Define a proxy object for the Unpickler's internal memo object. This is to
  4965. * avoid breaking code like:
  4966. * unpickler.memo.clear()
  4967. * and
  4968. * unpickler.memo = saved_memo
  4969. * Is this a good idea? Not really, but we don't want to break code that uses
  4970. * it. Note that we don't implement the entire mapping API here. This is
  4971. * intentional, as these should be treated as black-box implementation details.
  4972. *
  4973. * We do, however, have to implement pickling/unpickling support because of
  4974. * real-world code like cvs2svn.
  4975. */
  4976. typedef struct {
  4977. PyObject_HEAD
  4978. UnpicklerObject *unpickler;
  4979. } UnpicklerMemoProxyObject;
  4980. PyDoc_STRVAR(ump_clear_doc,
  4981. "memo.clear() -> None. Remove all items from memo.");
  4982. static PyObject *
  4983. ump_clear(UnpicklerMemoProxyObject *self)
  4984. {
  4985. _Unpickler_MemoCleanup(self->unpickler);
  4986. self->unpickler->memo = _Unpickler_NewMemo(self->unpickler->memo_size);
  4987. if (self->unpickler->memo == NULL)
  4988. return NULL;
  4989. Py_RETURN_NONE;
  4990. }
  4991. PyDoc_STRVAR(ump_copy_doc,
  4992. "memo.copy() -> new_memo. Copy the memo to a new object.");
  4993. static PyObject *
  4994. ump_copy(UnpicklerMemoProxyObject *self)
  4995. {
  4996. Py_ssize_t i;
  4997. PyObject *new_memo = PyDict_New();
  4998. if (new_memo == NULL)
  4999. return NULL;
  5000. for (i = 0; i < self->unpickler->memo_size; i++) {
  5001. int status;
  5002. PyObject *key, *value;
  5003. value = self->unpickler->memo[i];
  5004. if (value == NULL)
  5005. continue;
  5006. key = PyLong_FromSsize_t(i);
  5007. if (key == NULL)
  5008. goto error;
  5009. status = PyDict_SetItem(new_memo, key, value);
  5010. Py_DECREF(key);
  5011. if (status < 0)
  5012. goto error;
  5013. }
  5014. return new_memo;
  5015. error:
  5016. Py_DECREF(new_memo);
  5017. return NULL;
  5018. }
  5019. PyDoc_STRVAR(ump_reduce_doc,
  5020. "memo.__reduce__(). Pickling support.");
  5021. static PyObject *
  5022. ump_reduce(UnpicklerMemoProxyObject *self, PyObject *args)
  5023. {
  5024. PyObject *reduce_value;
  5025. PyObject *constructor_args;
  5026. PyObject *contents = ump_copy(self);
  5027. if (contents == NULL)
  5028. return NULL;
  5029. reduce_value = PyTuple_New(2);
  5030. if (reduce_value == NULL) {
  5031. Py_DECREF(contents);
  5032. return NULL;
  5033. }
  5034. constructor_args = PyTuple_New(1);
  5035. if (constructor_args == NULL) {
  5036. Py_DECREF(contents);
  5037. Py_DECREF(reduce_value);
  5038. return NULL;
  5039. }
  5040. PyTuple_SET_ITEM(constructor_args, 0, contents);
  5041. Py_INCREF((PyObject *)&PyDict_Type);
  5042. PyTuple_SET_ITEM(reduce_value, 0, (PyObject *)&PyDict_Type);
  5043. PyTuple_SET_ITEM(reduce_value, 1, constructor_args);
  5044. return reduce_value;
  5045. }
  5046. static PyMethodDef unpicklerproxy_methods[] = {
  5047. {"clear", (PyCFunction)ump_clear, METH_NOARGS, ump_clear_doc},
  5048. {"copy", (PyCFunction)ump_copy, METH_NOARGS, ump_copy_doc},
  5049. {"__reduce__", (PyCFunction)ump_reduce, METH_VARARGS, ump_reduce_doc},
  5050. {NULL, NULL} /* sentinel */
  5051. };
  5052. static void
  5053. UnpicklerMemoProxy_dealloc(UnpicklerMemoProxyObject *self)
  5054. {
  5055. PyObject_GC_UnTrack(self);
  5056. Py_XDECREF(self->unpickler);
  5057. PyObject_GC_Del((PyObject *)self);
  5058. }
  5059. static int
  5060. UnpicklerMemoProxy_traverse(UnpicklerMemoProxyObject *self,
  5061. visitproc visit, void *arg)
  5062. {
  5063. Py_VISIT(self->unpickler);
  5064. return 0;
  5065. }
  5066. static int
  5067. UnpicklerMemoProxy_clear(UnpicklerMemoProxyObject *self)
  5068. {
  5069. Py_CLEAR(self->unpickler);
  5070. return 0;
  5071. }
  5072. static PyTypeObject UnpicklerMemoProxyType = {
  5073. PyVarObject_HEAD_INIT(NULL, 0)
  5074. "_pickle.UnpicklerMemoProxy", /*tp_name*/
  5075. sizeof(UnpicklerMemoProxyObject), /*tp_basicsize*/
  5076. 0,
  5077. (destructor)UnpicklerMemoProxy_dealloc, /* tp_dealloc */
  5078. 0, /* tp_print */
  5079. 0, /* tp_getattr */
  5080. 0, /* tp_setattr */
  5081. 0, /* tp_compare */
  5082. 0, /* tp_repr */
  5083. 0, /* tp_as_number */
  5084. 0, /* tp_as_sequence */
  5085. 0, /* tp_as_mapping */
  5086. PyObject_HashNotImplemented, /* tp_hash */
  5087. 0, /* tp_call */
  5088. 0, /* tp_str */
  5089. PyObject_GenericGetAttr, /* tp_getattro */
  5090. PyObject_GenericSetAttr, /* tp_setattro */
  5091. 0, /* tp_as_buffer */
  5092. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
  5093. 0, /* tp_doc */
  5094. (traverseproc)UnpicklerMemoProxy_traverse, /* tp_traverse */
  5095. (inquiry)UnpicklerMemoProxy_clear, /* tp_clear */
  5096. 0, /* tp_richcompare */
  5097. 0, /* tp_weaklistoffset */
  5098. 0, /* tp_iter */
  5099. 0, /* tp_iternext */
  5100. unpicklerproxy_methods, /* tp_methods */
  5101. };
  5102. static PyObject *
  5103. UnpicklerMemoProxy_New(UnpicklerObject *unpickler)
  5104. {
  5105. UnpicklerMemoProxyObject *self;
  5106. self = PyObject_GC_New(UnpicklerMemoProxyObject,
  5107. &UnpicklerMemoProxyType);
  5108. if (self == NULL)
  5109. return NULL;
  5110. Py_INCREF(unpickler);
  5111. self->unpickler = unpickler;
  5112. PyObject_GC_Track(self);
  5113. return (PyObject *)self;
  5114. }
  5115. /*****************************************************************************/
  5116. static PyObject *
  5117. Unpickler_get_memo(UnpicklerObject *self)
  5118. {
  5119. return UnpicklerMemoProxy_New(self);
  5120. }
  5121. static int
  5122. Unpickler_set_memo(UnpicklerObject *self, PyObject *obj)
  5123. {
  5124. PyObject **new_memo;
  5125. Py_ssize_t new_memo_size = 0;
  5126. Py_ssize_t i;
  5127. if (obj == NULL) {
  5128. PyErr_SetString(PyExc_TypeError,
  5129. "attribute deletion is not supported");
  5130. return -1;
  5131. }
  5132. if (Py_TYPE(obj) == &UnpicklerMemoProxyType) {
  5133. UnpicklerObject *unpickler =
  5134. ((UnpicklerMemoProxyObject *)obj)->unpickler;
  5135. new_memo_size = unpickler->memo_size;
  5136. new_memo = _Unpickler_NewMemo(new_memo_size);
  5137. if (new_memo == NULL)
  5138. return -1;
  5139. for (i = 0; i < new_memo_size; i++) {
  5140. Py_XINCREF(unpickler->memo[i]);
  5141. new_memo[i] = unpickler->memo[i];
  5142. }
  5143. }
  5144. else if (PyDict_Check(obj)) {
  5145. Py_ssize_t i = 0;
  5146. PyObject *key, *value;
  5147. new_memo_size = PyDict_Size(obj);
  5148. new_memo = _Unpickler_NewMemo(new_memo_size);
  5149. if (new_memo == NULL)
  5150. return -1;
  5151. while (PyDict_Next(obj, &i, &key, &value)) {
  5152. Py_ssize_t idx;
  5153. if (!PyLong_Check(key)) {
  5154. PyErr_SetString(PyExc_TypeError,
  5155. "memo key must be integers");
  5156. goto error;
  5157. }
  5158. idx = PyLong_AsSsize_t(key);
  5159. if (idx == -1 && PyErr_Occurred())
  5160. goto error;
  5161. if (idx < 0) {
  5162. PyErr_SetString(PyExc_ValueError,
  5163. "memo key must be positive integers.");
  5164. goto error;
  5165. }
  5166. if (_Unpickler_MemoPut(self, idx, value) < 0)
  5167. goto error;
  5168. }
  5169. }
  5170. else {
  5171. PyErr_Format(PyExc_TypeError,
  5172. "'memo' attribute must be an UnpicklerMemoProxy object"
  5173. "or dict, not %.200s", Py_TYPE(obj)->tp_name);
  5174. return -1;
  5175. }
  5176. _Unpickler_MemoCleanup(self);
  5177. self->memo_size = new_memo_size;
  5178. self->memo = new_memo;
  5179. return 0;
  5180. error:
  5181. if (new_memo_size) {
  5182. i = new_memo_size;
  5183. while (--i >= 0) {
  5184. Py_XDECREF(new_memo[i]);
  5185. }
  5186. PyMem_FREE(new_memo);
  5187. }
  5188. return -1;
  5189. }
  5190. static PyObject *
  5191. Unpickler_get_persload(UnpicklerObject *self)
  5192. {
  5193. if (self->pers_func == NULL)
  5194. PyErr_SetString(PyExc_AttributeError, "persistent_load");
  5195. else
  5196. Py_INCREF(self->pers_func);
  5197. return self->pers_func;
  5198. }
  5199. static int
  5200. Unpickler_set_persload(UnpicklerObject *self, PyObject *value)
  5201. {
  5202. PyObject *tmp;
  5203. if (value == NULL) {
  5204. PyErr_SetString(PyExc_TypeError,
  5205. "attribute deletion is not supported");
  5206. return -1;
  5207. }
  5208. if (!PyCallable_Check(value)) {
  5209. PyErr_SetString(PyExc_TypeError,
  5210. "persistent_load must be a callable taking "
  5211. "one argument");
  5212. return -1;
  5213. }
  5214. tmp = self->pers_func;
  5215. Py_INCREF(value);
  5216. self->pers_func = value;
  5217. Py_XDECREF(tmp); /* self->pers_func can be NULL, so be careful. */
  5218. return 0;
  5219. }
  5220. static PyGetSetDef Unpickler_getsets[] = {
  5221. {"memo", (getter)Unpickler_get_memo, (setter)Unpickler_set_memo},
  5222. {"persistent_load", (getter)Unpickler_get_persload,
  5223. (setter)Unpickler_set_persload},
  5224. {NULL}
  5225. };
  5226. static PyTypeObject Unpickler_Type = {
  5227. PyVarObject_HEAD_INIT(NULL, 0)
  5228. "_pickle.Unpickler", /*tp_name*/
  5229. sizeof(UnpicklerObject), /*tp_basicsize*/
  5230. 0, /*tp_itemsize*/
  5231. (destructor)Unpickler_dealloc, /*tp_dealloc*/
  5232. 0, /*tp_print*/
  5233. 0, /*tp_getattr*/
  5234. 0, /*tp_setattr*/
  5235. 0, /*tp_reserved*/
  5236. 0, /*tp_repr*/
  5237. 0, /*tp_as_number*/
  5238. 0, /*tp_as_sequence*/
  5239. 0, /*tp_as_mapping*/
  5240. 0, /*tp_hash*/
  5241. 0, /*tp_call*/
  5242. 0, /*tp_str*/
  5243. 0, /*tp_getattro*/
  5244. 0, /*tp_setattro*/
  5245. 0, /*tp_as_buffer*/
  5246. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
  5247. Unpickler_doc, /*tp_doc*/
  5248. (traverseproc)Unpickler_traverse, /*tp_traverse*/
  5249. (inquiry)Unpickler_clear, /*tp_clear*/
  5250. 0, /*tp_richcompare*/
  5251. 0, /*tp_weaklistoffset*/
  5252. 0, /*tp_iter*/
  5253. 0, /*tp_iternext*/
  5254. Unpickler_methods, /*tp_methods*/
  5255. 0, /*tp_members*/
  5256. Unpickler_getsets, /*tp_getset*/
  5257. 0, /*tp_base*/
  5258. 0, /*tp_dict*/
  5259. 0, /*tp_descr_get*/
  5260. 0, /*tp_descr_set*/
  5261. 0, /*tp_dictoffset*/
  5262. (initproc)Unpickler_init, /*tp_init*/
  5263. PyType_GenericAlloc, /*tp_alloc*/
  5264. PyType_GenericNew, /*tp_new*/
  5265. PyObject_GC_Del, /*tp_free*/
  5266. 0, /*tp_is_gc*/
  5267. };
  5268. PyDoc_STRVAR(pickle_dump_doc,
  5269. "dump(obj, file, protocol=None, *, fix_imports=True) -> None\n"
  5270. "\n"
  5271. "Write a pickled representation of obj to the open file object file. This\n"
  5272. "is equivalent to ``Pickler(file, protocol).dump(obj)``, but may be more\n"
  5273. "efficient.\n"
  5274. "\n"
  5275. "The optional protocol argument tells the pickler to use the given protocol;\n"
  5276. "supported protocols are 0, 1, 2, 3. The default protocol is 3; a\n"
  5277. "backward-incompatible protocol designed for Python 3.0.\n"
  5278. "\n"
  5279. "Specifying a negative protocol version selects the highest protocol version\n"
  5280. "supported. The higher the protocol used, the more recent the version of\n"
  5281. "Python needed to read the pickle produced.\n"
  5282. "\n"
  5283. "The file argument must have a write() method that accepts a single bytes\n"
  5284. "argument. It can thus be a file object opened for binary writing, a\n"
  5285. "io.BytesIO instance, or any other custom object that meets this interface.\n"
  5286. "\n"
  5287. "If fix_imports is True and protocol is less than 3, pickle will try to\n"
  5288. "map the new Python 3.x names to the old module names used in Python 2.x,\n"
  5289. "so that the pickle data stream is readable with Python 2.x.\n");
  5290. static PyObject *
  5291. pickle_dump(PyObject *self, PyObject *args, PyObject *kwds)
  5292. {
  5293. static char *kwlist[] = {"obj", "file", "protocol", "fix_imports", 0};
  5294. PyObject *obj;
  5295. PyObject *file;
  5296. PyObject *proto = NULL;
  5297. PyObject *fix_imports = Py_True;
  5298. PicklerObject *pickler;
  5299. /* fix_imports is a keyword-only argument. */
  5300. if (Py_SIZE(args) > 3) {
  5301. PyErr_Format(PyExc_TypeError,
  5302. "pickle.dump() takes at most 3 positional "
  5303. "argument (%zd given)", Py_SIZE(args));
  5304. return NULL;
  5305. }
  5306. if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO|OO:dump", kwlist,
  5307. &obj, &file, &proto, &fix_imports))
  5308. return NULL;
  5309. pickler = _Pickler_New();
  5310. if (pickler == NULL)
  5311. return NULL;
  5312. if (_Pickler_SetProtocol(pickler, proto, fix_imports) < 0)
  5313. goto error;
  5314. if (_Pickler_SetOutputStream(pickler, file) < 0)
  5315. goto error;
  5316. if (dump(pickler, obj) < 0)
  5317. goto error;
  5318. if (_Pickler_FlushToFile(pickler) < 0)
  5319. goto error;
  5320. Py_DECREF(pickler);
  5321. Py_RETURN_NONE;
  5322. error:
  5323. Py_XDECREF(pickler);
  5324. return NULL;
  5325. }
  5326. PyDoc_STRVAR(pickle_dumps_doc,
  5327. "dumps(obj, protocol=None, *, fix_imports=True) -> bytes\n"
  5328. "\n"
  5329. "Return the pickled representation of the object as a bytes\n"
  5330. "object, instead of writing it to a file.\n"
  5331. "\n"
  5332. "The optional protocol argument tells the pickler to use the given protocol;\n"
  5333. "supported protocols are 0, 1, 2, 3. The default protocol is 3; a\n"
  5334. "backward-incompatible protocol designed for Python 3.0.\n"
  5335. "\n"
  5336. "Specifying a negative protocol version selects the highest protocol version\n"
  5337. "supported. The higher the protocol used, the more recent the version of\n"
  5338. "Python needed to read the pickle produced.\n"
  5339. "\n"
  5340. "If fix_imports is True and *protocol* is less than 3, pickle will try to\n"
  5341. "map the new Python 3.x names to the old module names used in Python 2.x,\n"
  5342. "so that the pickle data stream is readable with Python 2.x.\n");
  5343. static PyObject *
  5344. pickle_dumps(PyObject *self, PyObject *args, PyObject *kwds)
  5345. {
  5346. static char *kwlist[] = {"obj", "protocol", "fix_imports", 0};
  5347. PyObject *obj;
  5348. PyObject *proto = NULL;
  5349. PyObject *result;
  5350. PyObject *fix_imports = Py_True;
  5351. PicklerObject *pickler;
  5352. /* fix_imports is a keyword-only argument. */
  5353. if (Py_SIZE(args) > 2) {
  5354. PyErr_Format(PyExc_TypeError,
  5355. "pickle.dumps() takes at most 2 positional "
  5356. "argument (%zd given)", Py_SIZE(args));
  5357. return NULL;
  5358. }
  5359. if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OO:dumps", kwlist,
  5360. &obj, &proto, &fix_imports))
  5361. return NULL;
  5362. pickler = _Pickler_New();
  5363. if (pickler == NULL)
  5364. return NULL;
  5365. if (_Pickler_SetProtocol(pickler, proto, fix_imports) < 0)
  5366. goto error;
  5367. if (dump(pickler, obj) < 0)
  5368. goto error;
  5369. result = _Pickler_GetString(pickler);
  5370. Py_DECREF(pickler);
  5371. return result;
  5372. error:
  5373. Py_XDECREF(pickler);
  5374. return NULL;
  5375. }
  5376. PyDoc_STRVAR(pickle_load_doc,
  5377. "load(file, *, fix_imports=True, encoding='ASCII', errors='strict') -> object\n"
  5378. "\n"
  5379. "Read a pickled object representation from the open file object file and\n"
  5380. "return the reconstituted object hierarchy specified therein. This is\n"
  5381. "equivalent to ``Unpickler(file).load()``, but may be more efficient.\n"
  5382. "\n"
  5383. "The protocol version of the pickle is detected automatically, so no protocol\n"
  5384. "argument is needed. Bytes past the pickled object's representation are\n"
  5385. "ignored.\n"
  5386. "\n"
  5387. "The argument file must have two methods, a read() method that takes an\n"
  5388. "integer argument, and a readline() method that requires no arguments. Both\n"
  5389. "methods should return bytes. Thus *file* can be a binary file object opened\n"
  5390. "for reading, a BytesIO object, or any other custom object that meets this\n"
  5391. "interface.\n"
  5392. "\n"
  5393. "Optional keyword arguments are fix_imports, encoding and errors,\n"
  5394. "which are used to control compatiblity support for pickle stream generated\n"
  5395. "by Python 2.x. If fix_imports is True, pickle will try to map the old\n"
  5396. "Python 2.x names to the new names used in Python 3.x. The encoding and\n"
  5397. "errors tell pickle how to decode 8-bit string instances pickled by Python\n"
  5398. "2.x; these default to 'ASCII' and 'strict', respectively.\n");
  5399. static PyObject *
  5400. pickle_load(PyObject *self, PyObject *args, PyObject *kwds)
  5401. {
  5402. static char *kwlist[] = {"file", "fix_imports", "encoding", "errors", 0};
  5403. PyObject *file;
  5404. PyObject *fix_imports = Py_True;
  5405. PyObject *result;
  5406. char *encoding = NULL;
  5407. char *errors = NULL;
  5408. UnpicklerObject *unpickler;
  5409. /* fix_imports, encoding and errors are a keyword-only argument. */
  5410. if (Py_SIZE(args) != 1) {
  5411. PyErr_Format(PyExc_TypeError,
  5412. "pickle.load() takes exactly one positional "
  5413. "argument (%zd given)", Py_SIZE(args));
  5414. return NULL;
  5415. }
  5416. if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oss:load", kwlist,
  5417. &file, &fix_imports, &encoding, &errors))
  5418. return NULL;
  5419. unpickler = _Unpickler_New();
  5420. if (unpickler == NULL)
  5421. return NULL;
  5422. if (_Unpickler_SetInputStream(unpickler, file) < 0)
  5423. goto error;
  5424. if (_Unpickler_SetInputEncoding(unpickler, encoding, errors) < 0)
  5425. goto error;
  5426. unpickler->fix_imports = PyObject_IsTrue(fix_imports);
  5427. if (unpickler->fix_imports == -1)
  5428. goto error;
  5429. result = load(unpickler);
  5430. Py_DECREF(unpickler);
  5431. return result;
  5432. error:
  5433. Py_XDECREF(unpickler);
  5434. return NULL;
  5435. }
  5436. PyDoc_STRVAR(pickle_loads_doc,
  5437. "loads(input, *, fix_imports=True, encoding='ASCII', errors='strict') -> object\n"
  5438. "\n"
  5439. "Read a pickled object hierarchy from a bytes object and return the\n"
  5440. "reconstituted object hierarchy specified therein\n"
  5441. "\n"
  5442. "The protocol version of the pickle is detected automatically, so no protocol\n"
  5443. "argument is needed. Bytes past the pickled object's representation are\n"
  5444. "ignored.\n"
  5445. "\n"
  5446. "Optional keyword arguments are fix_imports, encoding and errors, which\n"
  5447. "are used to control compatiblity support for pickle stream generated\n"
  5448. "by Python 2.x. If fix_imports is True, pickle will try to map the old\n"
  5449. "Python 2.x names to the new names used in Python 3.x. The encoding and\n"
  5450. "errors tell pickle how to decode 8-bit string instances pickled by Python\n"
  5451. "2.x; these default to 'ASCII' and 'strict', respectively.\n");
  5452. static PyObject *
  5453. pickle_loads(PyObject *self, PyObject *args, PyObject *kwds)
  5454. {
  5455. static char *kwlist[] = {"input", "fix_imports", "encoding", "errors", 0};
  5456. PyObject *input;
  5457. PyObject *fix_imports = Py_True;
  5458. PyObject *result;
  5459. char *encoding = NULL;
  5460. char *errors = NULL;
  5461. UnpicklerObject *unpickler;
  5462. /* fix_imports, encoding and errors are a keyword-only argument. */
  5463. if (Py_SIZE(args) != 1) {
  5464. PyErr_Format(PyExc_TypeError,
  5465. "pickle.loads() takes exactly one positional "
  5466. "argument (%zd given)", Py_SIZE(args));
  5467. return NULL;
  5468. }
  5469. if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|Oss:loads", kwlist,
  5470. &input, &fix_imports, &encoding, &errors))
  5471. return NULL;
  5472. unpickler = _Unpickler_New();
  5473. if (unpickler == NULL)
  5474. return NULL;
  5475. if (_Unpickler_SetStringInput(unpickler, input) < 0)
  5476. goto error;
  5477. if (_Unpickler_SetInputEncoding(unpickler, encoding, errors) < 0)
  5478. goto error;
  5479. unpickler->fix_imports = PyObject_IsTrue(fix_imports);
  5480. if (unpickler->fix_imports == -1)
  5481. goto error;
  5482. result = load(unpickler);
  5483. Py_DECREF(unpickler);
  5484. return result;
  5485. error:
  5486. Py_XDECREF(unpickler);
  5487. return NULL;
  5488. }
  5489. static struct PyMethodDef pickle_methods[] = {
  5490. {"dump", (PyCFunction)pickle_dump, METH_VARARGS|METH_KEYWORDS,
  5491. pickle_dump_doc},
  5492. {"dumps", (PyCFunction)pickle_dumps, METH_VARARGS|METH_KEYWORDS,
  5493. pickle_dumps_doc},
  5494. {"load", (PyCFunction)pickle_load, METH_VARARGS|METH_KEYWORDS,
  5495. pickle_load_doc},
  5496. {"loads", (PyCFunction)pickle_loads, METH_VARARGS|METH_KEYWORDS,
  5497. pickle_loads_doc},
  5498. {NULL, NULL} /* sentinel */
  5499. };
  5500. static int
  5501. initmodule(void)
  5502. {
  5503. PyObject *copyreg = NULL;
  5504. PyObject *compat_pickle = NULL;
  5505. /* XXX: We should ensure that the types of the dictionaries imported are
  5506. exactly PyDict objects. Otherwise, it is possible to crash the pickle
  5507. since we use the PyDict API directly to access these dictionaries. */
  5508. copyreg = PyImport_ImportModule("copyreg");
  5509. if (!copyreg)
  5510. goto error;
  5511. dispatch_table = PyObject_GetAttrString(copyreg, "dispatch_table");
  5512. if (!dispatch_table)
  5513. goto error;
  5514. extension_registry = \
  5515. PyObject_GetAttrString(copyreg, "_extension_registry");
  5516. if (!extension_registry)
  5517. goto error;
  5518. inverted_registry = PyObject_GetAttrString(copyreg, "_inverted_registry");
  5519. if (!inverted_registry)
  5520. goto error;
  5521. extension_cache = PyObject_GetAttrString(copyreg, "_extension_cache");
  5522. if (!extension_cache)
  5523. goto error;
  5524. Py_CLEAR(copyreg);
  5525. /* Load the 2.x -> 3.x stdlib module mapping tables */
  5526. compat_pickle = PyImport_ImportModule("_compat_pickle");
  5527. if (!compat_pickle)
  5528. goto error;
  5529. name_mapping_2to3 = PyObject_GetAttrString(compat_pickle, "NAME_MAPPING");
  5530. if (!name_mapping_2to3)
  5531. goto error;
  5532. if (!PyDict_CheckExact(name_mapping_2to3)) {
  5533. PyErr_Format(PyExc_RuntimeError,
  5534. "_compat_pickle.NAME_MAPPING should be a dict, not %.200s",
  5535. Py_TYPE(name_mapping_2to3)->tp_name);
  5536. goto error;
  5537. }
  5538. import_mapping_2to3 = PyObject_GetAttrString(compat_pickle,
  5539. "IMPORT_MAPPING");
  5540. if (!import_mapping_2to3)
  5541. goto error;
  5542. if (!PyDict_CheckExact(import_mapping_2to3)) {
  5543. PyErr_Format(PyExc_RuntimeError,
  5544. "_compat_pickle.IMPORT_MAPPING should be a dict, "
  5545. "not %.200s", Py_TYPE(import_mapping_2to3)->tp_name);
  5546. goto error;
  5547. }
  5548. /* ... and the 3.x -> 2.x mapping tables */
  5549. name_mapping_3to2 = PyObject_GetAttrString(compat_pickle,
  5550. "REVERSE_NAME_MAPPING");
  5551. if (!name_mapping_3to2)
  5552. goto error;
  5553. if (!PyDict_CheckExact(name_mapping_3to2)) {
  5554. PyErr_Format(PyExc_RuntimeError,
  5555. "_compat_pickle.REVERSE_NAME_MAPPING should be a dict, "
  5556. "not %.200s", Py_TYPE(name_mapping_3to2)->tp_name);
  5557. goto error;
  5558. }
  5559. import_mapping_3to2 = PyObject_GetAttrString(compat_pickle,
  5560. "REVERSE_IMPORT_MAPPING");
  5561. if (!import_mapping_3to2)
  5562. goto error;
  5563. if (!PyDict_CheckExact(import_mapping_3to2)) {
  5564. PyErr_Format(PyExc_RuntimeError,
  5565. "_compat_pickle.REVERSE_IMPORT_MAPPING should be a dict, "
  5566. "not %.200s", Py_TYPE(import_mapping_3to2)->tp_name);
  5567. goto error;
  5568. }
  5569. Py_CLEAR(compat_pickle);
  5570. empty_tuple = PyTuple_New(0);
  5571. if (empty_tuple == NULL)
  5572. goto error;
  5573. two_tuple = PyTuple_New(2);
  5574. if (two_tuple == NULL)
  5575. goto error;
  5576. /* We use this temp container with no regard to refcounts, or to
  5577. * keeping containees alive. Exempt from GC, because we don't
  5578. * want anything looking at two_tuple() by magic.
  5579. */
  5580. PyObject_GC_UnTrack(two_tuple);
  5581. return 0;
  5582. error:
  5583. Py_CLEAR(copyreg);
  5584. Py_CLEAR(dispatch_table);
  5585. Py_CLEAR(extension_registry);
  5586. Py_CLEAR(inverted_registry);
  5587. Py_CLEAR(extension_cache);
  5588. Py_CLEAR(compat_pickle);
  5589. Py_CLEAR(name_mapping_2to3);
  5590. Py_CLEAR(import_mapping_2to3);
  5591. Py_CLEAR(name_mapping_3to2);
  5592. Py_CLEAR(import_mapping_3to2);
  5593. Py_CLEAR(empty_tuple);
  5594. Py_CLEAR(two_tuple);
  5595. return -1;
  5596. }
  5597. static struct PyModuleDef _picklemodule = {
  5598. PyModuleDef_HEAD_INIT,
  5599. "_pickle",
  5600. pickle_module_doc,
  5601. -1,
  5602. pickle_methods,
  5603. NULL,
  5604. NULL,
  5605. NULL,
  5606. NULL
  5607. };
  5608. PyMODINIT_FUNC
  5609. PyInit__pickle(void)
  5610. {
  5611. PyObject *m;
  5612. if (PyType_Ready(&Unpickler_Type) < 0)
  5613. return NULL;
  5614. if (PyType_Ready(&Pickler_Type) < 0)
  5615. return NULL;
  5616. if (PyType_Ready(&Pdata_Type) < 0)
  5617. return NULL;
  5618. if (PyType_Ready(&PicklerMemoProxyType) < 0)
  5619. return NULL;
  5620. if (PyType_Ready(&UnpicklerMemoProxyType) < 0)
  5621. return NULL;
  5622. /* Create the module and add the functions. */
  5623. m = PyModule_Create(&_picklemodule);
  5624. if (m == NULL)
  5625. return NULL;
  5626. Py_INCREF(&Pickler_Type);
  5627. if (PyModule_AddObject(m, "Pickler", (PyObject *)&Pickler_Type) < 0)
  5628. return NULL;
  5629. Py_INCREF(&Unpickler_Type);
  5630. if (PyModule_AddObject(m, "Unpickler", (PyObject *)&Unpickler_Type) < 0)
  5631. return NULL;
  5632. /* Initialize the exceptions. */
  5633. PickleError = PyErr_NewException("_pickle.PickleError", NULL, NULL);
  5634. if (PickleError == NULL)
  5635. return NULL;
  5636. PicklingError = \
  5637. PyErr_NewException("_pickle.PicklingError", PickleError, NULL);
  5638. if (PicklingError == NULL)
  5639. return NULL;
  5640. UnpicklingError = \
  5641. PyErr_NewException("_pickle.UnpicklingError", PickleError, NULL);
  5642. if (UnpicklingError == NULL)
  5643. return NULL;
  5644. if (PyModule_AddObject(m, "PickleError", PickleError) < 0)
  5645. return NULL;
  5646. if (PyModule_AddObject(m, "PicklingError", PicklingError) < 0)
  5647. return NULL;
  5648. if (PyModule_AddObject(m, "UnpicklingError", UnpicklingError) < 0)
  5649. return NULL;
  5650. if (initmodule() < 0)
  5651. return NULL;
  5652. return m;
  5653. }