This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Fix a bug in the recursion depth check in store_lhash().
[perl5.git] / dist / Storable / Storable.xs
1 /* -*-  c-basic-offset: 4 -*-
2  *
3  *  Fast store and retrieve mechanism.
4  *
5  *  Copyright (c) 1995-2000, Raphael Manfredi
6  *  Copyright (c) 2016, 2017 cPanel Inc
7  *  Copyright (c) 2017 Reini Urban
8  *
9  *  You may redistribute only under the same terms as Perl 5, as specified
10  *  in the README file that comes with the distribution.
11  *
12  */
13
14 #define PERL_NO_GET_CONTEXT     /* we want efficiency */
15 #include <EXTERN.h>
16 #include <perl.h>
17 #include <XSUB.h>
18
19 #ifndef PERL_VERSION_LT
20 # if !defined(PERL_VERSION) || !defined(PERL_REVISION) || ( PERL_REVISION == 5 && ( PERL_VERSION < 10 || (PERL_VERSION == 10 && PERL_SUBVERSION < 1) ) )
21 #   define NEED_PL_parser
22 #   define NEED_sv_2pv_flags
23 #   define NEED_load_module
24 #   define NEED_vload_module
25 #   define NEED_newCONSTSUB
26 #   define NEED_newSVpvn_flags
27 #   define NEED_newRV_noinc
28 # endif
29 #include "ppport.h"             /* handle old perls */
30 #endif
31
32 #ifdef DEBUGGING
33 #define DEBUGME /* Debug mode, turns assertions on as well */
34 #define DASSERT /* Assertion mode */
35 #endif
36
37 /*
38  * Earlier versions of perl might be used, we can't assume they have the latest!
39  */
40
41 /* perl <= 5.8.2 needs this */
42 #ifndef SvIsCOW
43 # define SvIsCOW(sv) 0
44 #endif
45
46 #ifndef HvRITER_set
47 #  define HvRITER_set(hv,r)     (HvRITER(hv) = r)
48 #endif
49 #ifndef HvEITER_set
50 #  define HvEITER_set(hv,r)     (HvEITER(hv) = r)
51 #endif
52
53 #ifndef HvRITER_get
54 #  define HvRITER_get           HvRITER
55 #endif
56 #ifndef HvEITER_get
57 #  define HvEITER_get           HvEITER
58 #endif
59
60 #ifndef HvPLACEHOLDERS_get
61 #  define HvPLACEHOLDERS_get    HvPLACEHOLDERS
62 #endif
63
64 #ifndef HvTOTALKEYS
65 #  define HvTOTALKEYS(hv)       HvKEYS(hv)
66 #endif
67 /* 5.6 */
68 #ifndef HvUSEDKEYS
69 #  define HvUSEDKEYS(hv)        HvKEYS(hv)
70 #endif
71
72 #ifdef SVf_IsCOW
73 #  define SvTRULYREADONLY(sv)   SvREADONLY(sv)
74 #else
75 #  define SvTRULYREADONLY(sv)   (SvREADONLY(sv) && !SvIsCOW(sv))
76 #endif
77
78 #ifndef strEQc
79 #  define strEQc(s,c) memEQ(s, ("" c ""), sizeof(c))
80 #endif
81
82 #if defined(HAS_FLOCK) || defined(FCNTL_CAN_LOCK) && defined(HAS_LOCKF)
83 #define CAN_FLOCK &PL_sv_yes
84 #else
85 #define CAN_FLOCK &PL_sv_no
86 #endif
87
88 #ifdef DEBUGME
89
90 #ifndef DASSERT
91 #define DASSERT
92 #endif
93
94 /*
95  * TRACEME() will only output things when the $Storable::DEBUGME is true,
96  * using the value traceme cached in the context.
97  *
98  *
99  * TRACEMED() directly looks at the variable, for use before traceme has been
100  * updated.
101  */
102
103 #define TRACEME(x)                                            \
104     STMT_START {                                              \
105         if (cxt->traceme)                                     \
106             { PerlIO_stdoutf x; PerlIO_stdoutf("\n"); }       \
107     } STMT_END
108
109 #define TRACEMED(x)                                           \
110     STMT_START {                                              \
111         if (SvTRUE(get_sv("Storable::DEBUGME", GV_ADD)))      \
112             { PerlIO_stdoutf x; PerlIO_stdoutf("\n"); }       \
113     } STMT_END
114
115 #define INIT_TRACEME                                                    \
116     STMT_START {                                                        \
117         cxt->traceme = SvTRUE(get_sv("Storable::DEBUGME", GV_ADD));     \
118     } STMT_END
119
120 #else
121 #define TRACEME(x)
122 #define TRACEMED(x)
123 #define INIT_TRACEME
124 #endif  /* DEBUGME */
125
126 #ifdef DASSERT
127 #define ASSERT(x,y)                                              \
128     STMT_START {                                                 \
129         if (!(x)) {                                              \
130             PerlIO_stdoutf("ASSERT FAILED (\"%s\", line %d): ",  \
131                            __FILE__, (int)__LINE__);             \
132             PerlIO_stdoutf y; PerlIO_stdoutf("\n");              \
133         }                                                        \
134     } STMT_END
135 #else
136 #define ASSERT(x,y)
137 #endif
138
139 /*
140  * Type markers.
141  */
142
143 #define C(x) ((char) (x))       /* For markers with dynamic retrieval handling */
144
145 #define SX_OBJECT       C(0)    /* Already stored object */
146 #define SX_LSCALAR      C(1)    /* Scalar (large binary) follows (length, data) */
147 #define SX_ARRAY        C(2)    /* Array forthcoming (size, item list) */
148 #define SX_HASH         C(3)    /* Hash forthcoming (size, key/value pair list) */
149 #define SX_REF          C(4)    /* Reference to object forthcoming */
150 #define SX_UNDEF        C(5)    /* Undefined scalar */
151 #define SX_INTEGER      C(6)    /* Integer forthcoming */
152 #define SX_DOUBLE       C(7)    /* Double forthcoming */
153 #define SX_BYTE         C(8)    /* (signed) byte forthcoming */
154 #define SX_NETINT       C(9)    /* Integer in network order forthcoming */
155 #define SX_SCALAR       C(10)   /* Scalar (binary, small) follows (length, data) */
156 #define SX_TIED_ARRAY   C(11)   /* Tied array forthcoming */
157 #define SX_TIED_HASH    C(12)   /* Tied hash forthcoming */
158 #define SX_TIED_SCALAR  C(13)   /* Tied scalar forthcoming */
159 #define SX_SV_UNDEF     C(14)   /* Perl's immortal PL_sv_undef */
160 #define SX_SV_YES       C(15)   /* Perl's immortal PL_sv_yes */
161 #define SX_SV_NO        C(16)   /* Perl's immortal PL_sv_no */
162 #define SX_BLESS        C(17)   /* Object is blessed */
163 #define SX_IX_BLESS     C(18)   /* Object is blessed, classname given by index */
164 #define SX_HOOK         C(19)   /* Stored via hook, user-defined */
165 #define SX_OVERLOAD     C(20)   /* Overloaded reference */
166 #define SX_TIED_KEY     C(21)   /* Tied magic key forthcoming */
167 #define SX_TIED_IDX     C(22)   /* Tied magic index forthcoming */
168 #define SX_UTF8STR      C(23)   /* UTF-8 string forthcoming (small) */
169 #define SX_LUTF8STR     C(24)   /* UTF-8 string forthcoming (large) */
170 #define SX_FLAG_HASH    C(25)   /* Hash with flags forthcoming (size, flags, key/flags/value triplet list) */
171 #define SX_CODE         C(26)   /* Code references as perl source code */
172 #define SX_WEAKREF      C(27)   /* Weak reference to object forthcoming */
173 #define SX_WEAKOVERLOAD C(28)   /* Overloaded weak reference */
174 #define SX_VSTRING      C(29)   /* vstring forthcoming (small) */
175 #define SX_LVSTRING     C(30)   /* vstring forthcoming (large) */
176 #define SX_SVUNDEF_ELEM C(31)   /* array element set to &PL_sv_undef */
177 #define SX_REGEXP       C(32)   /* Regexp */
178 #define SX_LOBJECT      C(33)   /* Large object: string, array or hash (size >2G) */
179 #define SX_LAST         C(34)   /* invalid. marker only */
180
181 /*
182  * Those are only used to retrieve "old" pre-0.6 binary images.
183  */
184 #define SX_ITEM         'i'     /* An array item introducer */
185 #define SX_IT_UNDEF     'I'     /* Undefined array item */
186 #define SX_KEY          'k'     /* A hash key introducer */
187 #define SX_VALUE        'v'     /* A hash value introducer */
188 #define SX_VL_UNDEF     'V'     /* Undefined hash value */
189
190 /*
191  * Those are only used to retrieve "old" pre-0.7 binary images
192  */
193
194 #define SX_CLASS        'b'     /* Object is blessed, class name length <255 */
195 #define SX_LG_CLASS     'B'     /* Object is blessed, class name length >255 */
196 #define SX_STORED       'X'     /* End of object */
197
198 /*
199  * Limits between short/long length representation.
200  */
201
202 #define LG_SCALAR       255     /* Large scalar length limit */
203 #define LG_BLESS        127     /* Large classname bless limit */
204
205 /*
206  * Operation types
207  */
208
209 #define ST_STORE        0x1     /* Store operation */
210 #define ST_RETRIEVE     0x2     /* Retrieval operation */
211 #define ST_CLONE        0x4     /* Deep cloning operation */
212
213 /*
214  * The following structure is used for hash table key retrieval. Since, when
215  * retrieving objects, we'll be facing blessed hash references, it's best
216  * to pre-allocate that buffer once and resize it as the need arises, never
217  * freeing it (keys will be saved away someplace else anyway, so even large
218  * keys are not enough a motivation to reclaim that space).
219  *
220  * This structure is also used for memory store/retrieve operations which
221  * happen in a fixed place before being malloc'ed elsewhere if persistence
222  * is required. Hence the aptr pointer.
223  */
224 struct extendable {
225     char *arena;        /* Will hold hash key strings, resized as needed */
226     STRLEN asiz;        /* Size of aforementioned buffer */
227     char *aptr;         /* Arena pointer, for in-place read/write ops */
228     char *aend;         /* First invalid address */
229 };
230
231 /*
232  * At store time:
233  * A hash table records the objects which have already been stored.
234  * Those are referred to as SX_OBJECT in the file, and their "tag" (i.e.
235  * an arbitrary sequence number) is used to identify them.
236  *
237  * At retrieve time:
238  * An array table records the objects which have already been retrieved,
239  * as seen by the tag determined by counting the objects themselves. The
240  * reference to that retrieved object is kept in the table, and is returned
241  * when an SX_OBJECT is found bearing that same tag.
242  *
243  * The same processing is used to record "classname" for blessed objects:
244  * indexing by a hash at store time, and via an array at retrieve time.
245  */
246
247 typedef unsigned long stag_t;   /* Used by pre-0.6 binary format */
248
249 /*
250  * Make the tag type 64-bit on 64-bit platforms.
251  *
252  * If the tag number is low enough it's stored as a 32-bit value, but
253  * with very large arrays and hashes it's possible to go over 2**32
254  * scalars.
255  */
256
257 typedef STRLEN ntag_t;
258
259 /* used for where_is_undef - marks an unset value */
260 #define UNSET_NTAG_T (~(ntag_t)0)
261
262 /*
263  * The following "thread-safe" related defines were contributed by
264  * Murray Nesbitt <murray@activestate.com> and integrated by RAM, who
265  * only renamed things a little bit to ensure consistency with surrounding
266  * code.        -- RAM, 14/09/1999
267  *
268  * The original patch suffered from the fact that the stcxt_t structure
269  * was global.  Murray tried to minimize the impact on the code as much as
270  * possible.
271  *
272  * Starting with 0.7, Storable can be re-entrant, via the STORABLE_xxx hooks
273  * on objects.  Therefore, the notion of context needs to be generalized,
274  * threading or not.
275  */
276
277 #define MY_VERSION "Storable(" XS_VERSION ")"
278
279
280 /*
281  * Conditional UTF8 support.
282  *
283  */
284 #define STORE_UTF8STR(pv, len)  STORE_PV_LEN(pv, len, SX_UTF8STR, SX_LUTF8STR)
285 #define HAS_UTF8_SCALARS
286 #ifdef HeKUTF8
287 #define HAS_UTF8_HASHES
288 #define HAS_UTF8_ALL
289 #else
290 /* 5.6 perl has utf8 scalars but not hashes */
291 #endif
292 #ifndef HAS_UTF8_ALL
293 #define UTF8_CROAK() CROAK(("Cannot retrieve UTF8 data in non-UTF8 perl"))
294 #endif
295 #ifndef SvWEAKREF
296 #define WEAKREF_CROAK() CROAK(("Cannot retrieve weak references in this perl"))
297 #endif
298 #ifndef SvVOK
299 #define VSTRING_CROAK() CROAK(("Cannot retrieve vstring in this perl"))
300 #endif
301
302 #ifdef HvPLACEHOLDERS
303 #define HAS_RESTRICTED_HASHES
304 #else
305 #define HVhek_PLACEHOLD 0x200
306 #define RESTRICTED_HASH_CROAK() CROAK(("Cannot retrieve restricted hash"))
307 #endif
308
309 #ifdef HvHASKFLAGS
310 #define HAS_HASH_KEY_FLAGS
311 #endif
312
313 #ifdef ptr_table_new
314 #define USE_PTR_TABLE
315 #endif
316
317 /* do we need/want to clear padding on NVs? */
318 #if defined(LONG_DOUBLEKIND) && defined(USE_LONG_DOUBLE)
319 #  if LONG_DOUBLEKIND == LONG_DOUBLE_IS_X86_80_BIT_LITTLE_ENDIAN || \
320       LONG_DOUBLEKIND == LONG_DOUBLE_IS_X86_80_BIT_BIG_ENDIAN
321 #    define NV_PADDING (NVSIZE - 10)
322 #  else
323 #    define NV_PADDING 0
324 #  endif
325 #else
326 /* This is kind of a guess - it means we'll get an unneeded clear on 128-bit NV
327    but an upgraded perl will fix that
328 */
329 #  if NVSIZE > 8
330 #    define NV_CLEAR
331 #  endif
332 #  define NV_PADDING 0
333 #endif
334
335 typedef union {
336     NV nv;
337     U8 bytes[sizeof(NV)];
338 } NV_bytes;
339
340 /* Needed for 32bit with lengths > 2G - 4G, and 64bit */
341 #if PTRSIZE > 4
342 #define HAS_U64
343 #endif
344
345 /*
346  * Fields s_tainted and s_dirty are prefixed with s_ because Perl's include
347  * files remap tainted and dirty when threading is enabled.  That's bad for
348  * perl to remap such common words.     -- RAM, 29/09/00
349  */
350
351 struct stcxt;
352 typedef struct stcxt {
353     int entry;          /* flags recursion */
354     int optype;         /* type of traversal operation */
355     /* which objects have been seen, store time.
356        tags are numbers, which are cast to (SV *) and stored directly */
357 #ifdef USE_PTR_TABLE
358     /* use pseen if we have ptr_tables. We have to store tag+1, because
359        tag numbers start at 0, and we can't store (SV *) 0 in a ptr_table
360        without it being confused for a fetch lookup failure.  */
361     struct ptr_tbl *pseen;
362     /* Still need hseen for the 0.6 file format code. */
363 #endif
364     HV *hseen;
365     AV *hook_seen;              /* which SVs were returned by STORABLE_freeze() */
366     AV *aseen;                  /* which objects have been seen, retrieve time */
367     ntag_t where_is_undef;              /* index in aseen of PL_sv_undef */
368     HV *hclass;                 /* which classnames have been seen, store time */
369     AV *aclass;                 /* which classnames have been seen, retrieve time */
370     HV *hook;                   /* cache for hook methods per class name */
371     IV tagnum;                  /* incremented at store time for each seen object */
372     IV classnum;                /* incremented at store time for each seen classname */
373     int netorder;               /* true if network order used */
374     int s_tainted;              /* true if input source is tainted, at retrieve time */
375     int forgive_me;             /* whether to be forgiving... */
376     int deparse;                /* whether to deparse code refs */
377     SV *eval;                   /* whether to eval source code */
378     int canonical;              /* whether to store hashes sorted by key */
379 #ifndef HAS_RESTRICTED_HASHES
380     int derestrict;             /* whether to downgrade restricted hashes */
381 #endif
382 #ifndef HAS_UTF8_ALL
383     int use_bytes;              /* whether to bytes-ify utf8 */
384 #endif
385     int accept_future_minor;    /* croak immediately on future minor versions?  */
386     int s_dirty;                /* context is dirty due to CROAK() -- can be cleaned */
387     int membuf_ro;              /* true means membuf is read-only and msaved is rw */
388     struct extendable keybuf;   /* for hash key retrieval */
389     struct extendable membuf;   /* for memory store/retrieve operations */
390     struct extendable msaved;   /* where potentially valid mbuf is saved */
391     PerlIO *fio;                /* where I/O are performed, NULL for memory */
392     int ver_major;              /* major of version for retrieved object */
393     int ver_minor;              /* minor of version for retrieved object */
394     SV *(**retrieve_vtbl)(pTHX_ struct stcxt *, const char *);  /* retrieve dispatch table */
395     SV *prev;                   /* contexts chained backwards in real recursion */
396     SV *my_sv;                  /* the blessed scalar who's SvPVX() I am */
397
398     /* recur_sv:
399
400        A hashref of hashrefs or arrayref of arrayrefs is actually a
401        chain of four SVs, eg for an array ref containing an array ref:
402
403          RV -> AV (element) -> RV -> AV
404
405        To make this depth appear natural from a perl level we only
406        want to count this as two levels, so store_ref() stores it's RV
407        into recur_sv and store_array()/store_hash() will only count
408        that level if the AV/HV *isn't* recur_sv.
409
410        We can't just have store_hash()/store_array() not count that
411        level, since it's possible for XS code to store an AV or HV
412        directly as an element (though perl code trying to access such
413        an object will generally croak.)
414      */
415     SV *recur_sv;               /* check only one recursive SV */
416     int in_retrieve_overloaded; /* performance hack for retrieving overloaded objects */
417     int flags;                  /* controls whether to bless or tie objects */
418     IV recur_depth;             /* avoid stack overflows RT #97526 */
419     IV max_recur_depth;        /* limit for recur_depth */
420     IV max_recur_depth_hash;   /* limit for recur_depth for hashes */
421 #ifdef DEBUGME
422     int traceme;                /* TRACEME() produces output */
423 #endif
424 } stcxt_t;
425
426 #define RECURSION_TOO_DEEP() \
427     (cxt->max_recur_depth != -1 && ++cxt->recur_depth > cxt->max_recur_depth)
428
429 /* There's cases where we need to check whether the hash recursion
430    limit has been reached without bumping the recursion levels, so the
431    hash check doesn't bump the depth.
432 */
433 #define RECURSION_TOO_DEEP_HASH() \
434     (cxt->max_recur_depth_hash != -1 && cxt->recur_depth > cxt->max_recur_depth_hash)
435 #define MAX_DEPTH_ERROR "Max. recursion depth with nested structures exceeded"
436
437 static int storable_free(pTHX_ SV *sv, MAGIC* mg);
438
439 static MGVTBL vtbl_storable = {
440     NULL, /* get */
441     NULL, /* set */
442     NULL, /* len */
443     NULL, /* clear */
444     storable_free,
445 #ifdef MGf_COPY
446     NULL, /* copy */
447 #endif
448 #ifdef MGf_DUP
449     NULL, /* dup */
450 #endif
451 #ifdef MGf_LOCAL
452     NULL /* local */
453 #endif
454 };
455
456 /* From Digest::MD5.  */
457 #ifndef sv_magicext
458 # define sv_magicext(sv, obj, type, vtbl, name, namlen)         \
459     THX_sv_magicext(aTHX_ sv, obj, type, vtbl, name, namlen)
460 static MAGIC *THX_sv_magicext(pTHX_
461         SV *sv, SV *obj, int type,
462         MGVTBL const *vtbl, char const *name, I32 namlen)
463 {
464     MAGIC *mg;
465     if (obj || namlen)
466         /* exceeded intended usage of this reserve implementation */
467         return NULL;
468     Newxz(mg, 1, MAGIC);
469     mg->mg_virtual = (MGVTBL*)vtbl;
470     mg->mg_type = type;
471     mg->mg_ptr = (char *)name;
472     mg->mg_len = -1;
473     (void) SvUPGRADE(sv, SVt_PVMG);
474     mg->mg_moremagic = SvMAGIC(sv);
475     SvMAGIC_set(sv, mg);
476     SvMAGICAL_off(sv);
477     mg_magical(sv);
478     return mg;
479 }
480 #endif
481
482 #define NEW_STORABLE_CXT_OBJ(cxt)                               \
483     STMT_START {                                                \
484         SV *self = newSV(sizeof(stcxt_t) - 1);                  \
485         SV *my_sv = newRV_noinc(self);                          \
486         sv_magicext(self, NULL, PERL_MAGIC_ext, &vtbl_storable, NULL, 0); \
487         cxt = (stcxt_t *)SvPVX(self);                           \
488         Zero(cxt, 1, stcxt_t);                                  \
489         cxt->my_sv = my_sv;                                     \
490     } STMT_END
491
492 #if defined(MULTIPLICITY) || defined(PERL_OBJECT) || defined(PERL_CAPI)
493
494 #define dSTCXT_SV                                               \
495     SV *perinterp_sv = *hv_fetch(PL_modglobal,                  \
496                                  MY_VERSION, sizeof(MY_VERSION)-1, TRUE)
497
498 #define dSTCXT_PTR(T,name)                                      \
499     T name = ((perinterp_sv                                     \
500                && SvIOK(perinterp_sv) && SvIVX(perinterp_sv)    \
501                ? (T)SvPVX(SvRV(INT2PTR(SV*,SvIVX(perinterp_sv)))) : (T) 0))
502 #define dSTCXT                                  \
503     dSTCXT_SV;                                  \
504     dSTCXT_PTR(stcxt_t *, cxt)
505
506 #define INIT_STCXT                                      \
507     dSTCXT;                                             \
508     NEW_STORABLE_CXT_OBJ(cxt);                          \
509     assert(perinterp_sv);                               \
510     sv_setiv(perinterp_sv, PTR2IV(cxt->my_sv))
511
512 #define SET_STCXT(x)                                    \
513     STMT_START {                                        \
514         dSTCXT_SV;                                      \
515         sv_setiv(perinterp_sv, PTR2IV(x->my_sv));       \
516     } STMT_END
517
518 #else /* !MULTIPLICITY && !PERL_OBJECT && !PERL_CAPI */
519
520 static stcxt_t *Context_ptr = NULL;
521 #define dSTCXT                  stcxt_t *cxt = Context_ptr
522 #define SET_STCXT(x)            Context_ptr = x
523 #define INIT_STCXT                              \
524     dSTCXT;                                     \
525     NEW_STORABLE_CXT_OBJ(cxt);                  \
526     SET_STCXT(cxt)
527
528
529 #endif /* MULTIPLICITY || PERL_OBJECT || PERL_CAPI */
530
531 /*
532  * KNOWN BUG:
533  *   Croaking implies a memory leak, since we don't use setjmp/longjmp
534  *   to catch the exit and free memory used during store or retrieve
535  *   operations.  This is not too difficult to fix, but I need to understand
536  *   how Perl does it, and croaking is exceptional anyway, so I lack the
537  *   motivation to do it.
538  *
539  * The current workaround is to mark the context as dirty when croaking,
540  * so that data structures can be freed whenever we renter Storable code
541  * (but only *then*: it's a workaround, not a fix).
542  *
543  * This is also imperfect, because we don't really know how far they trapped
544  * the croak(), and when we were recursing, we won't be able to clean anything
545  * but the topmost context stacked.
546  */
547
548 #define CROAK(x)        STMT_START { cxt->s_dirty = 1; croak x; } STMT_END
549
550 /*
551  * End of "thread-safe" related definitions.
552  */
553
554 /*
555  * LOW_32BITS
556  *
557  * Keep only the low 32 bits of a pointer (used for tags, which are not
558  * really pointers).
559  */
560
561 #if PTRSIZE <= 4
562 #define LOW_32BITS(x)   ((I32) (x))
563 #else
564 #define LOW_32BITS(x)   ((I32) ((STRLEN) (x) & 0xffffffffUL))
565 #endif
566
567 /*
568  * PTR2TAG(x)
569  *
570  * Convert a pointer into an ntag_t.
571  */
572
573 #define PTR2TAG(x) ((ntag_t)(x))
574
575 #define TAG2PTR(x, type) ((y)(x))
576
577 /*
578  * oI, oS, oC
579  *
580  * Hack for Crays, where sizeof(I32) == 8, and which are big-endians.
581  * Used in the WLEN and RLEN macros.
582  */
583
584 #if INTSIZE > 4
585 #define oI(x)   ((I32 *) ((char *) (x) + 4))
586 #define oS(x)   ((x) - 4)
587 #define oL(x)   (x)
588 #define oC(x)   (x = 0)
589 #define CRAY_HACK
590 #else
591 #define oI(x)   (x)
592 #define oS(x)   (x)
593 #define oL(x)   (x)
594 #define oC(x)
595 #endif
596
597 /*
598  * key buffer handling
599  */
600 #define kbuf    (cxt->keybuf).arena
601 #define ksiz    (cxt->keybuf).asiz
602 #define KBUFINIT()                                                      \
603     STMT_START {                                                        \
604         if (!kbuf) {                                                    \
605             TRACEME(("** allocating kbuf of 128 bytes"));               \
606             New(10003, kbuf, 128, char);                                \
607             ksiz = 128;                                                 \
608         }                                                               \
609     } STMT_END
610 #define KBUFCHK(x)                                                      \
611     STMT_START {                                                        \
612         if (x >= ksiz) {                                                \
613             if (x >= I32_MAX)                                           \
614                 CROAK(("Too large size > I32_MAX"));                    \
615             TRACEME(("** extending kbuf to %d bytes (had %d)",          \
616                      (int)(x+1), (int)ksiz));                           \
617             Renew(kbuf, x+1, char);                                     \
618             ksiz = x+1;                                                 \
619         }                                                               \
620     } STMT_END
621
622 /*
623  * memory buffer handling
624  */
625 #define mbase   (cxt->membuf).arena
626 #define msiz    (cxt->membuf).asiz
627 #define mptr    (cxt->membuf).aptr
628 #define mend    (cxt->membuf).aend
629
630 #define MGROW   (1 << 13)
631 #define MMASK   (MGROW - 1)
632
633 #define round_mgrow(x)  \
634     ((STRLEN) (((STRLEN) (x) + MMASK) & ~MMASK))
635 #define trunc_int(x)    \
636     ((STRLEN) ((STRLEN) (x) & ~(sizeof(int)-1)))
637 #define int_aligned(x)  \
638     ((STRLEN)(x) == trunc_int(x))
639
640 #define MBUF_INIT(x)                                                    \
641     STMT_START {                                                        \
642         if (!mbase) {                                                   \
643             TRACEME(("** allocating mbase of %d bytes", MGROW));        \
644             New(10003, mbase, (int)MGROW, char);                        \
645             msiz = (STRLEN)MGROW;                                       \
646         }                                                               \
647         mptr = mbase;                                                   \
648         if (x)                                                          \
649             mend = mbase + x;                                           \
650         else                                                            \
651             mend = mbase + msiz;                                        \
652     } STMT_END
653
654 #define MBUF_TRUNC(x)   mptr = mbase + x
655 #define MBUF_SIZE()     (mptr - mbase)
656
657 /*
658  * MBUF_SAVE_AND_LOAD
659  * MBUF_RESTORE
660  *
661  * Those macros are used in do_retrieve() to save the current memory
662  * buffer into cxt->msaved, before MBUF_LOAD() can be used to retrieve
663  * data from a string.
664  */
665 #define MBUF_SAVE_AND_LOAD(in)                                          \
666     STMT_START {                                                        \
667         ASSERT(!cxt->membuf_ro, ("mbase not already saved"));           \
668         cxt->membuf_ro = 1;                                             \
669         TRACEME(("saving mbuf"));                                       \
670         StructCopy(&cxt->membuf, &cxt->msaved, struct extendable);      \
671         MBUF_LOAD(in);                                                  \
672     } STMT_END
673
674 #define MBUF_RESTORE()                                                  \
675     STMT_START {                                                        \
676         ASSERT(cxt->membuf_ro, ("mbase is read-only"));                 \
677         cxt->membuf_ro = 0;                                             \
678         TRACEME(("restoring mbuf"));                                    \
679         StructCopy(&cxt->msaved, &cxt->membuf, struct extendable);      \
680     } STMT_END
681
682 /*
683  * Use SvPOKp(), because SvPOK() fails on tainted scalars.
684  * See store_scalar() for other usage of this workaround.
685  */
686 #define MBUF_LOAD(v)                                            \
687     STMT_START {                                                \
688         ASSERT(cxt->membuf_ro, ("mbase is read-only"));         \
689         if (!SvPOKp(v))                                         \
690             CROAK(("Not a scalar string"));                     \
691         mptr = mbase = SvPV(v, msiz);                           \
692         mend = mbase + msiz;                                    \
693     } STMT_END
694
695 #define MBUF_XTEND(x)                                           \
696     STMT_START {                                                \
697         STRLEN nsz = (STRLEN) round_mgrow((x)+msiz);            \
698         STRLEN offset = mptr - mbase;                           \
699         ASSERT(!cxt->membuf_ro, ("mbase is not read-only"));    \
700         TRACEME(("** extending mbase from %lu to %lu bytes (wants %lu new)", \
701                  (unsigned long)msiz, (unsigned long)nsz, (unsigned long)(x)));  \
702         Renew(mbase, nsz, char);                                \
703         msiz = nsz;                                             \
704         mptr = mbase + offset;                                  \
705         mend = mbase + nsz;                                     \
706     } STMT_END
707
708 #define MBUF_CHK(x)                             \
709     STMT_START {                                \
710         if ((mptr + (x)) > mend)                \
711             MBUF_XTEND(x);                      \
712     } STMT_END
713
714 #define MBUF_GETC(x)                            \
715     STMT_START {                                \
716         if (mptr < mend)                        \
717             x = (int) (unsigned char) *mptr++;  \
718         else                                    \
719             return (SV *) 0;                    \
720     } STMT_END
721
722 #ifdef CRAY_HACK
723 #define MBUF_GETINT(x)                          \
724     STMT_START {                                \
725         oC(x);                                  \
726         if ((mptr + 4) <= mend) {               \
727             memcpy(oI(&x), mptr, 4);            \
728             mptr += 4;                          \
729         } else                                  \
730             return (SV *) 0;                    \
731     } STMT_END
732 #else
733 #define MBUF_GETINT(x)                          \
734     STMT_START {                                \
735         if ((mptr + sizeof(int)) <= mend) {     \
736             if (int_aligned(mptr))              \
737                 x = *(int *) mptr;              \
738             else                                \
739                 memcpy(&x, mptr, sizeof(int));  \
740             mptr += sizeof(int);                \
741         } else                                  \
742             return (SV *) 0;                    \
743     } STMT_END
744 #endif
745
746 #define MBUF_READ(x,s)                          \
747     STMT_START {                                \
748         if ((mptr + (s)) <= mend) {             \
749             memcpy(x, mptr, s);                 \
750             mptr += s;                          \
751         } else                                  \
752             return (SV *) 0;                    \
753     } STMT_END
754
755 #define MBUF_SAFEREAD(x,s,z)                    \
756     STMT_START {                                \
757         if ((mptr + (s)) <= mend) {             \
758             memcpy(x, mptr, s);                 \
759             mptr += s;                          \
760         } else {                                \
761             sv_free(z);                         \
762             return (SV *) 0;                    \
763         }                                       \
764     } STMT_END
765
766 #define MBUF_SAFEPVREAD(x,s,z)                  \
767     STMT_START {                                \
768         if ((mptr + (s)) <= mend) {             \
769             memcpy(x, mptr, s);                 \
770             mptr += s;                          \
771         } else {                                \
772             Safefree(z);                        \
773             return (SV *) 0;                    \
774         }                                       \
775     } STMT_END
776
777 #define MBUF_PUTC(c)                            \
778     STMT_START {                                \
779         if (mptr < mend)                        \
780             *mptr++ = (char) c;                 \
781         else {                                  \
782             MBUF_XTEND(1);                      \
783             *mptr++ = (char) c;                 \
784         }                                       \
785     } STMT_END
786
787 #ifdef CRAY_HACK
788 #define MBUF_PUTINT(i)                          \
789     STMT_START {                                \
790         MBUF_CHK(4);                            \
791         memcpy(mptr, oI(&i), 4);                \
792         mptr += 4;                              \
793     } STMT_END
794 #else
795 #define MBUF_PUTINT(i)                          \
796     STMT_START {                                \
797         MBUF_CHK(sizeof(int));                  \
798         if (int_aligned(mptr))                  \
799             *(int *) mptr = i;                  \
800         else                                    \
801             memcpy(mptr, &i, sizeof(int));      \
802         mptr += sizeof(int);                    \
803     } STMT_END
804 #endif
805
806 #define MBUF_PUTLONG(l)                         \
807     STMT_START {                                \
808         MBUF_CHK(8);                            \
809         memcpy(mptr, &l, 8);                    \
810         mptr += 8;                              \
811     } STMT_END
812 #define MBUF_WRITE(x,s)                         \
813     STMT_START {                                \
814         MBUF_CHK(s);                            \
815         memcpy(mptr, x, s);                     \
816         mptr += s;                              \
817     } STMT_END
818
819 /*
820  * Possible return values for sv_type().
821  */
822
823 #define svis_REF                0
824 #define svis_SCALAR             1
825 #define svis_ARRAY              2
826 #define svis_HASH               3
827 #define svis_TIED               4
828 #define svis_TIED_ITEM          5
829 #define svis_CODE               6
830 #define svis_REGEXP             7
831 #define svis_OTHER              8
832
833 /*
834  * Flags for SX_HOOK.
835  */
836
837 #define SHF_TYPE_MASK           0x03
838 #define SHF_LARGE_CLASSLEN      0x04
839 #define SHF_LARGE_STRLEN        0x08
840 #define SHF_LARGE_LISTLEN       0x10
841 #define SHF_IDX_CLASSNAME       0x20
842 #define SHF_NEED_RECURSE        0x40
843 #define SHF_HAS_LIST            0x80
844
845 /*
846  * Types for SX_HOOK (last 2 bits in flags).
847  */
848
849 #define SHT_SCALAR              0
850 #define SHT_ARRAY               1
851 #define SHT_HASH                2
852 #define SHT_EXTRA               3       /* Read extra byte for type */
853
854 /*
855  * The following are held in the "extra byte"...
856  */
857
858 #define SHT_TSCALAR             4       /* 4 + 0 -- tied scalar */
859 #define SHT_TARRAY              5       /* 4 + 1 -- tied array */
860 #define SHT_THASH               6       /* 4 + 2 -- tied hash */
861
862 /*
863  * per hash flags for flagged hashes
864  */
865
866 #define SHV_RESTRICTED          0x01
867
868 /*
869  * per key flags for flagged hashes
870  */
871
872 #define SHV_K_UTF8              0x01
873 #define SHV_K_WASUTF8           0x02
874 #define SHV_K_LOCKED            0x04
875 #define SHV_K_ISSV              0x08
876 #define SHV_K_PLACEHOLDER       0x10
877
878 /*
879  * flags to allow blessing and/or tieing data the data we load
880  */
881 #define FLAG_BLESS_OK 2
882 #define FLAG_TIE_OK   4
883
884 /*
885  * Flags for SX_REGEXP.
886  */
887
888 #define SHR_U32_RE_LEN          0x01
889
890 /*
891  * Before 0.6, the magic string was "perl-store" (binary version number 0).
892  *
893  * Since 0.6 introduced many binary incompatibilities, the magic string has
894  * been changed to "pst0" to allow an old image to be properly retrieved by
895  * a newer Storable, but ensure a newer image cannot be retrieved with an
896  * older version.
897  *
898  * At 0.7, objects are given the ability to serialize themselves, and the
899  * set of markers is extended, backward compatibility is not jeopardized,
900  * so the binary version number could have remained unchanged.  To correctly
901  * spot errors if a file making use of 0.7-specific extensions is given to
902  * 0.6 for retrieval, the binary version was moved to "2".  And I'm introducing
903  * a "minor" version, to better track this kind of evolution from now on.
904  * 
905  */
906 static const char old_magicstr[] = "perl-store"; /* Magic number before 0.6 */
907 static const char magicstr[] = "pst0";           /* Used as a magic number */
908
909 #define MAGICSTR_BYTES  'p','s','t','0'
910 #define OLDMAGICSTR_BYTES  'p','e','r','l','-','s','t','o','r','e'
911
912 /* 5.6.x introduced the ability to have IVs as long long.
913    However, Configure still defined BYTEORDER based on the size of a long.
914    Storable uses the BYTEORDER value as part of the header, but doesn't
915    explicitly store sizeof(IV) anywhere in the header.  Hence on 5.6.x built
916    with IV as long long on a platform that uses Configure (ie most things
917    except VMS and Windows) headers are identical for the different IV sizes,
918    despite the files containing some fields based on sizeof(IV)
919    Erk. Broken-ness.
920    5.8 is consistent - the following redefinition kludge is only needed on
921    5.6.x, but the interwork is needed on 5.8 while data survives in files
922    with the 5.6 header.
923
924 */
925
926 #if defined (IVSIZE) && (IVSIZE == 8) && (LONGSIZE == 4)
927 #ifndef NO_56_INTERWORK_KLUDGE
928 #define USE_56_INTERWORK_KLUDGE
929 #endif
930 #if BYTEORDER == 0x1234
931 #undef BYTEORDER
932 #define BYTEORDER 0x12345678
933 #else
934 #if BYTEORDER == 0x4321
935 #undef BYTEORDER
936 #define BYTEORDER 0x87654321
937 #endif
938 #endif
939 #endif
940
941 #if BYTEORDER == 0x1234
942 #define BYTEORDER_BYTES  '1','2','3','4'
943 #else
944 #if BYTEORDER == 0x12345678
945 #define BYTEORDER_BYTES  '1','2','3','4','5','6','7','8'
946 #ifdef USE_56_INTERWORK_KLUDGE
947 #define BYTEORDER_BYTES_56  '1','2','3','4'
948 #endif
949 #else
950 #if BYTEORDER == 0x87654321
951 #define BYTEORDER_BYTES  '8','7','6','5','4','3','2','1'
952 #ifdef USE_56_INTERWORK_KLUDGE
953 #define BYTEORDER_BYTES_56  '4','3','2','1'
954 #endif
955 #else
956 #if BYTEORDER == 0x4321
957 #define BYTEORDER_BYTES  '4','3','2','1'
958 #else
959 #error Unknown byteorder. Please append your byteorder to Storable.xs
960 #endif
961 #endif
962 #endif
963 #endif
964
965 #ifndef INT32_MAX
966 # define INT32_MAX 2147483647
967 #endif
968 #if IVSIZE > 4 && !defined(INT64_MAX)
969 # define INT64_MAX 9223372036854775807LL
970 #endif
971
972 static const char byteorderstr[] = {BYTEORDER_BYTES, 0};
973 #ifdef USE_56_INTERWORK_KLUDGE
974 static const char byteorderstr_56[] = {BYTEORDER_BYTES_56, 0};
975 #endif
976
977 #define STORABLE_BIN_MAJOR      2               /* Binary major "version" */
978 #define STORABLE_BIN_MINOR      11              /* Binary minor "version" */
979
980 #if !defined (SvVOK)
981 /*
982  * Perl 5.6.0-5.8.0 can do weak references, but not vstring magic.
983 */
984 #define STORABLE_BIN_WRITE_MINOR        8
985 #elif PERL_VERSION_GE(5,19,0)
986 /* Perl 5.19 takes away the special meaning of PL_sv_undef in arrays. */
987 /* With 3.x we added LOBJECT */
988 #define STORABLE_BIN_WRITE_MINOR        11
989 #else
990 #define STORABLE_BIN_WRITE_MINOR        9
991 #endif
992
993 #if PERL_VERSION_LT(5,8,1)
994 #define PL_sv_placeholder PL_sv_undef
995 #endif
996
997 /*
998  * Useful store shortcuts...
999  */
1000
1001 /*
1002  * Note that if you put more than one mark for storing a particular
1003  * type of thing, *and* in the retrieve_foo() function you mark both
1004  * the thingy's you get off with SEEN(), you *must* increase the
1005  * tagnum with cxt->tagnum++ along with this macro!
1006  *     - samv 20Jan04
1007  */
1008 #define PUTMARK(x)                                      \
1009     STMT_START {                                        \
1010         if (!cxt->fio)                                  \
1011             MBUF_PUTC(x);                               \
1012         else if (PerlIO_putc(cxt->fio, x) == EOF)       \
1013             return -1;                                  \
1014     } STMT_END
1015
1016 #define WRITE_I32(x)                                            \
1017     STMT_START {                                                \
1018         ASSERT(sizeof(x) == sizeof(I32), ("writing an I32"));   \
1019         if (!cxt->fio)                                          \
1020             MBUF_PUTINT(x);                                     \
1021         else if (PerlIO_write(cxt->fio, oI(&x),                 \
1022                               oS(sizeof(x))) != oS(sizeof(x)))  \
1023             return -1;                                          \
1024     } STMT_END
1025
1026 #define WRITE_U64(x)                                                    \
1027     STMT_START {                                                        \
1028         ASSERT(sizeof(x) == sizeof(UV), ("writing an UV"));             \
1029         if (!cxt->fio)                                                  \
1030             MBUF_PUTLONG(x);                                            \
1031         else if (PerlIO_write(cxt->fio, oL(&x),                         \
1032                               oS(sizeof(x))) != oS(sizeof(x)))          \
1033             return -1;                                                  \
1034     } STMT_END
1035
1036 #ifdef HAS_HTONL
1037 #define WLEN(x)                                                         \
1038     STMT_START {                                                        \
1039         ASSERT(sizeof(x) == sizeof(int), ("WLEN writing an int"));      \
1040         if (cxt->netorder) {                                            \
1041             int y = (int) htonl(x);                                     \
1042             if (!cxt->fio)                                              \
1043                 MBUF_PUTINT(y);                                         \
1044             else if (PerlIO_write(cxt->fio,oI(&y),oS(sizeof(y))) != oS(sizeof(y))) \
1045                 return -1;                                              \
1046         } else {                                                        \
1047             if (!cxt->fio)                                              \
1048                 MBUF_PUTINT(x);                                         \
1049             else if (PerlIO_write(cxt->fio,oI(&x),                      \
1050                                   oS(sizeof(x))) != oS(sizeof(x)))      \
1051                 return -1;                                              \
1052         }                                                               \
1053     } STMT_END
1054
1055 #  ifdef HAS_U64
1056
1057 #define W64LEN(x)                                                       \
1058     STMT_START {                                                        \
1059         ASSERT(sizeof(x) == 8, ("W64LEN writing a U64"));               \
1060         if (cxt->netorder) {                                            \
1061             U32 buf[2];                                                 \
1062             buf[1] = htonl(x & 0xffffffffUL);                           \
1063             buf[0] = htonl(x >> 32);                                    \
1064             if (!cxt->fio)                                              \
1065                 MBUF_PUTLONG(buf);                                      \
1066             else if (PerlIO_write(cxt->fio, buf,                        \
1067                                   sizeof(buf)) != sizeof(buf))          \
1068                 return -1;                                              \
1069         } else {                                                        \
1070             if (!cxt->fio)                                              \
1071                 MBUF_PUTLONG(x);                                        \
1072             else if (PerlIO_write(cxt->fio,oI(&x),                      \
1073                                   oS(sizeof(x))) != oS(sizeof(x)))      \
1074                 return -1;                                              \
1075         }                                                               \
1076     } STMT_END
1077
1078 #  else
1079
1080 #define W64LEN(x) CROAK(("No 64bit UVs"))
1081
1082 #  endif
1083
1084 #else
1085 #define WLEN(x) WRITE_I32(x)
1086 #ifdef HAS_U64
1087 #define W64LEN(x) WRITE_U64(x)
1088 #else
1089 #define W64LEN(x) CROAK(("no 64bit UVs"))
1090 #endif
1091 #endif
1092
1093 #define WRITE(x,y)                                                      \
1094     STMT_START {                                                        \
1095         if (!cxt->fio)                                                  \
1096             MBUF_WRITE(x,y);                                            \
1097         else if (PerlIO_write(cxt->fio, x, y) != (SSize_t)y)            \
1098             return -1;                                                  \
1099     } STMT_END
1100
1101 #define STORE_PV_LEN(pv, len, small, large)                     \
1102     STMT_START {                                                \
1103         if (len <= LG_SCALAR) {                                 \
1104             int ilen = (int) len;                               \
1105             unsigned char clen = (unsigned char) len;           \
1106             PUTMARK(small);                                     \
1107             PUTMARK(clen);                                      \
1108             if (len)                                            \
1109                 WRITE(pv, ilen);                                \
1110         } else if (sizeof(len) > 4 && len > INT32_MAX) {        \
1111             PUTMARK(SX_LOBJECT);                                \
1112             PUTMARK(large);                                     \
1113             W64LEN(len);                                        \
1114             WRITE(pv, len);                                     \
1115         } else {                                                \
1116             int ilen = (int) len;                               \
1117             PUTMARK(large);                                     \
1118             WLEN(ilen);                                         \
1119             WRITE(pv, ilen);                                    \
1120         }                                                       \
1121     } STMT_END
1122
1123 #define STORE_SCALAR(pv, len)   STORE_PV_LEN(pv, len, SX_SCALAR, SX_LSCALAR)
1124
1125 /*
1126  * Store &PL_sv_undef in arrays without recursing through store().  We
1127  * actually use this to represent nonexistent elements, for historical
1128  * reasons.
1129  */
1130 #define STORE_SV_UNDEF()                                        \
1131     STMT_START {                                                \
1132         cxt->tagnum++;                                          \
1133         PUTMARK(SX_SV_UNDEF);                                   \
1134     } STMT_END
1135
1136 /*
1137  * Useful retrieve shortcuts...
1138  */
1139
1140 #define GETCHAR() \
1141     (cxt->fio ? PerlIO_getc(cxt->fio)                   \
1142               : (mptr >= mend ? EOF : (int) *mptr++))
1143
1144 #define GETMARK(x)                                                      \
1145     STMT_START {                                                        \
1146         if (!cxt->fio)                                                  \
1147             MBUF_GETC(x);                                               \
1148         else if ((int) (x = PerlIO_getc(cxt->fio)) == EOF)              \
1149             return (SV *) 0;                                            \
1150     } STMT_END
1151
1152 #define READ_I32(x)                                                     \
1153     STMT_START {                                                        \
1154         ASSERT(sizeof(x) == sizeof(I32), ("reading an I32"));           \
1155         oC(x);                                                          \
1156         if (!cxt->fio)                                                  \
1157             MBUF_GETINT(x);                                             \
1158         else if (PerlIO_read(cxt->fio, oI(&x),                          \
1159                                  oS(sizeof(x))) != oS(sizeof(x)))       \
1160             return (SV *) 0;                                            \
1161     } STMT_END
1162
1163 #ifdef HAS_NTOHL
1164 #define RLEN(x)                                                         \
1165     STMT_START {                                                        \
1166         oC(x);                                                          \
1167         if (!cxt->fio)                                                  \
1168             MBUF_GETINT(x);                                             \
1169         else if (PerlIO_read(cxt->fio, oI(&x),                          \
1170                                  oS(sizeof(x))) != oS(sizeof(x)))       \
1171             return (SV *) 0;                                            \
1172         if (cxt->netorder)                                              \
1173             x = (int) ntohl(x);                                         \
1174     } STMT_END
1175 #else
1176 #define RLEN(x) READ_I32(x)
1177 #endif
1178
1179 #define READ(x,y)                                                       \
1180     STMT_START {                                                        \
1181         if (!cxt->fio)                                                  \
1182             MBUF_READ(x, y);                                            \
1183         else if (PerlIO_read(cxt->fio, x, y) != (SSize_t)y)             \
1184             return (SV *) 0;                                            \
1185     } STMT_END
1186
1187 #define SAFEREAD(x,y,z)                                                 \
1188     STMT_START {                                                        \
1189         if (!cxt->fio)                                                  \
1190             MBUF_SAFEREAD(x,y,z);                                       \
1191         else if (PerlIO_read(cxt->fio, x, y) != (SSize_t)y) {           \
1192             sv_free(z);                                                 \
1193             return (SV *) 0;                                            \
1194         }                                                               \
1195     } STMT_END
1196
1197 #define SAFEPVREAD(x,y,z)                                       \
1198     STMT_START {                                                \
1199         if (!cxt->fio)                                          \
1200             MBUF_SAFEPVREAD(x,y,z);                             \
1201         else if (PerlIO_read(cxt->fio, x, y) != y) {            \
1202             Safefree(z);                                        \
1203             return (SV *) 0;                                    \
1204         }                                                       \
1205     } STMT_END
1206
1207 #ifdef HAS_U64
1208
1209 #  if defined(HAS_NTOHL)
1210 #    define Sntohl(x) ntohl(x)
1211 #  elif BYTEORDER == 0x87654321 || BYTEORDER == 0x4321
1212 #    define Sntohl(x) (x)
1213 #  else
1214 static U32 Sntohl(U32 x) {
1215     return (((U8) x) << 24) + ((x & 0xFF00) << 8)
1216         + ((x & 0xFF0000) >> 8) + ((x & 0xFF000000) >> 24);
1217 }
1218 #  endif
1219
1220 #  define READ_U64(x)                                                       \
1221     STMT_START {                                                          \
1222         ASSERT(sizeof(x) == 8, ("R64LEN reading a U64"));                 \
1223         if (cxt->netorder) {                                              \
1224             U32 buf[2];                                                   \
1225             READ((void *)buf, sizeof(buf));                               \
1226             (x) = ((UV)Sntohl(buf[0]) << 32) + Sntohl(buf[1]);          \
1227         }                                                                 \
1228         else {                                                            \
1229             READ(&(x), sizeof(x));                                        \
1230         }                                                                 \
1231     } STMT_END
1232
1233 #endif
1234
1235 /*
1236  * SEEN() is used at retrieve time, to remember where object 'y', bearing a
1237  * given tag 'tagnum', has been retrieved. Next time we see an SX_OBJECT marker,
1238  * we'll therefore know where it has been retrieved and will be able to
1239  * share the same reference, as in the original stored memory image.
1240  *
1241  * We also need to bless objects ASAP for hooks (which may compute "ref $x"
1242  * on the objects given to STORABLE_thaw and expect that to be defined), and
1243  * also for overloaded objects (for which we might not find the stash if the
1244  * object is not blessed yet--this might occur for overloaded objects that
1245  * refer to themselves indirectly: if we blessed upon return from a sub
1246  * retrieve(), the SX_OBJECT marker we'd found could not have overloading
1247  * restored on it because the underlying object would not be blessed yet!).
1248  *
1249  * To achieve that, the class name of the last retrieved object is passed down
1250  * recursively, and the first SEEN() call for which the class name is not NULL
1251  * will bless the object.
1252  *
1253  * i should be true iff sv is immortal (ie PL_sv_yes, PL_sv_no or PL_sv_undef)
1254  *
1255  * SEEN0() is a short-cut where stash is always NULL.
1256  *
1257  * The _NN variants dont check for y being null
1258  */
1259 #define SEEN0_NN(y,i)                                                   \
1260     STMT_START {                                                        \
1261         if (av_store(cxt->aseen, cxt->tagnum++, i ? (SV*)(y)            \
1262                      : SvREFCNT_inc(y)) == 0)                           \
1263             return (SV *) 0;                                            \
1264         TRACEME(("aseen(#%d) = 0x%" UVxf " (refcnt=%d)",                \
1265                  (int)cxt->tagnum-1,                                    \
1266                  PTR2UV(y), (int)SvREFCNT(y)-1));                       \
1267     } STMT_END
1268
1269 #define SEEN0(y,i)                                                      \
1270     STMT_START {                                                        \
1271         if (!y)                                                         \
1272             return (SV *) 0;                                            \
1273         SEEN0_NN(y,i);                                                  \
1274     } STMT_END
1275
1276 #define SEEN_NN(y,stash,i)                                              \
1277     STMT_START {                                                        \
1278         SEEN0_NN(y,i);                                                  \
1279         if (stash)                                                      \
1280             BLESS((SV *)(y), (HV *)(stash));                            \
1281     } STMT_END
1282
1283 #define SEEN(y,stash,i)                                                 \
1284     STMT_START {                                                        \
1285         if (!y)                                                         \
1286             return (SV *) 0;                                            \
1287         SEEN_NN(y,stash, i);                                            \
1288     } STMT_END
1289
1290 /*
1291  * Bless 's' in 'p', via a temporary reference, required by sv_bless().
1292  * "A" magic is added before the sv_bless for overloaded classes, this avoids
1293  * an expensive call to S_reset_amagic in sv_bless.
1294  */
1295 #define BLESS(s,stash)                                                  \
1296     STMT_START {                                                        \
1297         SV *ref;                                                        \
1298         if (cxt->flags & FLAG_BLESS_OK) {                               \
1299             TRACEME(("blessing 0x%" UVxf " in %s", PTR2UV(s),           \
1300                      HvNAME_get(stash)));                               \
1301             ref = newRV_noinc(s);                                       \
1302             if (cxt->in_retrieve_overloaded && Gv_AMG(stash)) {         \
1303                 cxt->in_retrieve_overloaded = 0;                        \
1304                 SvAMAGIC_on(ref);                                       \
1305             }                                                           \
1306             (void) sv_bless(ref, stash);                                \
1307             SvRV_set(ref, NULL);                                        \
1308             SvREFCNT_dec(ref);                                          \
1309         }                                                               \
1310         else {                                                          \
1311             TRACEME(("not blessing 0x%" UVxf " in %s", PTR2UV(s),       \
1312                      (HvNAME_get(stash))));                             \
1313         }                                                               \
1314     } STMT_END
1315 /*
1316  * sort (used in store_hash) - conditionally use qsort when
1317  * sortsv is not available ( <= 5.6.1 ).
1318  */
1319
1320 #if PERL_VERSION_LT(5,7,0)
1321
1322 #if defined(USE_ITHREADS)
1323
1324 #define STORE_HASH_SORT                                         \
1325     ENTER; {                                                    \
1326         PerlInterpreter *orig_perl = PERL_GET_CONTEXT;          \
1327         SAVESPTR(orig_perl);                                    \
1328         PERL_SET_CONTEXT(aTHX);                                 \
1329         qsort((char *) AvARRAY(av), len, sizeof(SV *), sortcmp);\
1330     } LEAVE;
1331
1332 #else /* ! USE_ITHREADS */
1333
1334 #define STORE_HASH_SORT                                 \
1335     qsort((char *) AvARRAY(av), len, sizeof(SV *), sortcmp);
1336
1337 #endif  /* USE_ITHREADS */
1338
1339 #else /* PERL >= 5.7.0 */
1340
1341 #define STORE_HASH_SORT \
1342     sortsv(AvARRAY(av), len, Perl_sv_cmp);
1343
1344 #endif /* PERL_VERSION_LT(5,7,0) */
1345
1346 static int store(pTHX_ stcxt_t *cxt, SV *sv);
1347 static SV *retrieve(pTHX_ stcxt_t *cxt, const char *cname);
1348
1349 #define UNSEE()                 \
1350     STMT_START {                        \
1351         av_pop(cxt->aseen);             \
1352         cxt->tagnum--;                  \
1353     } STMT_END
1354
1355 /*
1356  * Dynamic dispatching table for SV store.
1357  */
1358
1359 static int store_ref(pTHX_ stcxt_t *cxt, SV *sv);
1360 static int store_scalar(pTHX_ stcxt_t *cxt, SV *sv);
1361 static int store_array(pTHX_ stcxt_t *cxt, AV *av);
1362 static int store_hash(pTHX_ stcxt_t *cxt, HV *hv);
1363 static int store_tied(pTHX_ stcxt_t *cxt, SV *sv);
1364 static int store_tied_item(pTHX_ stcxt_t *cxt, SV *sv);
1365 static int store_code(pTHX_ stcxt_t *cxt, CV *cv);
1366 static int store_regexp(pTHX_ stcxt_t *cxt, SV *sv);
1367 static int store_other(pTHX_ stcxt_t *cxt, SV *sv);
1368 static int store_blessed(pTHX_ stcxt_t *cxt, SV *sv, int type, HV *pkg);
1369
1370 typedef int (*sv_store_t)(pTHX_ stcxt_t *cxt, SV *sv);
1371
1372 static const sv_store_t sv_store[] = {
1373     (sv_store_t)store_ref,      /* svis_REF */
1374     (sv_store_t)store_scalar,   /* svis_SCALAR */
1375     (sv_store_t)store_array,    /* svis_ARRAY */
1376     (sv_store_t)store_hash,     /* svis_HASH */
1377     (sv_store_t)store_tied,     /* svis_TIED */
1378     (sv_store_t)store_tied_item,/* svis_TIED_ITEM */
1379     (sv_store_t)store_code,     /* svis_CODE */
1380     (sv_store_t)store_regexp,   /* svis_REGEXP */
1381     (sv_store_t)store_other,    /* svis_OTHER */
1382 };
1383
1384 #define SV_STORE(x)     (*sv_store[x])
1385
1386 /*
1387  * Dynamic dispatching tables for SV retrieval.
1388  */
1389
1390 static SV *retrieve_lscalar(pTHX_ stcxt_t *cxt, const char *cname);
1391 static SV *retrieve_lutf8str(pTHX_ stcxt_t *cxt, const char *cname);
1392 static SV *old_retrieve_array(pTHX_ stcxt_t *cxt, const char *cname);
1393 static SV *old_retrieve_hash(pTHX_ stcxt_t *cxt, const char *cname);
1394 static SV *retrieve_ref(pTHX_ stcxt_t *cxt, const char *cname);
1395 static SV *retrieve_undef(pTHX_ stcxt_t *cxt, const char *cname);
1396 static SV *retrieve_integer(pTHX_ stcxt_t *cxt, const char *cname);
1397 static SV *retrieve_double(pTHX_ stcxt_t *cxt, const char *cname);
1398 static SV *retrieve_byte(pTHX_ stcxt_t *cxt, const char *cname);
1399 static SV *retrieve_netint(pTHX_ stcxt_t *cxt, const char *cname);
1400 static SV *retrieve_scalar(pTHX_ stcxt_t *cxt, const char *cname);
1401 static SV *retrieve_utf8str(pTHX_ stcxt_t *cxt, const char *cname);
1402 static SV *retrieve_tied_array(pTHX_ stcxt_t *cxt, const char *cname);
1403 static SV *retrieve_tied_hash(pTHX_ stcxt_t *cxt, const char *cname);
1404 static SV *retrieve_tied_scalar(pTHX_ stcxt_t *cxt, const char *cname);
1405 static SV *retrieve_other(pTHX_ stcxt_t *cxt, const char *cname);
1406 static SV *retrieve_lobject(pTHX_ stcxt_t *cxt, const char *cname);
1407 static SV *retrieve_regexp(pTHX_ stcxt_t *cxt, const char *cname);
1408
1409 /* helpers for U64 lobjects */
1410
1411 static SV *get_lstring(pTHX_ stcxt_t *cxt, UV len, int isutf8, const char *cname);
1412 #ifdef HAS_U64
1413 static SV *get_larray(pTHX_ stcxt_t *cxt, UV len, const char *cname);
1414 static SV *get_lhash(pTHX_ stcxt_t *cxt, UV len, int hash_flags, const char *cname);
1415 static int store_lhash(pTHX_ stcxt_t *cxt, HV *hv, unsigned char hash_flags);
1416 #endif
1417 static int store_hentry(pTHX_ stcxt_t *cxt, HV* hv, UV i, HE *he, SV *val,
1418                         unsigned char hash_flags);
1419
1420 typedef SV* (*sv_retrieve_t)(pTHX_ stcxt_t *cxt, const char *name);
1421
1422 static const sv_retrieve_t sv_old_retrieve[] = {
1423     0,                                  /* SX_OBJECT -- entry unused dynamically */
1424     (sv_retrieve_t)retrieve_lscalar,    /* SX_LSCALAR */
1425     (sv_retrieve_t)old_retrieve_array,  /* SX_ARRAY -- for pre-0.6 binaries */
1426     (sv_retrieve_t)old_retrieve_hash,   /* SX_HASH -- for pre-0.6 binaries */
1427     (sv_retrieve_t)retrieve_ref,        /* SX_REF */
1428     (sv_retrieve_t)retrieve_undef,      /* SX_UNDEF */
1429     (sv_retrieve_t)retrieve_integer,    /* SX_INTEGER */
1430     (sv_retrieve_t)retrieve_double,     /* SX_DOUBLE */
1431     (sv_retrieve_t)retrieve_byte,       /* SX_BYTE */
1432     (sv_retrieve_t)retrieve_netint,     /* SX_NETINT */
1433     (sv_retrieve_t)retrieve_scalar,     /* SX_SCALAR */
1434     (sv_retrieve_t)retrieve_tied_array, /* SX_TIED_ARRAY */
1435     (sv_retrieve_t)retrieve_tied_hash,  /* SX_TIED_HASH */
1436     (sv_retrieve_t)retrieve_tied_scalar,/* SX_TIED_SCALAR */
1437     (sv_retrieve_t)retrieve_other,      /* SX_SV_UNDEF not supported */
1438     (sv_retrieve_t)retrieve_other,      /* SX_SV_YES not supported */
1439     (sv_retrieve_t)retrieve_other,      /* SX_SV_NO not supported */
1440     (sv_retrieve_t)retrieve_other,      /* SX_BLESS not supported */
1441     (sv_retrieve_t)retrieve_other,      /* SX_IX_BLESS not supported */
1442     (sv_retrieve_t)retrieve_other,      /* SX_HOOK not supported */
1443     (sv_retrieve_t)retrieve_other,      /* SX_OVERLOADED not supported */
1444     (sv_retrieve_t)retrieve_other,      /* SX_TIED_KEY not supported */
1445     (sv_retrieve_t)retrieve_other,      /* SX_TIED_IDX not supported */
1446     (sv_retrieve_t)retrieve_other,      /* SX_UTF8STR not supported */
1447     (sv_retrieve_t)retrieve_other,      /* SX_LUTF8STR not supported */
1448     (sv_retrieve_t)retrieve_other,      /* SX_FLAG_HASH not supported */
1449     (sv_retrieve_t)retrieve_other,      /* SX_CODE not supported */
1450     (sv_retrieve_t)retrieve_other,      /* SX_WEAKREF not supported */
1451     (sv_retrieve_t)retrieve_other,      /* SX_WEAKOVERLOAD not supported */
1452     (sv_retrieve_t)retrieve_other,      /* SX_VSTRING not supported */
1453     (sv_retrieve_t)retrieve_other,      /* SX_LVSTRING not supported */
1454     (sv_retrieve_t)retrieve_other,      /* SX_SVUNDEF_ELEM not supported */
1455     (sv_retrieve_t)retrieve_other,      /* SX_REGEXP */
1456     (sv_retrieve_t)retrieve_other,      /* SX_LOBJECT not supported */
1457     (sv_retrieve_t)retrieve_other,      /* SX_LAST */
1458 };
1459
1460 static SV *retrieve_hook_common(pTHX_ stcxt_t *cxt, const char *cname, int large);
1461
1462 static SV *retrieve_array(pTHX_ stcxt_t *cxt, const char *cname);
1463 static SV *retrieve_hash(pTHX_ stcxt_t *cxt, const char *cname);
1464 static SV *retrieve_sv_undef(pTHX_ stcxt_t *cxt, const char *cname);
1465 static SV *retrieve_sv_yes(pTHX_ stcxt_t *cxt, const char *cname);
1466 static SV *retrieve_sv_no(pTHX_ stcxt_t *cxt, const char *cname);
1467 static SV *retrieve_blessed(pTHX_ stcxt_t *cxt, const char *cname);
1468 static SV *retrieve_idx_blessed(pTHX_ stcxt_t *cxt, const char *cname);
1469 static SV *retrieve_hook(pTHX_ stcxt_t *cxt, const char *cname);
1470 static SV *retrieve_overloaded(pTHX_ stcxt_t *cxt, const char *cname);
1471 static SV *retrieve_tied_key(pTHX_ stcxt_t *cxt, const char *cname);
1472 static SV *retrieve_tied_idx(pTHX_ stcxt_t *cxt, const char *cname);
1473 static SV *retrieve_flag_hash(pTHX_ stcxt_t *cxt, const char *cname);
1474 static SV *retrieve_code(pTHX_ stcxt_t *cxt, const char *cname);
1475 static SV *retrieve_weakref(pTHX_ stcxt_t *cxt, const char *cname);
1476 static SV *retrieve_weakoverloaded(pTHX_ stcxt_t *cxt, const char *cname);
1477 static SV *retrieve_vstring(pTHX_ stcxt_t *cxt, const char *cname);
1478 static SV *retrieve_lvstring(pTHX_ stcxt_t *cxt, const char *cname);
1479 static SV *retrieve_svundef_elem(pTHX_ stcxt_t *cxt, const char *cname);
1480
1481 static const sv_retrieve_t sv_retrieve[] = {
1482     0,                                  /* SX_OBJECT -- entry unused dynamically */
1483     (sv_retrieve_t)retrieve_lscalar,    /* SX_LSCALAR */
1484     (sv_retrieve_t)retrieve_array,      /* SX_ARRAY */
1485     (sv_retrieve_t)retrieve_hash,       /* SX_HASH */
1486     (sv_retrieve_t)retrieve_ref,        /* SX_REF */
1487     (sv_retrieve_t)retrieve_undef,      /* SX_UNDEF */
1488     (sv_retrieve_t)retrieve_integer,    /* SX_INTEGER */
1489     (sv_retrieve_t)retrieve_double,     /* SX_DOUBLE */
1490     (sv_retrieve_t)retrieve_byte,       /* SX_BYTE */
1491     (sv_retrieve_t)retrieve_netint,     /* SX_NETINT */
1492     (sv_retrieve_t)retrieve_scalar,     /* SX_SCALAR */
1493     (sv_retrieve_t)retrieve_tied_array, /* SX_TIED_ARRAY */
1494     (sv_retrieve_t)retrieve_tied_hash,  /* SX_TIED_HASH */
1495     (sv_retrieve_t)retrieve_tied_scalar,/* SX_TIED_SCALAR */
1496     (sv_retrieve_t)retrieve_sv_undef,   /* SX_SV_UNDEF */
1497     (sv_retrieve_t)retrieve_sv_yes,     /* SX_SV_YES */
1498     (sv_retrieve_t)retrieve_sv_no,      /* SX_SV_NO */
1499     (sv_retrieve_t)retrieve_blessed,    /* SX_BLESS */
1500     (sv_retrieve_t)retrieve_idx_blessed,/* SX_IX_BLESS */
1501     (sv_retrieve_t)retrieve_hook,       /* SX_HOOK */
1502     (sv_retrieve_t)retrieve_overloaded, /* SX_OVERLOAD */
1503     (sv_retrieve_t)retrieve_tied_key,   /* SX_TIED_KEY */
1504     (sv_retrieve_t)retrieve_tied_idx,   /* SX_TIED_IDX */
1505     (sv_retrieve_t)retrieve_utf8str,    /* SX_UTF8STR  */
1506     (sv_retrieve_t)retrieve_lutf8str,   /* SX_LUTF8STR */
1507     (sv_retrieve_t)retrieve_flag_hash,  /* SX_HASH */
1508     (sv_retrieve_t)retrieve_code,       /* SX_CODE */
1509     (sv_retrieve_t)retrieve_weakref,    /* SX_WEAKREF */
1510     (sv_retrieve_t)retrieve_weakoverloaded,/* SX_WEAKOVERLOAD */
1511     (sv_retrieve_t)retrieve_vstring,    /* SX_VSTRING */
1512     (sv_retrieve_t)retrieve_lvstring,   /* SX_LVSTRING */
1513     (sv_retrieve_t)retrieve_svundef_elem,/* SX_SVUNDEF_ELEM */
1514     (sv_retrieve_t)retrieve_regexp,     /* SX_REGEXP */
1515     (sv_retrieve_t)retrieve_lobject,    /* SX_LOBJECT */
1516     (sv_retrieve_t)retrieve_other,      /* SX_LAST */
1517 };
1518
1519 #define RETRIEVE(c,x) ((x) >= SX_LAST ? retrieve_other : *(c)->retrieve_vtbl[x])
1520
1521 static SV *mbuf2sv(pTHX);
1522
1523 /***
1524  *** Context management.
1525  ***/
1526
1527 /*
1528  * init_perinterp
1529  *
1530  * Called once per "thread" (interpreter) to initialize some global context.
1531  */
1532 static void init_perinterp(pTHX)
1533 {
1534     INIT_STCXT;
1535     INIT_TRACEME;
1536     cxt->netorder = 0;          /* true if network order used */
1537     cxt->forgive_me = -1;       /* whether to be forgiving... */
1538     cxt->accept_future_minor = -1; /* would otherwise occur too late */
1539 }
1540
1541 /*
1542  * reset_context
1543  *
1544  * Called at the end of every context cleaning, to perform common reset
1545  * operations.
1546  */
1547 static void reset_context(stcxt_t *cxt)
1548 {
1549     cxt->entry = 0;
1550     cxt->s_dirty = 0;
1551     cxt->recur_sv = NULL;
1552     cxt->recur_depth = 0;
1553     cxt->optype &= ~(ST_STORE|ST_RETRIEVE);     /* Leave ST_CLONE alone */
1554 }
1555
1556 /*
1557  * init_store_context
1558  *
1559  * Initialize a new store context for real recursion.
1560  */
1561 static void init_store_context(pTHX_
1562         stcxt_t *cxt,
1563         PerlIO *f,
1564         int optype,
1565         int network_order)
1566 {
1567     INIT_TRACEME;
1568
1569     TRACEME(("init_store_context"));
1570
1571     cxt->netorder = network_order;
1572     cxt->forgive_me = -1;               /* Fetched from perl if needed */
1573     cxt->deparse = -1;                  /* Idem */
1574     cxt->eval = NULL;                   /* Idem */
1575     cxt->canonical = -1;                /* Idem */
1576     cxt->tagnum = -1;                   /* Reset tag numbers */
1577     cxt->classnum = -1;                 /* Reset class numbers */
1578     cxt->fio = f;                       /* Where I/O are performed */
1579     cxt->optype = optype;               /* A store, or a deep clone */
1580     cxt->entry = 1;                     /* No recursion yet */
1581
1582     /*
1583      * The 'hseen' table is used to keep track of each SV stored and their
1584      * associated tag numbers is special. It is "abused" because the
1585      * values stored are not real SV, just integers cast to (SV *),
1586      * which explains the freeing below.
1587      *
1588      * It is also one possible bottleneck to achieve good storing speed,
1589      * so the "shared keys" optimization is turned off (unlikely to be
1590      * of any use here), and the hash table is "pre-extended". Together,
1591      * those optimizations increase the throughput by 12%.
1592      */
1593
1594 #ifdef USE_PTR_TABLE
1595     cxt->pseen = ptr_table_new();
1596     cxt->hseen = 0;
1597 #else
1598     cxt->hseen = newHV();       /* Table where seen objects are stored */
1599     HvSHAREKEYS_off(cxt->hseen);
1600 #endif
1601     /*
1602      * The following does not work well with perl5.004_04, and causes
1603      * a core dump later on, in a completely unrelated spot, which
1604      * makes me think there is a memory corruption going on.
1605      *
1606      * Calling hv_ksplit(hseen, HBUCKETS) instead of manually hacking
1607      * it below does not make any difference. It seems to work fine
1608      * with perl5.004_68 but given the probable nature of the bug,
1609      * that does not prove anything.
1610      *
1611      * It's a shame because increasing the amount of buckets raises
1612      * store() throughput by 5%, but until I figure this out, I can't
1613      * allow for this to go into production.
1614      *
1615      * It is reported fixed in 5.005, hence the #if.
1616      */
1617 #define HBUCKETS        4096            /* Buckets for %hseen */
1618 #ifndef USE_PTR_TABLE
1619     HvMAX(cxt->hseen) = HBUCKETS - 1;   /* keys %hseen = $HBUCKETS; */
1620 #endif
1621
1622     /*
1623      * The 'hclass' hash uses the same settings as 'hseen' above, but it is
1624      * used to assign sequential tags (numbers) to class names for blessed
1625      * objects.
1626      *
1627      * We turn the shared key optimization on.
1628      */
1629
1630     cxt->hclass = newHV();              /* Where seen classnames are stored */
1631
1632     HvMAX(cxt->hclass) = HBUCKETS - 1;  /* keys %hclass = $HBUCKETS; */
1633
1634     /*
1635      * The 'hook' hash table is used to keep track of the references on
1636      * the STORABLE_freeze hook routines, when found in some class name.
1637      *
1638      * It is assumed that the inheritance tree will not be changed during
1639      * storing, and that no new method will be dynamically created by the
1640      * hooks.
1641      */
1642
1643     cxt->hook = newHV();                /* Table where hooks are cached */
1644
1645     /*
1646      * The 'hook_seen' array keeps track of all the SVs returned by
1647      * STORABLE_freeze hooks for us to serialize, so that they are not
1648      * reclaimed until the end of the serialization process.  Each SV is
1649      * only stored once, the first time it is seen.
1650      */
1651
1652     cxt->hook_seen = newAV(); /* Lists SVs returned by STORABLE_freeze */
1653
1654     cxt->max_recur_depth = SvIV(get_sv("Storable::recursion_limit", GV_ADD));
1655     cxt->max_recur_depth_hash = SvIV(get_sv("Storable::recursion_limit_hash", GV_ADD));
1656 }
1657
1658 /*
1659  * clean_store_context
1660  *
1661  * Clean store context by
1662  */
1663 static void clean_store_context(pTHX_ stcxt_t *cxt)
1664 {
1665     HE *he;
1666
1667     TRACEMED(("clean_store_context"));
1668
1669     ASSERT(cxt->optype & ST_STORE, ("was performing a store()"));
1670
1671     /*
1672      * Insert real values into hashes where we stored faked pointers.
1673      */
1674
1675 #ifndef USE_PTR_TABLE
1676     if (cxt->hseen) {
1677         hv_iterinit(cxt->hseen);
1678         while ((he = hv_iternext(cxt->hseen)))  /* Extra () for -Wall */
1679             HeVAL(he) = &PL_sv_undef;
1680     }
1681 #endif
1682
1683     if (cxt->hclass) {
1684         hv_iterinit(cxt->hclass);
1685         while ((he = hv_iternext(cxt->hclass))) /* Extra () for -Wall */
1686             HeVAL(he) = &PL_sv_undef;
1687     }
1688
1689     /*
1690      * And now dispose of them...
1691      *
1692      * The surrounding if() protection has been added because there might be
1693      * some cases where this routine is called more than once, during
1694      * exceptional events.  This was reported by Marc Lehmann when Storable
1695      * is executed from mod_perl, and the fix was suggested by him.
1696      *          -- RAM, 20/12/2000
1697      */
1698
1699 #ifdef USE_PTR_TABLE
1700     if (cxt->pseen) {
1701         struct ptr_tbl *pseen = cxt->pseen;
1702         cxt->pseen = 0;
1703         ptr_table_free(pseen);
1704     }
1705     assert(!cxt->hseen);
1706 #else
1707     if (cxt->hseen) {
1708         HV *hseen = cxt->hseen;
1709         cxt->hseen = 0;
1710         hv_undef(hseen);
1711         sv_free((SV *) hseen);
1712     }
1713 #endif
1714
1715     if (cxt->hclass) {
1716         HV *hclass = cxt->hclass;
1717         cxt->hclass = 0;
1718         hv_undef(hclass);
1719         sv_free((SV *) hclass);
1720     }
1721
1722     if (cxt->hook) {
1723         HV *hook = cxt->hook;
1724         cxt->hook = 0;
1725         hv_undef(hook);
1726         sv_free((SV *) hook);
1727     }
1728
1729     if (cxt->hook_seen) {
1730         AV *hook_seen = cxt->hook_seen;
1731         cxt->hook_seen = 0;
1732         av_undef(hook_seen);
1733         sv_free((SV *) hook_seen);
1734     }
1735
1736     cxt->forgive_me = -1;       /* Fetched from perl if needed */
1737     cxt->deparse = -1;          /* Idem */
1738     if (cxt->eval) {
1739         SvREFCNT_dec(cxt->eval);
1740     }
1741     cxt->eval = NULL;           /* Idem */
1742     cxt->canonical = -1;        /* Idem */
1743
1744     reset_context(cxt);
1745 }
1746
1747 /*
1748  * init_retrieve_context
1749  *
1750  * Initialize a new retrieve context for real recursion.
1751  */
1752 static void init_retrieve_context(pTHX_
1753         stcxt_t *cxt, int optype, int is_tainted)
1754 {
1755     INIT_TRACEME;
1756
1757     TRACEME(("init_retrieve_context"));
1758
1759     /*
1760      * The hook hash table is used to keep track of the references on
1761      * the STORABLE_thaw hook routines, when found in some class name.
1762      *
1763      * It is assumed that the inheritance tree will not be changed during
1764      * storing, and that no new method will be dynamically created by the
1765      * hooks.
1766      */
1767
1768     cxt->hook  = newHV();                       /* Caches STORABLE_thaw */
1769
1770 #ifdef USE_PTR_TABLE
1771     cxt->pseen = 0;
1772 #endif
1773
1774     /*
1775      * If retrieving an old binary version, the cxt->retrieve_vtbl variable
1776      * was set to sv_old_retrieve. We'll need a hash table to keep track of
1777      * the correspondence between the tags and the tag number used by the
1778      * new retrieve routines.
1779      */
1780
1781     cxt->hseen = (((void*)cxt->retrieve_vtbl == (void*)sv_old_retrieve)
1782                   ? newHV() : 0);
1783
1784     cxt->aseen = newAV();       /* Where retrieved objects are kept */
1785     cxt->where_is_undef = UNSET_NTAG_T; /* Special case for PL_sv_undef */
1786     cxt->aclass = newAV();      /* Where seen classnames are kept */
1787     cxt->tagnum = 0;            /* Have to count objects... */
1788     cxt->classnum = 0;          /* ...and class names as well */
1789     cxt->optype = optype;
1790     cxt->s_tainted = is_tainted;
1791     cxt->entry = 1;             /* No recursion yet */
1792 #ifndef HAS_RESTRICTED_HASHES
1793     cxt->derestrict = -1;       /* Fetched from perl if needed */
1794 #endif
1795 #ifndef HAS_UTF8_ALL
1796     cxt->use_bytes = -1;        /* Fetched from perl if needed */
1797 #endif
1798     cxt->accept_future_minor = -1;/* Fetched from perl if needed */
1799     cxt->in_retrieve_overloaded = 0;
1800
1801     cxt->max_recur_depth = SvIV(get_sv("Storable::recursion_limit", GV_ADD));
1802     cxt->max_recur_depth_hash = SvIV(get_sv("Storable::recursion_limit_hash", GV_ADD));
1803 }
1804
1805 /*
1806  * clean_retrieve_context
1807  *
1808  * Clean retrieve context by
1809  */
1810 static void clean_retrieve_context(pTHX_ stcxt_t *cxt)
1811 {
1812     TRACEMED(("clean_retrieve_context"));
1813
1814     ASSERT(cxt->optype & ST_RETRIEVE, ("was performing a retrieve()"));
1815
1816     if (cxt->aseen) {
1817         AV *aseen = cxt->aseen;
1818         cxt->aseen = 0;
1819         av_undef(aseen);
1820         sv_free((SV *) aseen);
1821     }
1822     cxt->where_is_undef = UNSET_NTAG_T;
1823
1824     if (cxt->aclass) {
1825         AV *aclass = cxt->aclass;
1826         cxt->aclass = 0;
1827         av_undef(aclass);
1828         sv_free((SV *) aclass);
1829     }
1830
1831     if (cxt->hook) {
1832         HV *hook = cxt->hook;
1833         cxt->hook = 0;
1834         hv_undef(hook);
1835         sv_free((SV *) hook);
1836     }
1837
1838     if (cxt->hseen) {
1839         HV *hseen = cxt->hseen;
1840         cxt->hseen = 0;
1841         hv_undef(hseen);
1842         sv_free((SV *) hseen);  /* optional HV, for backward compat. */
1843     }
1844
1845 #ifndef HAS_RESTRICTED_HASHES
1846     cxt->derestrict = -1;               /* Fetched from perl if needed */
1847 #endif
1848 #ifndef HAS_UTF8_ALL
1849     cxt->use_bytes = -1;                /* Fetched from perl if needed */
1850 #endif
1851     cxt->accept_future_minor = -1;      /* Fetched from perl if needed */
1852
1853     cxt->in_retrieve_overloaded = 0;
1854     reset_context(cxt);
1855 }
1856
1857 /*
1858  * clean_context
1859  *
1860  * A workaround for the CROAK bug: cleanup the last context.
1861  */
1862 static void clean_context(pTHX_ stcxt_t *cxt)
1863 {
1864     TRACEMED(("clean_context"));
1865
1866     ASSERT(cxt->s_dirty, ("dirty context"));
1867
1868     if (cxt->membuf_ro)
1869         MBUF_RESTORE();
1870
1871     ASSERT(!cxt->membuf_ro, ("mbase is not read-only"));
1872
1873     if (cxt->optype & ST_RETRIEVE)
1874         clean_retrieve_context(aTHX_ cxt);
1875     else if (cxt->optype & ST_STORE)
1876         clean_store_context(aTHX_ cxt);
1877     else
1878         reset_context(cxt);
1879
1880     ASSERT(!cxt->s_dirty, ("context is clean"));
1881     ASSERT(cxt->entry == 0, ("context is reset"));
1882 }
1883
1884 /*
1885  * allocate_context
1886  *
1887  * Allocate a new context and push it on top of the parent one.
1888  * This new context is made globally visible via SET_STCXT().
1889  */
1890 static stcxt_t *allocate_context(pTHX_ stcxt_t *parent_cxt)
1891 {
1892     stcxt_t *cxt;
1893
1894     ASSERT(!parent_cxt->s_dirty, ("parent context clean"));
1895
1896     NEW_STORABLE_CXT_OBJ(cxt);
1897     TRACEMED(("allocate_context"));
1898
1899     cxt->prev = parent_cxt->my_sv;
1900     SET_STCXT(cxt);
1901
1902     ASSERT(!cxt->s_dirty, ("clean context"));
1903
1904     return cxt;
1905 }
1906
1907 /*
1908  * free_context
1909  *
1910  * Free current context, which cannot be the "root" one.
1911  * Make the context underneath globally visible via SET_STCXT().
1912  */
1913 static void free_context(pTHX_ stcxt_t *cxt)
1914 {
1915     stcxt_t *prev = (stcxt_t *)(cxt->prev ? SvPVX(SvRV(cxt->prev)) : 0);
1916
1917     TRACEMED(("free_context"));
1918
1919     ASSERT(!cxt->s_dirty, ("clean context"));
1920     ASSERT(prev, ("not freeing root context"));
1921     assert(prev);
1922
1923     SvREFCNT_dec(cxt->my_sv);
1924     SET_STCXT(prev);
1925
1926     ASSERT(cxt, ("context not void"));
1927 }
1928
1929 /***
1930  *** Predicates.
1931  ***/
1932
1933 /* these two functions are currently only used within asserts */
1934 #ifdef DASSERT
1935 /*
1936  * is_storing
1937  *
1938  * Tells whether we're in the middle of a store operation.
1939  */
1940 static int is_storing(pTHX)
1941 {
1942     dSTCXT;
1943
1944     return cxt->entry && (cxt->optype & ST_STORE);
1945 }
1946
1947 /*
1948  * is_retrieving
1949  *
1950  * Tells whether we're in the middle of a retrieve operation.
1951  */
1952 static int is_retrieving(pTHX)
1953 {
1954     dSTCXT;
1955
1956     return cxt->entry && (cxt->optype & ST_RETRIEVE);
1957 }
1958 #endif
1959
1960 /*
1961  * last_op_in_netorder
1962  *
1963  * Returns whether last operation was made using network order.
1964  *
1965  * This is typically out-of-band information that might prove useful
1966  * to people wishing to convert native to network order data when used.
1967  */
1968 static int last_op_in_netorder(pTHX)
1969 {
1970     dSTCXT;
1971
1972     assert(cxt);
1973     return cxt->netorder;
1974 }
1975
1976 /***
1977  *** Hook lookup and calling routines.
1978  ***/
1979
1980 /*
1981  * pkg_fetchmeth
1982  *
1983  * A wrapper on gv_fetchmethod_autoload() which caches results.
1984  *
1985  * Returns the routine reference as an SV*, or null if neither the package
1986  * nor its ancestors know about the method.
1987  */
1988 static SV *pkg_fetchmeth(pTHX_
1989         HV *cache,
1990         HV *pkg,
1991         const char *method)
1992 {
1993     GV *gv;
1994     SV *sv;
1995     const char *hvname = HvNAME_get(pkg);
1996 #ifdef DEBUGME
1997     dSTCXT;
1998 #endif
1999
2000     /*
2001      * The following code is the same as the one performed by UNIVERSAL::can
2002      * in the Perl core.
2003      */
2004
2005     gv = gv_fetchmethod_autoload(pkg, method, FALSE);
2006     if (gv && isGV(gv)) {
2007         sv = newRV_inc((SV*) GvCV(gv));
2008         TRACEME(("%s->%s: 0x%" UVxf, hvname, method, PTR2UV(sv)));
2009     } else {
2010         sv = newSVsv(&PL_sv_undef);
2011         TRACEME(("%s->%s: not found", hvname, method));
2012     }
2013
2014     /*
2015      * Cache the result, ignoring failure: if we can't store the value,
2016      * it just won't be cached.
2017      */
2018
2019     (void) hv_store(cache, hvname, strlen(hvname), sv, 0);
2020
2021     return SvOK(sv) ? sv : (SV *) 0;
2022 }
2023
2024 /*
2025  * pkg_hide
2026  *
2027  * Force cached value to be undef: hook ignored even if present.
2028  */
2029 static void pkg_hide(pTHX_
2030         HV *cache,
2031         HV *pkg,
2032         const char *method)
2033 {
2034     const char *hvname = HvNAME_get(pkg);
2035     PERL_UNUSED_ARG(method);
2036     (void) hv_store(cache,
2037                     hvname, strlen(hvname), newSVsv(&PL_sv_undef), 0);
2038 }
2039
2040 /*
2041  * pkg_uncache
2042  *
2043  * Discard cached value: a whole fetch loop will be retried at next lookup.
2044  */
2045 static void pkg_uncache(pTHX_
2046         HV *cache,
2047         HV *pkg,
2048         const char *method)
2049 {
2050     const char *hvname = HvNAME_get(pkg);
2051     PERL_UNUSED_ARG(method);
2052     (void) hv_delete(cache, hvname, strlen(hvname), G_DISCARD);
2053 }
2054
2055 /*
2056  * pkg_can
2057  *
2058  * Our own "UNIVERSAL::can", which caches results.
2059  *
2060  * Returns the routine reference as an SV*, or null if the object does not
2061  * know about the method.
2062  */
2063 static SV *pkg_can(pTHX_
2064         HV *cache,
2065         HV *pkg,
2066         const char *method)
2067 {
2068     SV **svh;
2069     SV *sv;
2070     const char *hvname = HvNAME_get(pkg);
2071 #ifdef DEBUGME
2072     dSTCXT;
2073 #endif
2074
2075     TRACEME(("pkg_can for %s->%s", hvname, method));
2076
2077     /*
2078      * Look into the cache to see whether we already have determined
2079      * where the routine was, if any.
2080      *
2081      * NOTA BENE: we don't use 'method' at all in our lookup, since we know
2082      * that only one hook (i.e. always the same) is cached in a given cache.
2083      */
2084
2085     svh = hv_fetch(cache, hvname, strlen(hvname), FALSE);
2086     if (svh) {
2087         sv = *svh;
2088         if (!SvOK(sv)) {
2089             TRACEME(("cached %s->%s: not found", hvname, method));
2090             return (SV *) 0;
2091         } else {
2092             TRACEME(("cached %s->%s: 0x%" UVxf,
2093                      hvname, method, PTR2UV(sv)));
2094             return sv;
2095         }
2096     }
2097
2098     TRACEME(("not cached yet"));
2099     return pkg_fetchmeth(aTHX_ cache, pkg, method);     /* Fetch and cache */
2100 }
2101
2102 /*
2103  * scalar_call
2104  *
2105  * Call routine as obj->hook(av) in scalar context.
2106  * Propagates the single returned value if not called in void context.
2107  */
2108 static SV *scalar_call(pTHX_
2109         SV *obj,
2110         SV *hook,
2111         int cloning,
2112         AV *av,
2113         I32 flags)
2114 {
2115     dSP;
2116     int count;
2117     SV *sv = 0;
2118 #ifdef DEBUGME
2119     dSTCXT;
2120 #endif
2121
2122     TRACEME(("scalar_call (cloning=%d)", cloning));
2123
2124     ENTER;
2125     SAVETMPS;
2126
2127     PUSHMARK(sp);
2128     XPUSHs(obj);
2129     XPUSHs(sv_2mortal(newSViv(cloning)));               /* Cloning flag */
2130     if (av) {
2131         SV **ary = AvARRAY(av);
2132         SSize_t cnt = AvFILLp(av) + 1;
2133         SSize_t i;
2134         XPUSHs(ary[0]);                                 /* Frozen string */
2135         for (i = 1; i < cnt; i++) {
2136             TRACEME(("pushing arg #%d (0x%" UVxf ")...",
2137                      (int)i, PTR2UV(ary[i])));
2138             XPUSHs(sv_2mortal(newRV_inc(ary[i])));
2139         }
2140     }
2141     PUTBACK;
2142
2143     TRACEME(("calling..."));
2144     count = call_sv(hook, flags);       /* Go back to Perl code */
2145     TRACEME(("count = %d", count));
2146
2147     SPAGAIN;
2148
2149     if (count) {
2150         sv = POPs;
2151         SvREFCNT_inc(sv); /* We're returning it, must stay alive! */
2152     }
2153
2154     PUTBACK;
2155     FREETMPS;
2156     LEAVE;
2157
2158     return sv;
2159 }
2160
2161 /*
2162  * array_call
2163  *
2164  * Call routine obj->hook(cloning) in list context.
2165  * Returns the list of returned values in an array.
2166  */
2167 static AV *array_call(pTHX_
2168         SV *obj,
2169         SV *hook,
2170         int cloning)
2171 {
2172     dSP;
2173     int count;
2174     AV *av;
2175     int i;
2176 #ifdef DEBUGME
2177     dSTCXT;
2178 #endif
2179
2180     TRACEME(("array_call (cloning=%d)", cloning));
2181
2182     ENTER;
2183     SAVETMPS;
2184
2185     PUSHMARK(sp);
2186     XPUSHs(obj);                                /* Target object */
2187     XPUSHs(sv_2mortal(newSViv(cloning)));       /* Cloning flag */
2188     PUTBACK;
2189
2190     count = call_sv(hook, G_ARRAY);     /* Go back to Perl code */
2191
2192     SPAGAIN;
2193
2194     av = newAV();
2195     for (i = count - 1; i >= 0; i--) {
2196         SV *sv = POPs;
2197         av_store(av, i, SvREFCNT_inc(sv));
2198     }
2199
2200     PUTBACK;
2201     FREETMPS;
2202     LEAVE;
2203
2204     return av;
2205 }
2206
2207 #if PERL_VERSION_LT(5,15,0)
2208 static void
2209 cleanup_recursive_av(pTHX_ AV* av) {
2210     SSize_t i = AvFILLp(av);
2211     SV** arr = AvARRAY(av);
2212     if (SvMAGICAL(av)) return;
2213     while (i >= 0) {
2214         if (arr[i]) {
2215 #if PERL_VERSION_LT(5,14,0)
2216             arr[i] = NULL;
2217 #else
2218             SvREFCNT_dec(arr[i]);
2219 #endif
2220         }
2221         i--;
2222     }
2223 }
2224
2225 #ifndef SvREFCNT_IMMORTAL
2226 #ifdef DEBUGGING
2227    /* exercise the immortal resurrection code in sv_free2() */
2228 #  define SvREFCNT_IMMORTAL 1000
2229 #else
2230 #  define SvREFCNT_IMMORTAL ((~(U32)0)/2)
2231 #endif
2232 #endif
2233
2234 static void
2235 cleanup_recursive_hv(pTHX_ HV* hv) {
2236     SSize_t i = HvTOTALKEYS(hv);
2237     HE** arr = HvARRAY(hv);
2238     if (SvMAGICAL(hv)) return;
2239     while (i >= 0) {
2240         if (arr[i]) {
2241             SvREFCNT(HeVAL(arr[i])) = SvREFCNT_IMMORTAL;
2242             arr[i] = NULL; /* let it leak. too dangerous to clean it up here */
2243         }
2244         i--;
2245     }
2246 #if PERL_VERSION_LT(5,8,0)
2247     ((XPVHV*)SvANY(hv))->xhv_array = NULL;
2248 #else
2249     HvARRAY(hv) = NULL;
2250 #endif
2251     HvTOTALKEYS(hv) = 0;
2252 }
2253 static void
2254 cleanup_recursive_rv(pTHX_ SV* sv) {
2255     if (sv && SvROK(sv))
2256         SvREFCNT_dec(SvRV(sv));
2257 }
2258 static void
2259 cleanup_recursive_data(pTHX_ SV* sv) {
2260     if (SvTYPE(sv) == SVt_PVAV) {
2261         cleanup_recursive_av(aTHX_ (AV*)sv);
2262     }
2263     else if (SvTYPE(sv) == SVt_PVHV) {
2264         cleanup_recursive_hv(aTHX_ (HV*)sv);
2265     }
2266     else {
2267         cleanup_recursive_rv(aTHX_ sv);
2268     }
2269 }
2270 #endif
2271
2272 /*
2273  * known_class
2274  *
2275  * Lookup the class name in the 'hclass' table and either assign it a new ID
2276  * or return the existing one, by filling in 'classnum'.
2277  *
2278  * Return true if the class was known, false if the ID was just generated.
2279  */
2280 static int known_class(pTHX_
2281         stcxt_t *cxt,
2282         char *name,             /* Class name */
2283         int len,                /* Name length */
2284         I32 *classnum)
2285 {
2286     SV **svh;
2287     HV *hclass = cxt->hclass;
2288
2289     TRACEME(("known_class (%s)", name));
2290
2291     /*
2292      * Recall that we don't store pointers in this hash table, but tags.
2293      * Therefore, we need LOW_32BITS() to extract the relevant parts.
2294      */
2295
2296     svh = hv_fetch(hclass, name, len, FALSE);
2297     if (svh) {
2298         *classnum = LOW_32BITS(*svh);
2299         return TRUE;
2300     }
2301
2302     /*
2303      * Unknown classname, we need to record it.
2304      */
2305
2306     cxt->classnum++;
2307     if (!hv_store(hclass, name, len, INT2PTR(SV*, cxt->classnum), 0))
2308         CROAK(("Unable to record new classname"));
2309
2310     *classnum = cxt->classnum;
2311     return FALSE;
2312 }
2313
2314 /***
2315  *** Specific store routines.
2316  ***/
2317
2318 /*
2319  * store_ref
2320  *
2321  * Store a reference.
2322  * Layout is SX_REF <object> or SX_OVERLOAD <object>.
2323  */
2324 static int store_ref(pTHX_ stcxt_t *cxt, SV *sv)
2325 {
2326     int retval;
2327     int is_weak = 0;
2328     TRACEME(("store_ref (0x%" UVxf ")", PTR2UV(sv)));
2329
2330     /*
2331      * Follow reference, and check if target is overloaded.
2332      */
2333
2334 #ifdef SvWEAKREF
2335     if (SvWEAKREF(sv))
2336         is_weak = 1;
2337     TRACEME(("ref (0x%" UVxf ") is%s weak", PTR2UV(sv),
2338              is_weak ? "" : "n't"));
2339 #endif
2340     sv = SvRV(sv);
2341
2342     if (SvOBJECT(sv)) {
2343         HV *stash = (HV *) SvSTASH(sv);
2344         if (stash && Gv_AMG(stash)) {
2345             TRACEME(("ref (0x%" UVxf ") is overloaded", PTR2UV(sv)));
2346             PUTMARK(is_weak ? SX_WEAKOVERLOAD : SX_OVERLOAD);
2347         } else
2348             PUTMARK(is_weak ? SX_WEAKREF : SX_REF);
2349     } else
2350         PUTMARK(is_weak ? SX_WEAKREF : SX_REF);
2351
2352     cxt->recur_sv = sv;
2353
2354     TRACEME((">ref recur_depth %" IVdf ", recur_sv (0x%" UVxf ") max %" IVdf, cxt->recur_depth,
2355              PTR2UV(cxt->recur_sv), cxt->max_recur_depth));
2356     if (RECURSION_TOO_DEEP()) {
2357 #if PERL_VERSION_LT(5,15,0)
2358         cleanup_recursive_data(aTHX_ (SV*)sv);
2359 #endif
2360         CROAK((MAX_DEPTH_ERROR));
2361     }
2362
2363     retval = store(aTHX_ cxt, sv);
2364     if (cxt->max_recur_depth != -1 && cxt->recur_depth > 0) {
2365         TRACEME(("<ref recur_depth --%" IVdf, cxt->recur_depth));
2366         --cxt->recur_depth;
2367     }
2368     return retval;
2369 }
2370
2371 /*
2372  * store_scalar
2373  *
2374  * Store a scalar.
2375  *
2376  * Layout is SX_LSCALAR <length> <data>, SX_SCALAR <length> <data> or SX_UNDEF.
2377  * SX_LUTF8STR and SX_UTF8STR are used for UTF-8 strings.
2378  * The <data> section is omitted if <length> is 0.
2379  *
2380  * For vstrings, the vstring portion is stored first with
2381  * SX_LVSTRING <length> <data> or SX_VSTRING <length> <data>, followed by
2382  * SX_(L)SCALAR or SX_(L)UTF8STR with the actual PV.
2383  *
2384  * If integer or double, the layout is SX_INTEGER <data> or SX_DOUBLE <data>.
2385  * Small integers (within [-127, +127]) are stored as SX_BYTE <byte>.
2386  *
2387  * For huge strings use SX_LOBJECT SX_type SX_U64 <type> <data>
2388  */
2389 static int store_scalar(pTHX_ stcxt_t *cxt, SV *sv)
2390 {
2391     IV iv;
2392     char *pv;
2393     STRLEN len;
2394     U32 flags = SvFLAGS(sv);    /* "cc -O" may put it in register */
2395
2396     TRACEME(("store_scalar (0x%" UVxf ")", PTR2UV(sv)));
2397
2398     /*
2399      * For efficiency, break the SV encapsulation by peaking at the flags
2400      * directly without using the Perl macros to avoid dereferencing
2401      * sv->sv_flags each time we wish to check the flags.
2402      */
2403
2404     if (!(flags & SVf_OK)) {                    /* !SvOK(sv) */
2405         if (sv == &PL_sv_undef) {
2406             TRACEME(("immortal undef"));
2407             PUTMARK(SX_SV_UNDEF);
2408         } else {
2409             TRACEME(("undef at 0x%" UVxf, PTR2UV(sv)));
2410             PUTMARK(SX_UNDEF);
2411         }
2412         return 0;
2413     }
2414
2415     /*
2416      * Always store the string representation of a scalar if it exists.
2417      * Gisle Aas provided me with this test case, better than a long speach:
2418      *
2419      *  perl -MDevel::Peek -le '$a="abc"; $a+0; Dump($a)'
2420      *  SV = PVNV(0x80c8520)
2421      *       REFCNT = 1
2422      *       FLAGS = (NOK,POK,pNOK,pPOK)
2423      *       IV = 0
2424      *       NV = 0
2425      *       PV = 0x80c83d0 "abc"\0
2426      *       CUR = 3
2427      *       LEN = 4
2428      *
2429      * Write SX_SCALAR, length, followed by the actual data.
2430      *
2431      * Otherwise, write an SX_BYTE, SX_INTEGER or an SX_DOUBLE as
2432      * appropriate, followed by the actual (binary) data. A double
2433      * is written as a string if network order, for portability.
2434      *
2435      * NOTE: instead of using SvNOK(sv), we test for SvNOKp(sv).
2436      * The reason is that when the scalar value is tainted, the SvNOK(sv)
2437      * value is false.
2438      *
2439      * The test for a read-only scalar with both POK and NOK set is meant
2440      * to quickly detect &PL_sv_yes and &PL_sv_no without having to pay the
2441      * address comparison for each scalar we store.
2442      */
2443
2444 #define SV_MAYBE_IMMORTAL (SVf_READONLY|SVf_POK|SVf_NOK)
2445
2446     if ((flags & SV_MAYBE_IMMORTAL) == SV_MAYBE_IMMORTAL) {
2447         if (sv == &PL_sv_yes) {
2448             TRACEME(("immortal yes"));
2449             PUTMARK(SX_SV_YES);
2450         } else if (sv == &PL_sv_no) {
2451             TRACEME(("immortal no"));
2452             PUTMARK(SX_SV_NO);
2453         } else {
2454             pv = SvPV(sv, len);         /* We know it's SvPOK */
2455             goto string;                        /* Share code below */
2456         }
2457     } else if (flags & SVf_POK) {
2458         /* public string - go direct to string read.  */
2459         goto string_readlen;
2460     } else if (
2461 #if PERL_VERSION_LT(5,7,0)
2462                /* For 5.6 and earlier NV flag trumps IV flag, so only use integer
2463                   direct if NV flag is off.  */
2464                (flags & (SVf_NOK | SVf_IOK)) == SVf_IOK
2465 #else
2466                /* 5.7 rules are that if IV public flag is set, IV value is as
2467                   good, if not better, than NV value.  */
2468                flags & SVf_IOK
2469 #endif
2470                ) {
2471         iv = SvIV(sv);
2472         /*
2473          * Will come here from below with iv set if double is an integer.
2474          */
2475     integer:
2476
2477         /* Sorry. This isn't in 5.005_56 (IIRC) or earlier.  */
2478 #ifdef SVf_IVisUV
2479         /* Need to do this out here, else 0xFFFFFFFF becomes iv of -1
2480          * (for example) and that ends up in the optimised small integer
2481          * case. 
2482          */
2483         if ((flags & SVf_IVisUV) && SvUV(sv) > IV_MAX) {
2484             TRACEME(("large unsigned integer as string, value = %" UVuf,
2485                      SvUV(sv)));
2486             goto string_readlen;
2487         }
2488 #endif
2489         /*
2490          * Optimize small integers into a single byte, otherwise store as
2491          * a real integer (converted into network order if they asked).
2492          */
2493
2494         if (iv >= -128 && iv <= 127) {
2495             unsigned char siv = (unsigned char) (iv + 128); /* [0,255] */
2496             PUTMARK(SX_BYTE);
2497             PUTMARK(siv);
2498             TRACEME(("small integer stored as %d", (int)siv));
2499         } else if (cxt->netorder) {
2500 #ifndef HAS_HTONL
2501             TRACEME(("no htonl, fall back to string for integer"));
2502             goto string_readlen;
2503 #else
2504             I32 niv;
2505
2506
2507 #if IVSIZE > 4
2508             if (
2509 #ifdef SVf_IVisUV
2510                 /* Sorry. This isn't in 5.005_56 (IIRC) or earlier.  */
2511                 ((flags & SVf_IVisUV) && SvUV(sv) > (UV)0x7FFFFFFF) ||
2512 #endif
2513                 (iv > (IV)0x7FFFFFFF) || (iv < -(IV)0x80000000)) {
2514                 /* Bigger than 32 bits.  */
2515                 TRACEME(("large network order integer as string, value = %" IVdf, iv));
2516                 goto string_readlen;
2517             }
2518 #endif
2519
2520             niv = (I32) htonl((I32) iv);
2521             TRACEME(("using network order"));
2522             PUTMARK(SX_NETINT);
2523             WRITE_I32(niv);
2524 #endif
2525         } else {
2526             PUTMARK(SX_INTEGER);
2527             WRITE(&iv, sizeof(iv));
2528         }
2529
2530         TRACEME(("ok (integer 0x%" UVxf ", value = %" IVdf ")", PTR2UV(sv), iv));
2531     } else if (flags & SVf_NOK) {
2532         NV_bytes nv;
2533 #ifdef NV_CLEAR
2534         /* if we can't tell if there's padding, clear the whole NV and hope the
2535            compiler leaves the padding alone
2536         */
2537         Zero(&nv, 1, NV_bytes);
2538 #endif
2539 #if PERL_VERSION_LT(5,7,0)
2540         nv.nv = SvNV(sv);
2541         /*
2542          * Watch for number being an integer in disguise.
2543          */
2544         if (nv.nv == (NV) (iv = I_V(nv.nv))) {
2545             TRACEME(("double %" NVff " is actually integer %" IVdf, nv, iv));
2546             goto integer;               /* Share code above */
2547         }
2548 #else
2549
2550         SvIV_please(sv);
2551         if (SvIOK_notUV(sv)) {
2552             iv = SvIV(sv);
2553             goto integer;               /* Share code above */
2554         }
2555         nv.nv = SvNV(sv);
2556 #endif
2557
2558         if (cxt->netorder) {
2559             TRACEME(("double %" NVff " stored as string", nv.nv));
2560             goto string_readlen;                /* Share code below */
2561         }
2562 #if NV_PADDING
2563         Zero(nv.bytes + NVSIZE - NV_PADDING, NV_PADDING, char);
2564 #endif
2565
2566         PUTMARK(SX_DOUBLE);
2567         WRITE(&nv, sizeof(nv));
2568
2569         TRACEME(("ok (double 0x%" UVxf ", value = %" NVff ")", PTR2UV(sv), nv.nv));
2570
2571     } else if (flags & (SVp_POK | SVp_NOK | SVp_IOK)) {
2572 #ifdef SvVOK
2573         MAGIC *mg;
2574 #endif
2575         UV wlen; /* For 64-bit machines */
2576
2577     string_readlen:
2578         pv = SvPV(sv, len);
2579
2580         /*
2581          * Will come here from above  if it was readonly, POK and NOK but
2582          * neither &PL_sv_yes nor &PL_sv_no.
2583          */
2584     string:
2585
2586 #ifdef SvVOK
2587         if (SvMAGICAL(sv) && (mg = mg_find(sv, 'V'))) {
2588             /* The macro passes this by address, not value, and a lot of
2589                called code assumes that it's 32 bits without checking.  */
2590             const SSize_t len = mg->mg_len;
2591             /* we no longer accept vstrings over I32_SIZE-1, so don't emit
2592                them, also, older Storables handle them badly.
2593             */
2594             if (len >= I32_MAX) {
2595                 CROAK(("vstring too large to freeze"));
2596             }
2597             STORE_PV_LEN((const char *)mg->mg_ptr,
2598                          len, SX_VSTRING, SX_LVSTRING);
2599         }
2600 #endif
2601
2602         wlen = (Size_t)len;
2603         if (SvUTF8 (sv))
2604             STORE_UTF8STR(pv, wlen);
2605         else
2606             STORE_SCALAR(pv, wlen);
2607         TRACEME(("ok (scalar 0x%" UVxf " '%s', length = %" UVuf ")",
2608                  PTR2UV(sv), len >= 2048 ? "<string too long>" : SvPVX(sv),
2609                  (UV)len));
2610     } else {
2611         CROAK(("Can't determine type of %s(0x%" UVxf ")",
2612                sv_reftype(sv, FALSE),
2613                PTR2UV(sv)));
2614     }
2615     return 0;           /* Ok, no recursion on scalars */
2616 }
2617
2618 /*
2619  * store_array
2620  *
2621  * Store an array.
2622  *
2623  * Layout is SX_ARRAY <size> followed by each item, in increasing index order.
2624  * Each item is stored as <object>.
2625  */
2626 static int store_array(pTHX_ stcxt_t *cxt, AV *av)
2627 {
2628     SV **sav;
2629     UV len = av_len(av) + 1;
2630     UV i;
2631     int ret;
2632     SV *const recur_sv = cxt->recur_sv;
2633
2634     TRACEME(("store_array (0x%" UVxf ")", PTR2UV(av)));
2635
2636 #ifdef HAS_U64
2637     if (len > 0x7fffffffu) {
2638         /*
2639          * Large array by emitting SX_LOBJECT 1 U64 data
2640          */
2641         PUTMARK(SX_LOBJECT);
2642         PUTMARK(SX_ARRAY);
2643         W64LEN(len);
2644         TRACEME(("lobject size = %lu", (unsigned long)len));
2645     } else
2646 #endif
2647     {
2648         /*
2649          * Normal array by emitting SX_ARRAY, followed by the array length.
2650          */
2651         I32 l = (I32)len;
2652         PUTMARK(SX_ARRAY);
2653         WLEN(l);
2654         TRACEME(("size = %d", (int)l));
2655     }
2656
2657     TRACEME((">array recur_depth %" IVdf ", recur_sv (0x%" UVxf ") max %" IVdf, cxt->recur_depth,
2658              PTR2UV(cxt->recur_sv), cxt->max_recur_depth));
2659     if (recur_sv != (SV*)av) {
2660         if (RECURSION_TOO_DEEP()) {
2661             /* with <= 5.14 it recurses in the cleanup also, needing 2x stack size */
2662 #if PERL_VERSION_LT(5,15,0)
2663             cleanup_recursive_data(aTHX_ (SV*)av);
2664 #endif
2665             CROAK((MAX_DEPTH_ERROR));
2666         }
2667     }
2668
2669     /*
2670      * Now store each item recursively.
2671      */
2672
2673     for (i = 0; i < len; i++) {
2674         sav = av_fetch(av, i, 0);
2675         if (!sav) {
2676             TRACEME(("(#%d) nonexistent item", (int)i));
2677             STORE_SV_UNDEF();
2678             continue;
2679         }
2680 #if PERL_VERSION_GE(5,19,0)
2681         /* In 5.19.3 and up, &PL_sv_undef can actually be stored in
2682          * an array; it no longer represents nonexistent elements.
2683          * Historically, we have used SX_SV_UNDEF in arrays for
2684          * nonexistent elements, so we use SX_SVUNDEF_ELEM for
2685          * &PL_sv_undef itself. */
2686         if (*sav == &PL_sv_undef) {
2687             TRACEME(("(#%d) undef item", (int)i));
2688             cxt->tagnum++;
2689             PUTMARK(SX_SVUNDEF_ELEM);
2690             continue;
2691         }
2692 #endif
2693         TRACEME(("(#%d) item", (int)i));
2694         if ((ret = store(aTHX_ cxt, *sav)))     /* Extra () for -Wall */
2695             return ret;
2696     }
2697
2698     if (recur_sv != (SV*)av) {
2699         assert(cxt->max_recur_depth == -1 || cxt->recur_depth > 0);
2700         if (cxt->max_recur_depth != -1 && cxt->recur_depth > 0) {
2701             TRACEME(("<array recur_depth --%" IVdf, cxt->recur_depth));
2702             --cxt->recur_depth;
2703         }
2704     }
2705     TRACEME(("ok (array)"));
2706
2707     return 0;
2708 }
2709
2710
2711 #if PERL_VERSION_LT(5,7,0)
2712
2713 /*
2714  * sortcmp
2715  *
2716  * Sort two SVs
2717  * Borrowed from perl source file pp_ctl.c, where it is used by pp_sort.
2718  */
2719 static int
2720 sortcmp(const void *a, const void *b)
2721 {
2722 #if defined(USE_ITHREADS)
2723     dTHX;
2724 #endif /* USE_ITHREADS */
2725     return sv_cmp(*(SV * const *) a, *(SV * const *) b);
2726 }
2727
2728 #endif /* PERL_VERSION_LT(5,7,0) */
2729
2730 /*
2731  * store_hash
2732  *
2733  * Store a hash table.
2734  *
2735  * For a "normal" hash (not restricted, no utf8 keys):
2736  *
2737  * Layout is SX_HASH <size> followed by each key/value pair, in random order.
2738  * Values are stored as <object>.
2739  * Keys are stored as <length> <data>, the <data> section being omitted
2740  * if length is 0.
2741  *
2742  * For a "fancy" hash (restricted or utf8 keys):
2743  *
2744  * Layout is SX_FLAG_HASH <size> <hash flags> followed by each key/value pair,
2745  * in random order.
2746  * Values are stored as <object>.
2747  * Keys are stored as <flags> <length> <data>, the <data> section being omitted
2748  * if length is 0.
2749  * Currently the only hash flag is "restricted"
2750  * Key flags are as for hv.h
2751  */
2752 static int store_hash(pTHX_ stcxt_t *cxt, HV *hv)
2753 {
2754     dVAR;
2755     UV len = (UV)HvTOTALKEYS(hv);
2756     Size_t i;
2757     int ret = 0;
2758     I32 riter;
2759     HE *eiter;
2760     int flagged_hash = ((SvREADONLY(hv)
2761 #ifdef HAS_HASH_KEY_FLAGS
2762                          || HvHASKFLAGS(hv)
2763 #endif
2764                          ) ? 1 : 0);
2765     unsigned char hash_flags = (SvREADONLY(hv) ? SHV_RESTRICTED : 0);
2766     SV * const recur_sv = cxt->recur_sv;
2767
2768     /* 
2769      * Signal hash by emitting SX_HASH, followed by the table length.
2770      * Max number of keys per perl version:
2771      *    IV            - 5.12
2772      *    STRLEN  5.14  - 5.24   (size_t: U32/U64)
2773      *    SSize_t 5.22c - 5.24c  (I32/I64)
2774      *    U32     5.25c -
2775      */
2776
2777     if (len > 0x7fffffffu) { /* keys > I32_MAX */
2778         /* 
2779          * Large hash: SX_LOBJECT type hashflags? U64 data
2780          *
2781          * Stupid limitation:
2782          * Note that perl5 can store more than 2G keys, but only iterate
2783          * over 2G max. (cperl can)
2784          * We need to manually iterate over it then, unsorted.
2785          * But until perl itself cannot do that, skip that.
2786          */
2787         TRACEME(("lobject size = %lu", (unsigned long)len));
2788 #ifdef HAS_U64
2789         PUTMARK(SX_LOBJECT);
2790         if (flagged_hash) {
2791             PUTMARK(SX_FLAG_HASH);
2792             PUTMARK(hash_flags);
2793         } else {
2794             PUTMARK(SX_HASH);
2795         }
2796         W64LEN(len);
2797         return store_lhash(aTHX_ cxt, hv, hash_flags);
2798 #else
2799         /* <5.12 you could store larger hashes, but cannot iterate over them.
2800            So we reject them, it's a bug. */
2801         CROAK(("Cannot store large objects on a 32bit system"));
2802 #endif
2803     } else {
2804         I32 l = (I32)len;
2805         if (flagged_hash) {
2806             TRACEME(("store_hash (0x%" UVxf ") (flags %x)", PTR2UV(hv),
2807                      (unsigned int)hash_flags));
2808             PUTMARK(SX_FLAG_HASH);
2809             PUTMARK(hash_flags);
2810         } else {
2811             TRACEME(("store_hash (0x%" UVxf ")", PTR2UV(hv)));
2812             PUTMARK(SX_HASH);
2813         }
2814         WLEN(l);
2815         TRACEME(("size = %d, used = %d", (int)l, (int)HvUSEDKEYS(hv)));
2816     }
2817
2818     TRACEME((">hash recur_depth %" IVdf ", recur_sv (0x%" UVxf ") max %" IVdf, cxt->recur_depth,
2819              PTR2UV(cxt->recur_sv), cxt->max_recur_depth_hash));
2820     if (recur_sv != (SV*)hv && cxt->max_recur_depth_hash != -1) {
2821         ++cxt->recur_depth;
2822     }
2823     if (RECURSION_TOO_DEEP_HASH()) {
2824 #if PERL_VERSION_LT(5,15,0)
2825         cleanup_recursive_data(aTHX_ (SV*)hv);
2826 #endif
2827         CROAK((MAX_DEPTH_ERROR));
2828     }
2829
2830     /*
2831      * Save possible iteration state via each() on that table.
2832      *
2833      * Note that perl as of 5.24 *can* store more than 2G keys, but *not*
2834      * iterate over it.
2835      * Lengths of hash keys are also limited to I32, which is good.
2836      */
2837
2838     riter = HvRITER_get(hv);
2839     eiter = HvEITER_get(hv);
2840     hv_iterinit(hv);
2841
2842     /*
2843      * Now store each item recursively.
2844      *
2845      * If canonical is defined to some true value then store each
2846      * key/value pair in sorted order otherwise the order is random.
2847      * Canonical order is irrelevant when a deep clone operation is performed.
2848      *
2849      * Fetch the value from perl only once per store() operation, and only
2850      * when needed.
2851      */
2852
2853     if (
2854         !(cxt->optype & ST_CLONE)
2855         && (cxt->canonical == 1
2856             || (cxt->canonical < 0
2857                 && (cxt->canonical =
2858                     (SvTRUE(get_sv("Storable::canonical", GV_ADD))
2859                      ? 1 : 0))))
2860         ) {
2861         /*
2862          * Storing in order, sorted by key.
2863          * Run through the hash, building up an array of keys in a
2864          * mortal array, sort the array and then run through the
2865          * array.
2866          */
2867         AV *av = newAV();
2868         av_extend (av, len);
2869
2870         TRACEME(("using canonical order"));
2871
2872         for (i = 0; i < len; i++) {
2873 #ifdef HAS_RESTRICTED_HASHES
2874             HE *he = hv_iternext_flags(hv, HV_ITERNEXT_WANTPLACEHOLDERS);
2875 #else
2876             HE *he = hv_iternext(hv);
2877 #endif
2878             av_store(av, i, hv_iterkeysv(he));
2879         }
2880
2881         STORE_HASH_SORT;
2882
2883         for (i = 0; i < len; i++) {
2884 #ifdef HAS_RESTRICTED_HASHES
2885             int placeholders = (int)HvPLACEHOLDERS_get(hv);
2886 #endif
2887             unsigned char flags = 0;
2888             char *keyval;
2889             STRLEN keylen_tmp;
2890             I32 keylen;
2891             SV *key = av_shift(av);
2892             /* This will fail if key is a placeholder.
2893                Track how many placeholders we have, and error if we
2894                "see" too many.  */
2895             HE *he  = hv_fetch_ent(hv, key, 0, 0);
2896             SV *val;
2897
2898             if (he) {
2899                 if (!(val =  HeVAL(he))) {
2900                     /* Internal error, not I/O error */
2901                     return 1;
2902                 }
2903             } else {
2904 #ifdef HAS_RESTRICTED_HASHES
2905                 /* Should be a placeholder.  */
2906                 if (placeholders-- < 0) {
2907                     /* This should not happen - number of
2908                        retrieves should be identical to
2909                        number of placeholders.  */
2910                     return 1;
2911                 }
2912                 /* Value is never needed, and PL_sv_undef is
2913                    more space efficient to store.  */
2914                 val = &PL_sv_undef;
2915                 ASSERT (flags == 0,
2916                         ("Flags not 0 but %d", (int)flags));
2917                 flags = SHV_K_PLACEHOLDER;
2918 #else
2919                 return 1;
2920 #endif
2921             }
2922
2923             /*
2924              * Store value first.
2925              */
2926
2927             TRACEME(("(#%d) value 0x%" UVxf, (int)i, PTR2UV(val)));
2928
2929             if ((ret = store(aTHX_ cxt, val)))  /* Extra () for -Wall, grr... */
2930                 goto out;
2931
2932             /*
2933              * Write key string.
2934              * Keys are written after values to make sure retrieval
2935              * can be optimal in terms of memory usage, where keys are
2936              * read into a fixed unique buffer called kbuf.
2937              * See retrieve_hash() for details.
2938              */
2939
2940             /* Implementation of restricted hashes isn't nicely
2941                abstracted:  */
2942             if ((hash_flags & SHV_RESTRICTED)
2943                 && SvTRULYREADONLY(val)) {
2944                 flags |= SHV_K_LOCKED;
2945             }
2946
2947             keyval = SvPV(key, keylen_tmp);
2948             keylen = keylen_tmp;
2949             if (SvUTF8(key)) {
2950                 const char *keysave = keyval;
2951                 bool is_utf8 = TRUE;
2952
2953                 /* Just casting the &klen to (STRLEN) won't work
2954                    well if STRLEN and I32 are of different widths.
2955                    --jhi */
2956                 keyval = (char*)bytes_from_utf8((U8*)keyval,
2957                                                 &keylen_tmp,
2958                                                 &is_utf8);
2959
2960                 /* If we were able to downgrade here, then than
2961                    means that we have  a key which only had chars
2962                    0-255, but was utf8 encoded.  */
2963
2964                 if (keyval != keysave) {
2965                     keylen = keylen_tmp;
2966                     flags |= SHV_K_WASUTF8;
2967                 } else {
2968                     /* keylen_tmp can't have changed, so no need
2969                        to assign back to keylen.  */
2970                     flags |= SHV_K_UTF8;
2971                 }
2972             }
2973
2974             if (flagged_hash) {
2975                 PUTMARK(flags);
2976                 TRACEME(("(#%d) key '%s' flags %x %u", (int)i, keyval, flags, *keyval));
2977             } else {
2978                 /* This is a workaround for a bug in 5.8.0
2979                    that causes the HEK_WASUTF8 flag to be
2980                    set on an HEK without the hash being
2981                    marked as having key flags. We just
2982                    cross our fingers and drop the flag.
2983                    AMS 20030901 */
2984                 assert (flags == 0 || flags == SHV_K_WASUTF8);
2985                 TRACEME(("(#%d) key '%s'", (int)i, keyval));
2986             }
2987             WLEN(keylen);
2988             if (keylen)
2989                 WRITE(keyval, keylen);
2990             if (flags & SHV_K_WASUTF8)
2991                 Safefree (keyval);
2992         }
2993
2994         /* 
2995          * Free up the temporary array
2996          */
2997
2998         av_undef(av);
2999         sv_free((SV *) av);
3000
3001     } else {
3002
3003         /*
3004          * Storing in "random" order (in the order the keys are stored
3005          * within the hash).  This is the default and will be faster!
3006          */
3007
3008         for (i = 0; i < len; i++) {
3009 #ifdef HV_ITERNEXT_WANTPLACEHOLDERS
3010             HE *he = hv_iternext_flags(hv, HV_ITERNEXT_WANTPLACEHOLDERS);
3011 #else
3012             HE *he = hv_iternext(hv);
3013 #endif
3014             SV *val = (he ? hv_iterval(hv, he) : 0);
3015
3016             if (val == 0)
3017                 return 1;               /* Internal error, not I/O error */
3018
3019             if ((ret = store_hentry(aTHX_ cxt, hv, i, he, val, hash_flags)))
3020                 goto out;
3021         }
3022     }
3023
3024     TRACEME(("ok (hash 0x%" UVxf ")", PTR2UV(hv)));
3025
3026  out:
3027     assert(cxt->max_recur_depth_hash != -1 && cxt->recur_depth > 0);
3028     TRACEME(("<hash recur_depth --%" IVdf , cxt->recur_depth));
3029     if (cxt->max_recur_depth_hash != -1 && recur_sv != (SV*)hv && cxt->recur_depth > 0) {
3030         --cxt->recur_depth;
3031     }
3032     HvRITER_set(hv, riter);             /* Restore hash iterator state */
3033     HvEITER_set(hv, eiter);
3034
3035     return ret;
3036 }
3037
3038 static int store_hentry(pTHX_
3039         stcxt_t *cxt, HV* hv, UV i, HE *he, SV *val, unsigned char hash_flags)
3040 {
3041     int ret = 0;
3042     int flagged_hash = ((SvREADONLY(hv)
3043 #ifdef HAS_HASH_KEY_FLAGS
3044                          || HvHASKFLAGS(hv)
3045 #endif
3046                          ) ? 1 : 0);
3047     /* Implementation of restricted hashes isn't nicely
3048        abstracted:  */
3049     unsigned char flags = (((hash_flags & SHV_RESTRICTED)
3050                             && SvTRULYREADONLY(val))
3051                            ? SHV_K_LOCKED : 0);
3052 #ifndef DEBUGME
3053     PERL_UNUSED_ARG(i);
3054 #endif
3055     if (val == &PL_sv_placeholder) {
3056         flags |= SHV_K_PLACEHOLDER;
3057         val = &PL_sv_undef;
3058     }
3059
3060     /*
3061      * Store value first.
3062      */
3063
3064     TRACEME(("(#%d) value 0x%" UVxf, (int)i, PTR2UV(val)));
3065
3066     {
3067         HEK* hek = HeKEY_hek(he);
3068         I32  len = HEK_LEN(hek);
3069         SV *key_sv = NULL;
3070         char *key = 0;
3071
3072         if ((ret = store(aTHX_ cxt, val)))
3073             return ret;
3074         if (len == HEf_SVKEY) {
3075             /* This is somewhat sick, but the internal APIs are
3076              * such that XS code could put one of these in
3077              * a regular hash.
3078              * Maybe we should be capable of storing one if
3079              * found.
3080              */
3081             key_sv = HeKEY_sv(he);
3082             flags |= SHV_K_ISSV;
3083         } else {
3084             /* Regular string key. */
3085 #ifdef HAS_HASH_KEY_FLAGS
3086             if (HEK_UTF8(hek))
3087                 flags |= SHV_K_UTF8;
3088             if (HEK_WASUTF8(hek))
3089                 flags |= SHV_K_WASUTF8;
3090 #endif
3091             key = HEK_KEY(hek);
3092         }
3093         /*
3094          * Write key string.
3095          * Keys are written after values to make sure retrieval
3096          * can be optimal in terms of memory usage, where keys are
3097          * read into a fixed unique buffer called kbuf.
3098          * See retrieve_hash() for details.
3099          */
3100
3101         if (flagged_hash) {
3102             PUTMARK(flags);
3103             TRACEME(("(#%d) key '%s' flags %x", (int)i, key, flags));
3104         } else {
3105             /* This is a workaround for a bug in 5.8.0
3106                that causes the HEK_WASUTF8 flag to be
3107                set on an HEK without the hash being
3108                marked as having key flags. We just
3109                cross our fingers and drop the flag.
3110                AMS 20030901 */
3111             assert (flags == 0 || flags == SHV_K_WASUTF8);
3112             TRACEME(("(#%d) key '%s'", (int)i, key));
3113         }
3114         if (flags & SHV_K_ISSV) {
3115             if ((ret = store(aTHX_ cxt, key_sv)))
3116                 return ret;
3117         } else {
3118             WLEN(len);
3119             if (len)
3120                 WRITE(key, len);
3121         }
3122     }
3123     return ret;
3124 }
3125
3126
3127 #ifdef HAS_U64
3128 /*
3129  * store_lhash
3130  *
3131  * Store a overlong hash table, with >2G keys, which we cannot iterate
3132  * over with perl5. xhv_eiter is only I32 there. (only cperl can)
3133  * and we also do not want to sort it.
3134  * So we walk the buckets and chains manually.
3135  *
3136  * type, len and flags are already written.
3137  */
3138
3139 static int store_lhash(pTHX_ stcxt_t *cxt, HV *hv, unsigned char hash_flags)
3140 {
3141     dVAR;
3142     int ret = 0;
3143     Size_t i;
3144     UV ix = 0;
3145     HE** array;
3146 #ifdef DEBUGME
3147     UV len = (UV)HvTOTALKEYS(hv);
3148 #endif
3149     SV * const recur_sv = cxt->recur_sv;
3150     if (hash_flags) {
3151         TRACEME(("store_lhash (0x%" UVxf ") (flags %x)", PTR2UV(hv),
3152                  (int) hash_flags));
3153     } else {
3154         TRACEME(("store_lhash (0x%" UVxf ")", PTR2UV(hv)));
3155     }
3156     TRACEME(("size = %" UVuf ", used = %" UVuf, len, (UV)HvUSEDKEYS(hv)));
3157
3158     TRACEME(("recur_depth %" IVdf ", recur_sv (0x%" UVxf ")", cxt->recur_depth,
3159              PTR2UV(cxt->recur_sv)));
3160     if (recur_sv != (SV*)hv && cxt->max_recur_depth_hash != -1) {
3161         ++cxt->recur_depth;
3162     }
3163     if (RECURSION_TOO_DEEP_HASH()) {
3164 #if PERL_VERSION_LT(5,15,0)
3165         cleanup_recursive_data(aTHX_ (SV*)hv);
3166 #endif
3167         CROAK((MAX_DEPTH_ERROR));
3168     }
3169
3170     array = HvARRAY(hv);
3171     for (i = 0; i <= (Size_t)HvMAX(hv); i++) {
3172         HE* entry = array[i];
3173
3174         while (entry) {
3175             SV* val = hv_iterval(hv, entry);
3176             if ((ret = store_hentry(aTHX_ cxt, hv, ix++, entry, val, hash_flags)))
3177                 return ret;
3178             entry = HeNEXT(entry);
3179         }
3180     }
3181     if (recur_sv != (SV*)hv && cxt->max_recur_depth_hash != -1 && cxt->recur_depth > 0) {
3182         TRACEME(("recur_depth --%" IVdf, cxt->recur_depth));
3183         --cxt->recur_depth;
3184     }
3185     assert(ix == len);
3186     return ret;
3187 }
3188 #endif
3189
3190 /*
3191  * store_code
3192  *
3193  * Store a code reference.
3194  *
3195  * Layout is SX_CODE <length> followed by a scalar containing the perl
3196  * source code of the code reference.
3197  */
3198 static int store_code(pTHX_ stcxt_t *cxt, CV *cv)
3199 {
3200     dSP;
3201     STRLEN len;
3202     STRLEN count, reallen;
3203     SV *text, *bdeparse;
3204
3205     TRACEME(("store_code (0x%" UVxf ")", PTR2UV(cv)));
3206
3207     if (
3208         cxt->deparse == 0 ||
3209         (cxt->deparse < 0 &&
3210          !(cxt->deparse =
3211            SvTRUE(get_sv("Storable::Deparse", GV_ADD)) ? 1 : 0))
3212         ) {
3213         return store_other(aTHX_ cxt, (SV*)cv);
3214     }
3215
3216     /*
3217      * Require B::Deparse. At least B::Deparse 0.61 is needed for
3218      * blessed code references.
3219      */
3220     /* Ownership of both SVs is passed to load_module, which frees them. */
3221     load_module(PERL_LOADMOD_NOIMPORT, newSVpvs("B::Deparse"), newSVnv(0.61));
3222     SPAGAIN;
3223
3224     ENTER;
3225     SAVETMPS;
3226
3227     /*
3228      * create the B::Deparse object
3229      */
3230
3231     PUSHMARK(sp);
3232     XPUSHs(newSVpvs_flags("B::Deparse", SVs_TEMP));
3233     PUTBACK;
3234     count = call_method("new", G_SCALAR);
3235     SPAGAIN;
3236     if (count != 1)
3237         CROAK(("Unexpected return value from B::Deparse::new\n"));
3238     bdeparse = POPs;
3239
3240     /*
3241      * call the coderef2text method
3242      */
3243
3244     PUSHMARK(sp);
3245     XPUSHs(bdeparse); /* XXX is this already mortal? */
3246     XPUSHs(sv_2mortal(newRV_inc((SV*)cv)));
3247     PUTBACK;
3248     count = call_method("coderef2text", G_SCALAR);
3249     SPAGAIN;
3250     if (count != 1)
3251         CROAK(("Unexpected return value from B::Deparse::coderef2text\n"));
3252
3253     text = POPs;
3254     len = SvCUR(text);
3255     reallen = strlen(SvPV_nolen(text));
3256
3257     /*
3258      * Empty code references or XS functions are deparsed as
3259      * "(prototype) ;" or ";".
3260      */
3261
3262     if (len == 0 || *(SvPV_nolen(text)+reallen-1) == ';') {
3263         CROAK(("The result of B::Deparse::coderef2text was empty - maybe you're trying to serialize an XS function?\n"));
3264     }
3265
3266     /* 
3267      * Signal code by emitting SX_CODE.
3268      */
3269
3270     PUTMARK(SX_CODE);
3271     cxt->tagnum++;   /* necessary, as SX_CODE is a SEEN() candidate */
3272     TRACEME(("size = %d", (int)len));
3273     TRACEME(("code = %s", SvPV_nolen(text)));
3274
3275     /*
3276      * Now store the source code.
3277      */
3278
3279     if(SvUTF8 (text))
3280         STORE_UTF8STR(SvPV_nolen(text), len);
3281     else
3282         STORE_SCALAR(SvPV_nolen(text), len);
3283
3284     FREETMPS;
3285     LEAVE;
3286
3287     TRACEME(("ok (code)"));
3288
3289     return 0;
3290 }
3291
3292 #if PERL_VERSION_LT(5,8,0)
3293 #   define PERL_MAGIC_qr                  'r' /* precompiled qr// regex */
3294 #   define BFD_Svs_SMG_OR_RMG SVs_RMG
3295 #elif PERL_VERSION_GE(5,8,1)
3296 #   define BFD_Svs_SMG_OR_RMG SVs_SMG
3297 #   define MY_PLACEHOLDER PL_sv_placeholder
3298 #else
3299 #   define BFD_Svs_SMG_OR_RMG SVs_RMG
3300 #   define MY_PLACEHOLDER PL_sv_undef
3301 #endif
3302
3303 static int get_regexp(pTHX_ stcxt_t *cxt, SV* sv, SV **re, SV **flags) {
3304     dSP;
3305     SV* rv;
3306 #if PERL_VERSION_GE(5,12,0)
3307     CV *cv = get_cv("re::regexp_pattern", 0);
3308 #else
3309     CV *cv = get_cv("Storable::_regexp_pattern", 0);
3310 #endif
3311     I32 count;
3312
3313     assert(cv);
3314
3315     ENTER;
3316     SAVETMPS;
3317     rv = sv_2mortal((SV*)newRV_inc(sv));
3318     PUSHMARK(sp);
3319     XPUSHs(rv);
3320     PUTBACK;
3321     /* optimize to call the XS directly later */
3322     count = call_sv((SV*)cv, G_ARRAY);
3323     SPAGAIN;
3324     if (count < 2)
3325       CROAK(("re::regexp_pattern returned only %d results", (int)count));
3326     *flags = POPs;
3327     SvREFCNT_inc(*flags);
3328     *re = POPs;
3329     SvREFCNT_inc(*re);
3330
3331     PUTBACK;
3332     FREETMPS;
3333     LEAVE;
3334
3335     return 1;
3336 }
3337
3338 static int store_regexp(pTHX_ stcxt_t *cxt, SV *sv) {
3339     SV *re = NULL;
3340     SV *flags = NULL;
3341     const char *re_pv;
3342     const char *flags_pv;
3343     STRLEN re_len;
3344     STRLEN flags_len;
3345     U8 op_flags = 0;
3346
3347     if (!get_regexp(aTHX_ cxt, sv, &re, &flags))
3348       return -1;
3349
3350     re_pv = SvPV(re, re_len);
3351     flags_pv = SvPV(flags, flags_len);
3352
3353     if (re_len > 0xFF) {
3354       op_flags |= SHR_U32_RE_LEN;
3355     }
3356     
3357     PUTMARK(SX_REGEXP);
3358     PUTMARK(op_flags);
3359     if (op_flags & SHR_U32_RE_LEN) {
3360       U32 re_len32 = re_len;
3361       WLEN(re_len32);
3362     }
3363     else
3364       PUTMARK(re_len);
3365     WRITE(re_pv, re_len);
3366     PUTMARK(flags_len);
3367     WRITE(flags_pv, flags_len);
3368
3369     return 0;
3370 }
3371
3372 /*
3373  * store_tied
3374  *
3375  * When storing a tied object (be it a tied scalar, array or hash), we lay out
3376  * a special mark, followed by the underlying tied object. For instance, when
3377  * dealing with a tied hash, we store SX_TIED_HASH <hash object>, where
3378  * <hash object> stands for the serialization of the tied hash.
3379  */
3380 static int store_tied(pTHX_ stcxt_t *cxt, SV *sv)
3381 {
3382     MAGIC *mg;
3383     SV *obj = NULL;
3384     int ret = 0;
3385     int svt = SvTYPE(sv);
3386     char mtype = 'P';
3387
3388     TRACEME(("store_tied (0x%" UVxf ")", PTR2UV(sv)));
3389
3390     /*
3391      * We have a small run-time penalty here because we chose to factorise
3392      * all tieds objects into the same routine, and not have a store_tied_hash,
3393      * a store_tied_array, etc...
3394      *
3395      * Don't use a switch() statement, as most compilers don't optimize that
3396      * well for 2/3 values. An if() else if() cascade is just fine. We put
3397      * tied hashes first, as they are the most likely beasts.
3398      */
3399
3400     if (svt == SVt_PVHV) {
3401         TRACEME(("tied hash"));
3402         PUTMARK(SX_TIED_HASH);          /* Introduces tied hash */
3403     } else if (svt == SVt_PVAV) {
3404         TRACEME(("tied array"));
3405         PUTMARK(SX_TIED_ARRAY);         /* Introduces tied array */
3406     } else {
3407         TRACEME(("tied scalar"));
3408         PUTMARK(SX_TIED_SCALAR);        /* Introduces tied scalar */
3409         mtype = 'q';
3410     }
3411
3412     if (!(mg = mg_find(sv, mtype)))
3413         CROAK(("No magic '%c' found while storing tied %s", mtype,
3414                (svt == SVt_PVHV) ? "hash" :
3415                (svt == SVt_PVAV) ? "array" : "scalar"));
3416
3417     /*
3418      * The mg->mg_obj found by mg_find() above actually points to the
3419      * underlying tied Perl object implementation. For instance, if the
3420      * original SV was that of a tied array, then mg->mg_obj is an AV.
3421      *
3422      * Note that we store the Perl object as-is. We don't call its FETCH
3423      * method along the way. At retrieval time, we won't call its STORE
3424      * method either, but the tieing magic will be re-installed. In itself,
3425      * that ensures that the tieing semantics are preserved since further
3426      * accesses on the retrieved object will indeed call the magic methods...
3427      */
3428
3429     /* [#17040] mg_obj is NULL for scalar self-ties. AMS 20030416 */
3430     obj = mg->mg_obj ? mg->mg_obj : newSV(0);
3431     if ((ret = store(aTHX_ cxt, obj)))
3432         return ret;
3433
3434     TRACEME(("ok (tied)"));
3435
3436     return 0;
3437 }
3438
3439 /*
3440  * store_tied_item
3441  *
3442  * Stores a reference to an item within a tied structure:
3443  *
3444  *  . \$h{key}, stores both the (tied %h) object and 'key'.
3445  *  . \$a[idx], stores both the (tied @a) object and 'idx'.
3446  *
3447  * Layout is therefore either:
3448  *     SX_TIED_KEY <object> <key>
3449  *     SX_TIED_IDX <object> <index>
3450  */
3451 static int store_tied_item(pTHX_ stcxt_t *cxt, SV *sv)
3452 {
3453     MAGIC *mg;
3454     int ret;
3455
3456     TRACEME(("store_tied_item (0x%" UVxf ")", PTR2UV(sv)));
3457
3458     if (!(mg = mg_find(sv, 'p')))
3459         CROAK(("No magic 'p' found while storing reference to tied item"));
3460
3461     /*
3462      * We discriminate between \$h{key} and \$a[idx] via mg_ptr.
3463      */
3464
3465     if (mg->mg_ptr) {
3466         TRACEME(("store_tied_item: storing a ref to a tied hash item"));
3467         PUTMARK(SX_TIED_KEY);
3468         TRACEME(("store_tied_item: storing OBJ 0x%" UVxf, PTR2UV(mg->mg_obj)));
3469
3470         if ((ret = store(aTHX_ cxt, mg->mg_obj)))       /* Extra () for -Wall, grr... */
3471             return ret;
3472
3473         TRACEME(("store_tied_item: storing PTR 0x%" UVxf, PTR2UV(mg->mg_ptr)));
3474
3475         if ((ret = store(aTHX_ cxt, (SV *) mg->mg_ptr))) /* Idem, for -Wall */
3476             return ret;
3477     } else {
3478         I32 idx = mg->mg_len;
3479
3480         TRACEME(("store_tied_item: storing a ref to a tied array item "));
3481         PUTMARK(SX_TIED_IDX);
3482         TRACEME(("store_tied_item: storing OBJ 0x%" UVxf, PTR2UV(mg->mg_obj)));
3483
3484         if ((ret = store(aTHX_ cxt, mg->mg_obj)))       /* Idem, for -Wall */
3485             return ret;
3486
3487         TRACEME(("store_tied_item: storing IDX %d", (int)idx));
3488
3489         WLEN(idx);
3490     }
3491
3492     TRACEME(("ok (tied item)"));
3493
3494     return 0;
3495 }
3496
3497 /*
3498  * store_hook           -- dispatched manually, not via sv_store[]
3499  *
3500  * The blessed SV is serialized by a hook.
3501  *
3502  * Simple Layout is:
3503  *
3504  *     SX_HOOK <flags> <len> <classname> <len2> <str> [<len3> <object-IDs>]
3505  *
3506  * where <flags> indicates how long <len>, <len2> and <len3> are, whether
3507  * the trailing part [] is present, the type of object (scalar, array or hash).
3508  * There is also a bit which says how the classname is stored between:
3509  *
3510  *     <len> <classname>
3511  *     <index>
3512  *
3513  * and when the <index> form is used (classname already seen), the "large
3514  * classname" bit in <flags> indicates how large the <index> is.
3515  * 
3516  * The serialized string returned by the hook is of length <len2> and comes
3517  * next.  It is an opaque string for us.
3518  *
3519  * Those <len3> object IDs which are listed last represent the extra references
3520  * not directly serialized by the hook, but which are linked to the object.
3521  *
3522  * When recursion is mandated to resolve object-IDs not yet seen, we have
3523  * instead, with <header> being flags with bits set to indicate the object type
3524  * and that recursion was indeed needed:
3525  *
3526  *     SX_HOOK <header> <object> <header> <object> <flags>
3527  *
3528  * that same header being repeated between serialized objects obtained through
3529  * recursion, until we reach flags indicating no recursion, at which point
3530  * we know we've resynchronized with a single layout, after <flags>.
3531  *
3532  * When storing a blessed ref to a tied variable, the following format is
3533  * used:
3534  *
3535  *     SX_HOOK <flags> <extra> ... [<len3> <object-IDs>] <magic object>
3536  *
3537  * The first <flags> indication carries an object of type SHT_EXTRA, and the
3538  * real object type is held in the <extra> flag.  At the very end of the
3539  * serialization stream, the underlying magic object is serialized, just like
3540  * any other tied variable.
3541  */
3542 static int store_hook(
3543                       pTHX_
3544                       stcxt_t *cxt,
3545                       SV *sv,
3546                       int type,
3547                       HV *pkg,
3548                       SV *hook)
3549 {
3550     I32 len;
3551     char *classname;
3552     STRLEN len2;
3553     SV *ref;
3554     AV *av;
3555     SV **ary;
3556     IV count;                   /* really len3 + 1 */
3557     unsigned char flags;
3558     char *pv;
3559     int i;
3560     int recursed = 0;           /* counts recursion */
3561     int obj_type;               /* object type, on 2 bits */
3562     I32 classnum;
3563     int ret;
3564     int clone = cxt->optype & ST_CLONE;
3565     char mtype = '\0';          /* for blessed ref to tied structures */
3566     unsigned char eflags = '\0'; /* used when object type is SHT_EXTRA */
3567 #ifdef HAS_U64
3568     int need_large_oids = 0;
3569 #endif
3570
3571     TRACEME(("store_hook, classname \"%s\", tagged #%d", HvNAME_get(pkg), (int)cxt->tagnum));
3572
3573     /*
3574      * Determine object type on 2 bits.
3575      */
3576
3577     switch (type) {
3578     case svis_REF:
3579     case svis_SCALAR:
3580         obj_type = SHT_SCALAR;
3581         break;
3582     case svis_ARRAY:
3583         obj_type = SHT_ARRAY;
3584         break;
3585     case svis_HASH:
3586         obj_type = SHT_HASH;
3587         break;
3588     case svis_TIED:
3589         /*
3590          * Produced by a blessed ref to a tied data structure, $o in the
3591          * following Perl code.
3592          *
3593          *      my %h;
3594          *  tie %h, 'FOO';
3595          *      my $o = bless \%h, 'BAR';
3596          *
3597          * Signal the tie-ing magic by setting the object type as SHT_EXTRA
3598          * (since we have only 2 bits in <flags> to store the type), and an
3599          * <extra> byte flag will be emitted after the FIRST <flags> in the
3600          * stream, carrying what we put in 'eflags'.
3601          */
3602         obj_type = SHT_EXTRA;
3603         switch (SvTYPE(sv)) {
3604         case SVt_PVHV:
3605             eflags = (unsigned char) SHT_THASH;
3606             mtype = 'P';
3607             break;
3608         case SVt_PVAV:
3609             eflags = (unsigned char) SHT_TARRAY;
3610             mtype = 'P';
3611             break;
3612         default:
3613             eflags = (unsigned char) SHT_TSCALAR;
3614             mtype = 'q';
3615             break;
3616         }
3617         break;
3618     default:
3619         CROAK(("Unexpected object type (%d) in store_hook()", type));
3620     }
3621     flags = SHF_NEED_RECURSE | obj_type;
3622
3623     classname = HvNAME_get(pkg);
3624     len = strlen(classname);
3625
3626     /*
3627      * To call the hook, we need to fake a call like:
3628      *
3629      *    $object->STORABLE_freeze($cloning);
3630      *
3631      * but we don't have the $object here.  For instance, if $object is
3632      * a blessed array, what we have in 'sv' is the array, and we can't
3633      * call a method on those.
3634      *
3635      * Therefore, we need to create a temporary reference to the object and
3636      * make the call on that reference.
3637      */
3638
3639     TRACEME(("about to call STORABLE_freeze on class %s", classname));
3640
3641     ref = newRV_inc(sv);                /* Temporary reference */
3642     av = array_call(aTHX_ ref, hook, clone); /* @a = $object->STORABLE_freeze($c) */
3643     SvREFCNT_dec(ref);                  /* Reclaim temporary reference */
3644
3645     count = AvFILLp(av) + 1;
3646     TRACEME(("store_hook, array holds %" IVdf " items", count));
3647
3648     /*
3649      * If they return an empty list, it means they wish to ignore the
3650      * hook for this class (and not just this instance -- that's for them
3651      * to handle if they so wish).
3652      *
3653      * Simply disable the cached entry for the hook (it won't be recomputed
3654      * since it's present in the cache) and recurse to store_blessed().
3655      */
3656
3657     if (!count) {
3658         /* free empty list returned by the hook */
3659         av_undef(av);
3660         sv_free((SV *) av);
3661
3662         /*
3663          * They must not change their mind in the middle of a serialization.
3664          */
3665
3666         if (hv_fetch(cxt->hclass, classname, len, FALSE))
3667             CROAK(("Too late to ignore hooks for %s class \"%s\"",
3668                    (cxt->optype & ST_CLONE) ? "cloning" : "storing",
3669                    classname));
3670
3671         pkg_hide(aTHX_ cxt->hook, pkg, "STORABLE_freeze");
3672
3673         ASSERT(!pkg_can(aTHX_ cxt->hook, pkg, "STORABLE_freeze"),
3674                ("hook invisible"));
3675         TRACEME(("ignoring STORABLE_freeze in class \"%s\"", classname));
3676
3677         return store_blessed(aTHX_ cxt, sv, type, pkg);
3678     }
3679
3680     /*
3681      * Get frozen string.
3682      */
3683
3684     ary = AvARRAY(av);
3685     pv = SvPV(ary[0], len2);
3686     /* We can't use pkg_can here because it only caches one method per
3687      * package */
3688     { 
3689         GV* gv = gv_fetchmethod_autoload(pkg, "STORABLE_attach", FALSE);
3690         if (gv && isGV(gv)) {
3691             if (count > 1)
3692                 CROAK(("Freeze cannot return references if %s class is using STORABLE_attach", classname));
3693             goto check_done;
3694         }
3695     }
3696
3697 #ifdef HAS_U64
3698     if (count > I32_MAX) {
3699         CROAK(("Too many references returned by STORABLE_freeze()"));
3700     }
3701 #endif
3702
3703     /*
3704      * If they returned more than one item, we need to serialize some
3705      * extra references if not already done.
3706      *
3707      * Loop over the array, starting at position #1, and for each item,
3708      * ensure it is a reference, serialize it if not already done, and
3709      * replace the entry with the tag ID of the corresponding serialized
3710      * object.
3711      *
3712      * We CHEAT by not calling av_fetch() and read directly within the
3713      * array, for speed.
3714      */
3715
3716     for (i = 1; i < count; i++) {
3717 #ifdef USE_PTR_TABLE
3718         char *fake_tag;
3719 #else
3720         SV **svh;
3721 #endif
3722         SV *rsv = ary[i];
3723         SV *xsv;
3724         SV *tag;
3725         AV *av_hook = cxt->hook_seen;
3726
3727         if (!SvROK(rsv))
3728             CROAK(("Item #%d returned by STORABLE_freeze "
3729                    "for %s is not a reference", (int)i, classname));
3730         xsv = SvRV(rsv);        /* Follow ref to know what to look for */
3731
3732         /*
3733          * Look in hseen and see if we have a tag already.
3734          * Serialize entry if not done already, and get its tag.
3735          */
3736
3737 #ifdef USE_PTR_TABLE
3738         /* Fakery needed because ptr_table_fetch returns zero for a
3739            failure, whereas the existing code assumes that it can
3740            safely store a tag zero. So for ptr_tables we store tag+1
3741         */
3742         if ((fake_tag = (char *)ptr_table_fetch(cxt->pseen, xsv)))
3743             goto sv_seen;       /* Avoid moving code too far to the right */
3744 #else
3745         if ((svh = hv_fetch(cxt->hseen, (char *) &xsv, sizeof(xsv), FALSE)))
3746             goto sv_seen;       /* Avoid moving code too far to the right */
3747 #endif
3748
3749         TRACEME(("listed object %d at 0x%" UVxf " is unknown", i-1,
3750                  PTR2UV(xsv)));
3751
3752         /*
3753          * We need to recurse to store that object and get it to be known
3754          * so that we can resolve the list of object-IDs at retrieve time.
3755          *
3756          * The first time we do this, we need to emit the proper header
3757          * indicating that we recursed, and what the type of object is (the
3758          * object we're storing via a user-hook).  Indeed, during retrieval,
3759          * we'll have to create the object before recursing to retrieve the
3760          * others, in case those would point back at that object.
3761          */
3762
3763         /* [SX_HOOK] <flags> [<extra>] <object>*/
3764         if (!recursed++) {
3765 #ifdef HAS_U64
3766             if (len2 > INT32_MAX)
3767                 PUTMARK(SX_LOBJECT);
3768 #endif
3769             PUTMARK(SX_HOOK);
3770             PUTMARK(flags);
3771             if (obj_type == SHT_EXTRA)
3772                 PUTMARK(eflags);
3773         } else
3774             PUTMARK(flags);
3775
3776         if ((ret = store(aTHX_ cxt, xsv)))      /* Given by hook for us to store */
3777             return ret;
3778
3779 #ifdef USE_PTR_TABLE
3780         fake_tag = (char *)ptr_table_fetch(cxt->pseen, xsv);
3781         if (!fake_tag)
3782             CROAK(("Could not serialize item #%d from hook in %s",
3783                    (int)i, classname));
3784 #else
3785         svh = hv_fetch(cxt->hseen, (char *) &xsv, sizeof(xsv), FALSE);
3786         if (!svh)
3787             CROAK(("Could not serialize item #%d from hook in %s",
3788                    (int)i, classname));
3789 #endif
3790         /*
3791          * It was the first time we serialized 'xsv'.
3792          *
3793          * Keep this SV alive until the end of the serialization: if we
3794          * disposed of it right now by decrementing its refcount, and it was
3795          * a temporary value, some next temporary value allocated during
3796          * another STORABLE_freeze might take its place, and we'd wrongly
3797          * assume that new SV was already serialized, based on its presence
3798          * in cxt->hseen.
3799          *
3800          * Therefore, push it away in cxt->hook_seen.
3801          */
3802
3803         av_store(av_hook, AvFILLp(av_hook)+1, SvREFCNT_inc(xsv));
3804
3805     sv_seen:
3806         /*
3807          * Dispose of the REF they returned.  If we saved the 'xsv' away
3808          * in the array of returned SVs, that will not cause the underlying
3809          * referenced SV to be reclaimed.
3810          */
3811
3812         ASSERT(SvREFCNT(xsv) > 1, ("SV will survive disposal of its REF"));
3813         SvREFCNT_dec(rsv);              /* Dispose of reference */
3814
3815         /*
3816          * Replace entry with its tag (not a real SV, so no refcnt increment)
3817          */
3818
3819 #ifdef USE_PTR_TABLE
3820         tag = (SV *)--fake_tag;
3821 #else
3822         tag = *svh;
3823 #endif
3824         ary[i] = tag;
3825         TRACEME(("listed object %d at 0x%" UVxf " is tag #%" UVuf,
3826                  i-1, PTR2UV(xsv), PTR2UV(tag)));
3827 #ifdef HAS_U64
3828        if ((U32)PTR2TAG(tag) != PTR2TAG(tag))
3829            need_large_oids = 1;
3830 #endif
3831     }
3832
3833     /*
3834      * Allocate a class ID if not already done.
3835      *
3836      * This needs to be done after the recursion above, since at retrieval
3837      * time, we'll see the inner objects first.  Many thanks to
3838      * Salvador Ortiz Garcia <sog@msg.com.mx> who spot that bug and
3839      * proposed the right fix.  -- RAM, 15/09/2000
3840      */
3841
3842  check_done:
3843     if (!known_class(aTHX_ cxt, classname, len, &classnum)) {
3844         TRACEME(("first time we see class %s, ID = %d", classname, (int)classnum));
3845         classnum = -1;                  /* Mark: we must store classname */
3846     } else {
3847         TRACEME(("already seen class %s, ID = %d", classname, (int)classnum));
3848     }
3849
3850     /*
3851      * Compute leading flags.
3852      */
3853
3854     flags = obj_type;
3855     if (((classnum == -1) ? len : classnum) > LG_SCALAR)
3856         flags |= SHF_LARGE_CLASSLEN;
3857     if (classnum != -1)
3858         flags |= SHF_IDX_CLASSNAME;
3859     if (len2 > LG_SCALAR)
3860         flags |= SHF_LARGE_STRLEN;
3861     if (count > 1)
3862         flags |= SHF_HAS_LIST;
3863     if (count > (LG_SCALAR + 1))
3864         flags |= SHF_LARGE_LISTLEN;
3865 #ifdef HAS_U64
3866     if (need_large_oids)
3867         flags |= SHF_LARGE_LISTLEN;
3868 #endif
3869
3870     /*
3871      * We're ready to emit either serialized form:
3872      *
3873      *   SX_HOOK <flags> <len> <classname> <len2> <str> [<len3> <object-IDs>]
3874      *   SX_HOOK <flags> <index>           <len2> <str> [<len3> <object-IDs>]
3875      *
3876      * If we recursed, the SX_HOOK has already been emitted.
3877      */
3878
3879     TRACEME(("SX_HOOK (recursed=%d) flags=0x%x "
3880              "class=%" IVdf " len=%" IVdf " len2=%" IVdf " len3=%" IVdf,
3881              recursed, flags, (IV)classnum, (IV)len, (IV)len2, count-1));
3882
3883     /* SX_HOOK <flags> [<extra>] */
3884     if (!recursed) {
3885 #ifdef HAS_U64
3886         if (len2 > INT32_MAX)
3887             PUTMARK(SX_LOBJECT);
3888 #endif
3889         PUTMARK(SX_HOOK);
3890         PUTMARK(flags);
3891         if (obj_type == SHT_EXTRA)
3892             PUTMARK(eflags);
3893     } else
3894         PUTMARK(flags);
3895
3896     /* <len> <classname> or <index> */
3897     if (flags & SHF_IDX_CLASSNAME) {
3898         if (flags & SHF_LARGE_CLASSLEN)
3899             WLEN(classnum);
3900         else {
3901             unsigned char cnum = (unsigned char) classnum;
3902             PUTMARK(cnum);
3903         }
3904     } else {
3905         if (flags & SHF_LARGE_CLASSLEN)
3906             WLEN(len);
3907         else {
3908             unsigned char clen = (unsigned char) len;
3909             PUTMARK(clen);
3910         }
3911         WRITE(classname, len);          /* Final \0 is omitted */
3912     }
3913
3914     /* <len2> <frozen-str> */
3915 #ifdef HAS_U64
3916     if (len2 > INT32_MAX) {
3917         W64LEN(len2);
3918     }
3919     else
3920 #endif
3921     if (flags & SHF_LARGE_STRLEN) {
3922         U32 wlen2 = len2;               /* STRLEN might be 8 bytes */
3923         WLEN(wlen2);                    /* Must write an I32 for 64-bit machines */
3924     } else {
3925         unsigned char clen = (unsigned char) len2;
3926         PUTMARK(clen);
3927     }
3928     if (len2)
3929         WRITE(pv, (SSize_t)len2);       /* Final \0 is omitted */
3930
3931     /* [<len3> <object-IDs>] */
3932     if (flags & SHF_HAS_LIST) {
3933         int len3 = count - 1;
3934         if (flags & SHF_LARGE_LISTLEN) {
3935 #ifdef HAS_U64
3936             int tlen3 = need_large_oids ? -len3 : len3;
3937             WLEN(tlen3);
3938 #else
3939             WLEN(len3);
3940 #endif
3941         }
3942         else {
3943             unsigned char clen = (unsigned char) len3;
3944             PUTMARK(clen);
3945         }
3946
3947         /*
3948          * NOTA BENE, for 64-bit machines: the ary[i] below does not yield a
3949          * real pointer, rather a tag number, well under the 32-bit limit.
3950          * Which is wrong... if we have more than 2**32 SVs we can get ids over
3951          * the 32-bit limit.
3952          */
3953
3954         for (i = 1; i < count; i++) {
3955 #ifdef HAS_U64
3956             if (need_large_oids) {
3957                 ntag_t tag = PTR2TAG(ary[i]);
3958                 W64LEN(tag);
3959                 TRACEME(("object %d, tag #%" UVuf, i-1, (UV)tag));
3960             }
3961             else
3962 #endif
3963             {
3964                 I32 tagval = htonl(LOW_32BITS(ary[i]));
3965                 WRITE_I32(tagval);
3966                 TRACEME(("object %d, tag #%d", i-1, ntohl(tagval)));
3967             }
3968         }
3969     }
3970
3971     /*
3972      * Free the array.  We need extra care for indices after 0, since they
3973      * don't hold real SVs but integers cast.
3974      */
3975
3976     if (count > 1)
3977         AvFILLp(av) = 0;        /* Cheat, nothing after 0 interests us */
3978     av_undef(av);
3979     sv_free((SV *) av);
3980
3981     /*
3982      * If object was tied, need to insert serialization of the magic object.
3983      */
3984
3985     if (obj_type == SHT_EXTRA) {
3986         MAGIC *mg;
3987
3988         if (!(mg = mg_find(sv, mtype))) {
3989             int svt = SvTYPE(sv);
3990             CROAK(("No magic '%c' found while storing ref to tied %s with hook",
3991                    mtype, (svt == SVt_PVHV) ? "hash" :
3992                    (svt == SVt_PVAV) ? "array" : "scalar"));
3993         }
3994
3995         TRACEME(("handling the magic object 0x%" UVxf " part of 0x%" UVxf,
3996                  PTR2UV(mg->mg_obj), PTR2UV(sv)));
3997
3998         /*
3999          * [<magic object>]
4000          */
4001         if ((ret = store(aTHX_ cxt, mg->mg_obj)))
4002             return ret;
4003     }
4004
4005     return 0;
4006 }
4007
4008 /*
4009  * store_blessed        -- dispatched manually, not via sv_store[]
4010  *
4011  * Check whether there is a STORABLE_xxx hook defined in the class or in one
4012  * of its ancestors.  If there is, then redispatch to store_hook();
4013  *
4014  * Otherwise, the blessed SV is stored using the following layout:
4015  *
4016  *    SX_BLESS <flag> <len> <classname> <object>
4017  *
4018  * where <flag> indicates whether <len> is stored on 0 or 4 bytes, depending
4019  * on the high-order bit in flag: if 1, then length follows on 4 bytes.
4020  * Otherwise, the low order bits give the length, thereby giving a compact
4021  * representation for class names less than 127 chars long.
4022  *
4023  * Each <classname> seen is remembered and indexed, so that the next time
4024  * an object in the blessed in the same <classname> is stored, the following
4025  * will be emitted:
4026  *
4027  *    SX_IX_BLESS <flag> <index> <object>
4028  *
4029  * where <index> is the classname index, stored on 0 or 4 bytes depending
4030  * on the high-order bit in flag (same encoding as above for <len>).
4031  */
4032 static int store_blessed(
4033                          pTHX_
4034                          stcxt_t *cxt,
4035                          SV *sv,
4036                          int type,
4037                          HV *pkg)
4038 {
4039     SV *hook;
4040     char *classname;
4041     I32 len;
4042     I32 classnum;
4043
4044     TRACEME(("store_blessed, type %d, class \"%s\"", type, HvNAME_get(pkg)));
4045
4046     /*
4047      * Look for a hook for this blessed SV and redirect to store_hook()
4048      * if needed.
4049      */
4050
4051     hook = pkg_can(aTHX_ cxt->hook, pkg, "STORABLE_freeze");
4052     if (hook)
4053         return store_hook(aTHX_ cxt, sv, type, pkg, hook);
4054
4055     /*
4056      * This is a blessed SV without any serialization hook.
4057      */
4058
4059     classname = HvNAME_get(pkg);
4060     len = strlen(classname);
4061
4062     TRACEME(("blessed 0x%" UVxf " in %s, no hook: tagged #%d",
4063              PTR2UV(sv), classname, (int)cxt->tagnum));
4064
4065     /*
4066      * Determine whether it is the first time we see that class name (in which
4067      * case it will be stored in the SX_BLESS form), or whether we already
4068      * saw that class name before (in which case the SX_IX_BLESS form will be
4069      * used).
4070      */
4071
4072     if (known_class(aTHX_ cxt, classname, len, &classnum)) {
4073         TRACEME(("already seen class %s, ID = %d", classname, (int)classnum));
4074         PUTMARK(SX_IX_BLESS);
4075         if (classnum <= LG_BLESS) {
4076             unsigned char cnum = (unsigned char) classnum;
4077             PUTMARK(cnum);
4078         } else {
4079             unsigned char flag = (unsigned char) 0x80;
4080             PUTMARK(flag);
4081             WLEN(classnum);
4082         }
4083     } else {
4084         TRACEME(("first time we see class %s, ID = %d", classname,
4085                  (int)classnum));
4086         PUTMARK(SX_BLESS);
4087         if (len <= LG_BLESS) {
4088             unsigned char clen = (unsigned char) len;
4089             PUTMARK(clen);
4090         } else {
4091             unsigned char flag = (unsigned char) 0x80;
4092             PUTMARK(flag);
4093             WLEN(len);  /* Don't BER-encode, this should be rare */
4094         }
4095         WRITE(classname, len);  /* Final \0 is omitted */
4096     }
4097
4098     /*
4099      * Now emit the <object> part.
4100      */
4101
4102     return SV_STORE(type)(aTHX_ cxt, sv);
4103 }
4104
4105 /*
4106  * store_other
4107  *
4108  * We don't know how to store the item we reached, so return an error condition.
4109  * (it's probably a GLOB, some CODE reference, etc...)
4110  *
4111  * If they defined the 'forgive_me' variable at the Perl level to some
4112  * true value, then don't croak, just warn, and store a placeholder string
4113  * instead.
4114  */
4115 static int store_other(pTHX_ stcxt_t *cxt, SV *sv)
4116 {
4117     STRLEN len;
4118     char buf[80];
4119
4120     TRACEME(("store_other"));
4121
4122     /*
4123      * Fetch the value from perl only once per store() operation.
4124      */
4125
4126     if (
4127         cxt->forgive_me == 0 ||
4128         (cxt->forgive_me < 0 &&
4129          !(cxt->forgive_me = SvTRUE
4130            (get_sv("Storable::forgive_me", GV_ADD)) ? 1 : 0))
4131         )
4132         CROAK(("Can't store %s items", sv_reftype(sv, FALSE)));
4133
4134     warn("Can't store item %s(0x%" UVxf ")",
4135          sv_reftype(sv, FALSE), PTR2UV(sv));
4136
4137     /*
4138      * Store placeholder string as a scalar instead...
4139      */
4140
4141     (void) sprintf(buf, "You lost %s(0x%" UVxf ")%c", sv_reftype(sv, FALSE),
4142                    PTR2UV(sv), (char) 0);
4143
4144     len = strlen(buf);
4145     if (len < 80)
4146         STORE_SCALAR(buf, len);
4147     TRACEME(("ok (dummy \"%s\", length = %" IVdf ")", buf, (IV) len));
4148
4149     return 0;
4150 }
4151
4152 /***
4153  *** Store driving routines
4154  ***/
4155
4156 /*
4157  * sv_type
4158  *
4159  * WARNING: partially duplicates Perl's sv_reftype for speed.
4160  *
4161  * Returns the type of the SV, identified by an integer. That integer
4162  * may then be used to index the dynamic routine dispatch table.
4163  */
4164 static int sv_type(pTHX_ SV *sv)
4165 {
4166     switch (SvTYPE(sv)) {
4167     case SVt_NULL:
4168 #if PERL_VERSION_LT(5,11,0)
4169     case SVt_IV:
4170 #endif
4171     case SVt_NV:
4172         /*
4173          * No need to check for ROK, that can't be set here since there
4174          * is no field capable of hodling the xrv_rv reference.
4175          */
4176         return svis_SCALAR;
4177     case SVt_PV:
4178 #if PERL_VERSION_LT(5,11,0)
4179     case SVt_RV:
4180 #else
4181     case SVt_IV:
4182 #endif
4183     case SVt_PVIV:
4184     case SVt_PVNV:
4185         /*
4186          * Starting from SVt_PV, it is possible to have the ROK flag
4187          * set, the pointer to the other SV being either stored in
4188          * the xrv_rv (in the case of a pure SVt_RV), or as the
4189          * xpv_pv field of an SVt_PV and its heirs.
4190          *
4191          * However, those SV cannot be magical or they would be an
4192          * SVt_PVMG at least.
4193          */
4194         return SvROK(sv) ? svis_REF : svis_SCALAR;
4195     case SVt_PVMG:
4196 #if PERL_VERSION_LT(5,11,0)
4197         if ((SvFLAGS(sv) & (SVs_OBJECT|SVf_OK|SVs_GMG|SVs_SMG|SVs_RMG))
4198                   == (SVs_OBJECT|BFD_Svs_SMG_OR_RMG)
4199             && mg_find(sv, PERL_MAGIC_qr)) {
4200               return svis_REGEXP;
4201         }
4202 #endif
4203     case SVt_PVLV:              /* Workaround for perl5.004_04 "LVALUE" bug */
4204         if ((SvFLAGS(sv) & (SVs_GMG|SVs_SMG|SVs_RMG)) ==
4205             (SVs_GMG|SVs_SMG|SVs_RMG) &&
4206             (mg_find(sv, 'p')))
4207             return svis_TIED_ITEM;
4208         /* FALL THROUGH */
4209 #if PERL_VERSION_LT(5,9,0)
4210     case SVt_PVBM:
4211 #endif
4212         if ((SvFLAGS(sv) & (SVs_GMG|SVs_SMG|SVs_RMG)) ==
4213             (SVs_GMG|SVs_SMG|SVs_RMG) &&
4214             (mg_find(sv, 'q')))
4215             return svis_TIED;
4216         return SvROK(sv) ? svis_REF : svis_SCALAR;
4217     case SVt_PVAV:
4218         if (SvRMAGICAL(sv) && (mg_find(sv, 'P')))
4219             return svis_TIED;
4220         return svis_ARRAY;
4221     case SVt_PVHV:
4222         if (SvRMAGICAL(sv) && (mg_find(sv, 'P')))
4223             return svis_TIED;
4224         return svis_HASH;
4225     case SVt_PVCV:
4226         return svis_CODE;
4227 #if PERL_VERSION_GE(5,9,0)
4228         /* case SVt_INVLIST: */
4229 #endif
4230 #if PERL_VERSION_GE(5,11,0)
4231     case SVt_REGEXP:
4232         return svis_REGEXP;
4233 #endif
4234     default:
4235         break;
4236     }
4237
4238     return svis_OTHER;
4239 }
4240
4241 /*
4242  * store
4243  *
4244  * Recursively store objects pointed to by the sv to the specified file.
4245  *
4246  * Layout is <content> or SX_OBJECT <tagnum> if we reach an already stored
4247  * object (one for which storage has started -- it may not be over if we have
4248  * a self-referenced structure). This data set forms a stored <object>.
4249  */
4250 static int store(pTHX_ stcxt_t *cxt, SV *sv)
4251 {
4252     SV **svh;
4253     int ret;
4254     int type;
4255 #ifdef USE_PTR_TABLE
4256     struct ptr_tbl *pseen = cxt->pseen;
4257 #else
4258     HV *hseen = cxt->hseen;
4259 #endif
4260
4261     TRACEME(("store (0x%" UVxf ")", PTR2UV(sv)));
4262
4263     /*
4264      * If object has already been stored, do not duplicate data.
4265      * Simply emit the SX_OBJECT marker followed by its tag data.
4266      * The tag is always written in network order.
4267      *
4268      * NOTA BENE, for 64-bit machines: the "*svh" below does not yield a
4269      * real pointer, rather a tag number (watch the insertion code below).
4270      * That means it probably safe to assume it is well under the 32-bit
4271      * limit, and makes the truncation safe.
4272      *          -- RAM, 14/09/1999
4273      */
4274
4275 #ifdef USE_PTR_TABLE
4276     svh = (SV **)ptr_table_fetch(pseen, sv);
4277 #else
4278     svh = hv_fetch(hseen, (char *) &sv, sizeof(sv), FALSE);
4279 #endif
4280     if (svh) {
4281         ntag_t tagval;
4282         if (sv == &PL_sv_undef) {
4283             /* We have seen PL_sv_undef before, but fake it as
4284                if we have not.
4285
4286                Not the simplest solution to making restricted
4287                hashes work on 5.8.0, but it does mean that
4288                repeated references to the one true undef will
4289                take up less space in the output file.
4290             */
4291             /* Need to jump past the next hv_store, because on the
4292                second store of undef the old hash value will be
4293                SvREFCNT_dec()ed, and as Storable cheats horribly
4294                by storing non-SVs in the hash a SEGV will ensure.
4295                Need to increase the tag number so that the
4296                receiver has no idea what games we're up to.  This
4297                special casing doesn't affect hooks that store
4298                undef, as the hook routine does its own lookup into
4299                hseen.  Also this means that any references back
4300                to PL_sv_undef (from the pathological case of hooks
4301                storing references to it) will find the seen hash
4302                entry for the first time, as if we didn't have this
4303                hackery here. (That hseen lookup works even on 5.8.0
4304                because it's a key of &PL_sv_undef and a value
4305                which is a tag number, not a value which is
4306                PL_sv_undef.)  */
4307             cxt->tagnum++;
4308             type = svis_SCALAR;
4309             goto undef_special_case;
4310         }
4311
4312 #ifdef USE_PTR_TABLE
4313         tagval = PTR2TAG(((char *)svh)-1);
4314 #else
4315         tagval = PTR2TAG(*svh);
4316 #endif
4317 #ifdef HAS_U64
4318
4319        /* older versions of Storable streat the tag as a signed value
4320           used in an array lookup, corrupting the data structure.
4321           Ensure only a newer Storable will be able to parse this tag id
4322           if it's over the 2G mark.
4323         */
4324         if (tagval > I32_MAX) {
4325
4326             TRACEME(("object 0x%" UVxf " seen as #%" UVuf, PTR2UV(sv),
4327                      (UV)tagval));
4328
4329             PUTMARK(SX_LOBJECT);
4330             PUTMARK(SX_OBJECT);
4331             W64LEN(tagval);
4332             return 0;
4333         }
4334         else
4335 #endif
4336         {
4337             I32 ltagval;
4338
4339             ltagval = htonl((I32)tagval);
4340
4341             TRACEME(("object 0x%" UVxf " seen as #%d", PTR2UV(sv),
4342                      ntohl(ltagval)));
4343
4344             PUTMARK(SX_OBJECT);
4345             WRITE_I32(ltagval);
4346             return 0;
4347         }
4348     }
4349
4350     /*
4351      * Allocate a new tag and associate it with the address of the sv being
4352      * stored, before recursing...
4353      *
4354      * In order to avoid creating new SvIVs to hold the tagnum we just
4355      * cast the tagnum to an SV pointer and store that in the hash.  This
4356      * means that we must clean up the hash manually afterwards, but gives
4357      * us a 15% throughput increase.
4358      *
4359      */
4360
4361     cxt->tagnum++;
4362 #ifdef USE_PTR_TABLE
4363     ptr_table_store(pseen, sv, INT2PTR(SV*, 1 + cxt->tagnum));
4364 #else
4365     if (!hv_store(hseen,
4366                   (char *) &sv, sizeof(sv), INT2PTR(SV*, cxt->tagnum), 0))
4367         return -1;
4368 #endif
4369
4370     /*
4371      * Store 'sv' and everything beneath it, using appropriate routine.
4372      * Abort immediately if we get a non-zero status back.
4373      */
4374
4375     type = sv_type(aTHX_ sv);
4376
4377  undef_special_case:
4378     TRACEME(("storing 0x%" UVxf " tag #%d, type %d...",
4379              PTR2UV(sv), (int)cxt->tagnum, (int)type));
4380
4381     if (SvOBJECT(sv)) {
4382         HV *pkg = SvSTASH(sv);
4383         ret = store_blessed(aTHX_ cxt, sv, type, pkg);
4384     } else
4385         ret = SV_STORE(type)(aTHX_ cxt, sv);
4386
4387     TRACEME(("%s (stored 0x%" UVxf ", refcnt=%d, %s)",
4388              ret ? "FAILED" : "ok", PTR2UV(sv),
4389              (int)SvREFCNT(sv), sv_reftype(sv, FALSE)));
4390
4391     return ret;
4392 }
4393
4394 /*
4395  * magic_write
4396  *
4397  * Write magic number and system information into the file.
4398  * Layout is <magic> <network> [<len> <byteorder> <sizeof int> <sizeof long>
4399  * <sizeof ptr>] where <len> is the length of the byteorder hexa string.
4400  * All size and lengths are written as single characters here.
4401  *
4402  * Note that no byte ordering info is emitted when <network> is true, since
4403  * integers will be emitted in network order in that case.
4404  */
4405 static int magic_write(pTHX_ stcxt_t *cxt)
4406 {
4407     /*
4408      * Starting with 0.6, the "use_network_order" byte flag is also used to
4409      * indicate the version number of the binary image, encoded in the upper
4410      * bits. The bit 0 is always used to indicate network order.
4411      */
4412     /*
4413      * Starting with 0.7, a full byte is dedicated to the minor version of
4414      * the binary format, which is incremented only when new markers are
4415      * introduced, for instance, but when backward compatibility is preserved.
4416      */
4417
4418     /* Make these at compile time.  The WRITE() macro is sufficiently complex
4419        that it saves about 200 bytes doing it this way and only using it
4420        once.  */
4421     static const unsigned char network_file_header[] = {
4422         MAGICSTR_BYTES,
4423         (STORABLE_BIN_MAJOR << 1) | 1,
4424         STORABLE_BIN_WRITE_MINOR
4425     };
4426     static const unsigned char file_header[] = {
4427         MAGICSTR_BYTES,
4428         (STORABLE_BIN_MAJOR << 1) | 0,
4429         STORABLE_BIN_WRITE_MINOR,
4430         /* sizeof the array includes the 0 byte at the end:  */
4431         (char) sizeof (byteorderstr) - 1,
4432         BYTEORDER_BYTES,
4433         (unsigned char) sizeof(int),
4434         (unsigned char) sizeof(long),
4435         (unsigned char) sizeof(char *),
4436         (unsigned char) sizeof(NV)
4437     };
4438 #ifdef USE_56_INTERWORK_KLUDGE
4439     static const unsigned char file_header_56[] = {
4440         MAGICSTR_BYTES,
4441         (STORABLE_BIN_MAJOR << 1) | 0,
4442         STORABLE_BIN_WRITE_MINOR,
4443         /* sizeof the array includes the 0 byte at the end:  */
4444         (char) sizeof (byteorderstr_56) - 1,
4445         BYTEORDER_BYTES_56,
4446         (unsigned char) sizeof(int),
4447         (unsigned char) sizeof(long),
4448         (unsigned char) sizeof(char *),
4449         (unsigned char) sizeof(NV)
4450     };
4451 #endif
4452     const unsigned char *header;
4453     SSize_t length;
4454
4455     TRACEME(("magic_write on fd=%d", cxt->fio ? PerlIO_fileno(cxt->fio) : -1));
4456
4457     if (cxt->netorder) {
4458         header = network_file_header;
4459         length = sizeof (network_file_header);
4460     } else {
4461 #ifdef USE_56_INTERWORK_KLUDGE
4462         if (SvTRUE(get_sv("Storable::interwork_56_64bit", GV_ADD))) {
4463             header = file_header_56;
4464             length = sizeof (file_header_56);
4465         } else
4466 #endif
4467             {
4468                 header = file_header;
4469                 length = sizeof (file_header);
4470             }
4471     }
4472
4473     if (!cxt->fio) {
4474         /* sizeof the array includes the 0 byte at the end.  */
4475         header += sizeof (magicstr) - 1;
4476         length -= sizeof (magicstr) - 1;
4477     }
4478
4479     WRITE( (unsigned char*) header, length);
4480
4481     if (!cxt->netorder) {
4482         TRACEME(("ok (magic_write byteorder = 0x%lx [%d], I%d L%d P%d D%d)",
4483                  (unsigned long) BYTEORDER, (int) sizeof (byteorderstr) - 1,
4484                  (int) sizeof(int), (int) sizeof(long),
4485                  (int) sizeof(char *), (int) sizeof(NV)));
4486     }
4487     return 0;
4488 }
4489
4490 /*
4491  * do_store
4492  *
4493  * Common code for store operations.
4494  *
4495  * When memory store is requested (f = NULL) and a non null SV* is given in
4496  * 'res', it is filled with a new SV created out of the memory buffer.
4497  *
4498  * It is required to provide a non-null 'res' when the operation type is not
4499  * dclone() and store() is performed to memory.
4500  */
4501 static int do_store(pTHX_
4502         PerlIO *f,
4503         SV *sv,
4504         int optype,
4505         int network_order,
4506         SV **res)
4507 {
4508     dSTCXT;
4509     int status;
4510
4511     ASSERT(!(f == 0 && !(optype & ST_CLONE)) || res,
4512            ("must supply result SV pointer for real recursion to memory"));
4513
4514     TRACEMED(("do_store (optype=%d, netorder=%d)",
4515              optype, network_order));
4516
4517     optype |= ST_STORE;
4518
4519     /*
4520      * Workaround for CROAK leak: if they enter with a "dirty" context,
4521      * free up memory for them now.
4522      */
4523
4524     assert(cxt);
4525     if (cxt->s_dirty)
4526         clean_context(aTHX_ cxt);
4527
4528     /*
4529      * Now that STORABLE_xxx hooks exist, it is possible that they try to
4530      * re-enter store() via the hooks.  We need to stack contexts.
4531      */
4532
4533     if (cxt->entry)
4534         cxt = allocate_context(aTHX_ cxt);
4535
4536     INIT_TRACEME;
4537
4538     cxt->entry++;
4539
4540     ASSERT(cxt->entry == 1, ("starting new recursion"));
4541     ASSERT(!cxt->s_dirty, ("clean context"));
4542
4543     /*
4544      * Ensure sv is actually a reference. From perl, we called something
4545      * like:
4546      *       pstore(aTHX_ FILE, \@array);
4547      * so we must get the scalar value behind that reference.
4548      */
4549
4550     if (!SvROK(sv))
4551         CROAK(("Not a reference"));
4552     sv = SvRV(sv);              /* So follow it to know what to store */
4553
4554     /* 
4555      * If we're going to store to memory, reset the buffer.
4556      */
4557
4558     if (!f)
4559         MBUF_INIT(0);
4560
4561     /*
4562      * Prepare context and emit headers.
4563      */
4564
4565     init_store_context(aTHX_ cxt, f, optype, network_order);
4566
4567     if (-1 == magic_write(aTHX_ cxt))   /* Emit magic and ILP info */
4568         return 0;                       /* Error */
4569
4570     /*
4571      * Recursively store object...
4572      */
4573
4574     ASSERT(is_storing(aTHX), ("within store operation"));
4575
4576     status = store(aTHX_ cxt, sv);      /* Just do it! */
4577
4578     /*
4579      * If they asked for a memory store and they provided an SV pointer,
4580      * make an SV string out of the buffer and fill their pointer.
4581      *
4582      * When asking for ST_REAL, it's MANDATORY for the caller to provide
4583      * an SV, since context cleanup might free the buffer if we did recurse.
4584      * (unless caller is dclone(), which is aware of that).
4585      */
4586
4587     if (!cxt->fio && res)
4588         *res = mbuf2sv(aTHX);
4589
4590     TRACEME(("do_store returns %d", status));
4591
4592     /*
4593      * Final cleanup.
4594      *
4595      * The "root" context is never freed, since it is meant to be always
4596      * handy for the common case where no recursion occurs at all (i.e.
4597      * we enter store() outside of any Storable code and leave it, period).
4598      * We know it's the "root" context because there's nothing stacked
4599      * underneath it.
4600      *
4601      * OPTIMIZATION:
4602      *
4603      * When deep cloning, we don't free the context: doing so would force
4604      * us to copy the data in the memory buffer.  Sicne we know we're
4605      * about to enter do_retrieve...
4606      */
4607
4608     clean_store_context(aTHX_ cxt);
4609     if (cxt->prev && !(cxt->optype & ST_CLONE))
4610         free_context(aTHX_ cxt);
4611
4612     return status == 0;
4613 }
4614
4615 /***
4616  *** Memory stores.
4617  ***/
4618
4619 /*
4620  * mbuf2sv
4621  *
4622  * Build a new SV out of the content of the internal memory buffer.
4623  */
4624 static SV *mbuf2sv(pTHX)
4625 {
4626     dSTCXT;
4627
4628     assert(cxt);
4629     return newSVpv(mbase, MBUF_SIZE());
4630 }
4631
4632 /***
4633  *** Specific retrieve callbacks.
4634  ***/
4635
4636 /*
4637  * retrieve_other
4638  *
4639  * Return an error via croak, since it is not possible that we get here
4640  * under normal conditions, when facing a file produced via pstore().
4641  */
4642 static SV *retrieve_other(pTHX_ stcxt_t *cxt, const char *cname)
4643 {
4644     PERL_UNUSED_ARG(cname);
4645     if (
4646         cxt->ver_major != STORABLE_BIN_MAJOR &&
4647         cxt->ver_minor != STORABLE_BIN_MINOR
4648         ) {
4649         CROAK(("Corrupted storable %s (binary v%d.%d), current is v%d.%d",
4650                cxt->fio ? "file" : "string",
4651                cxt->ver_major, cxt->ver_minor,
4652                STORABLE_BIN_MAJOR, STORABLE_BIN_MINOR));
4653     } else {
4654         CROAK(("Corrupted storable %s (binary v%d.%d)",
4655                cxt->fio ? "file" : "string",
4656                cxt->ver_major, cxt->ver_minor));
4657     }
4658
4659     return (SV *) 0;            /* Just in case */
4660 }
4661
4662 /*
4663  * retrieve_idx_blessed
4664  *
4665  * Layout is SX_IX_BLESS <index> <object> with SX_IX_BLESS already read.
4666  * <index> can be coded on either 1 or 5 bytes.
4667  */
4668 static SV *retrieve_idx_blessed(pTHX_ stcxt_t *cxt, const char *cname)
4669 {
4670     I32 idx;
4671     const char *classname;
4672     SV **sva;
4673     SV *sv;
4674
4675     PERL_UNUSED_ARG(cname);
4676     TRACEME(("retrieve_idx_blessed (#%d)", (int)cxt->tagnum));
4677     ASSERT(!cname, ("no bless-into class given here, got %s", cname));
4678
4679     GETMARK(idx);                       /* Index coded on a single char? */
4680     if (idx & 0x80)
4681         RLEN(idx);
4682
4683     /*
4684      * Fetch classname in 'aclass'
4685      */
4686
4687     sva = av_fetch(cxt->aclass, idx, FALSE);
4688     if (!sva)
4689         CROAK(("Class name #%" IVdf " should have been seen already",
4690                (IV) idx));
4691
4692     classname = SvPVX(*sva);    /* We know it's a PV, by construction */
4693
4694     TRACEME(("class ID %d => %s", (int)idx, classname));
4695
4696     /*
4697      * Retrieve object and bless it.
4698      */
4699
4700     sv = retrieve(aTHX_ cxt, classname); /* First SV which is SEEN
4701                                             will be blessed */
4702
4703     return sv;
4704 }
4705
4706 /*
4707  * retrieve_blessed
4708  *
4709  * Layout is SX_BLESS <len> <classname> <object> with SX_BLESS already read.
4710  * <len> can be coded on either 1 or 5 bytes.
4711  */
4712 static SV *retrieve_blessed(pTHX_ stcxt_t *cxt, const char *cname)
4713 {
4714     U32 len;
4715     SV *sv;
4716     char buf[LG_BLESS + 1];             /* Avoid malloc() if possible */
4717     char *classname = buf;
4718     char *malloced_classname = NULL;
4719
4720     PERL_UNUSED_ARG(cname);
4721     TRACEME(("retrieve_blessed (#%d)", (int)cxt->tagnum));
4722     ASSERT(!cname, ("no bless-into class given here, got %s", cname));
4723
4724     /*
4725      * Decode class name length and read that name.
4726      *
4727      * Short classnames have two advantages: their length is stored on one
4728      * single byte, and the string can be read on the stack.
4729      */
4730
4731     GETMARK(len);                       /* Length coded on a single char? */
4732     if (len & 0x80) {
4733         RLEN(len);
4734         TRACEME(("** allocating %ld bytes for class name", (long)len+1));
4735         if (len > I32_MAX)
4736             CROAK(("Corrupted classname length %lu", (long)len));
4737         PL_nomemok = TRUE; /* handle error by ourselves */
4738         New(10003, classname, len+1, char);
4739         PL_nomemok = FALSE;
4740         if (!classname)
4741             CROAK(("Out of memory with len %ld", (long)len));
4742         PL_nomemok = FALSE;
4743         malloced_classname = classname;
4744     }
4745     SAFEPVREAD(classname, (I32)len, malloced_classname);
4746     classname[len] = '\0';              /* Mark string end */
4747
4748     /*
4749      * It's a new classname, otherwise it would have been an SX_IX_BLESS.
4750      */
4751
4752     TRACEME(("new class name \"%s\" will bear ID = %d", classname,
4753              (int)cxt->classnum));
4754
4755     if (!av_store(cxt->aclass, cxt->classnum++, newSVpvn(classname, len))) {
4756         Safefree(malloced_classname);
4757         return (SV *) 0;
4758     }
4759
4760     /*
4761      * Retrieve object and bless it.
4762      */
4763
4764     sv = retrieve(aTHX_ cxt, classname); /* First SV which is SEEN will be blessed */
4765     if (malloced_classname)
4766         Safefree(malloced_classname);
4767
4768     return sv;
4769 }
4770
4771 /*
4772  * retrieve_hook
4773  *
4774  * Layout: SX_HOOK <flags> <len> <classname> <len2> <str> [<len3> <object-IDs>]
4775  * with leading mark already read, as usual.
4776  *
4777  * When recursion was involved during serialization of the object, there
4778  * is an unknown amount of serialized objects after the SX_HOOK mark.  Until
4779  * we reach a <flags> marker with the recursion bit cleared.
4780  *
4781  * If the first <flags> byte contains a type of SHT_EXTRA, then the real type
4782  * is held in the <extra> byte, and if the object is tied, the serialized
4783  * magic object comes at the very end:
4784  *
4785  *     SX_HOOK <flags> <extra> ... [<len3> <object-IDs>] <magic object>
4786  *
4787  * This means the STORABLE_thaw hook will NOT get a tied variable during its
4788  * processing (since we won't have seen the magic object by the time the hook
4789  * is called).  See comments below for why it was done that way.
4790  */
4791 static SV *retrieve_hook_common(pTHX_ stcxt_t *cxt, const char *cname, int large)
4792 {
4793     U32 len;
4794     char buf[LG_BLESS + 1];             /* Avoid malloc() if possible */
4795     char *classname = buf;
4796     unsigned int flags;
4797     STRLEN len2;
4798     SV *frozen;
4799     I32 len3 = 0;
4800     AV *av = 0;
4801     SV *hook;
4802     SV *sv;
4803     SV *rv;
4804     GV *attach;
4805     HV *stash;
4806     int obj_type;
4807     int clone = cxt->optype & ST_CLONE;
4808     char mtype = '\0';
4809     unsigned int extra_type = 0;
4810 #ifdef HAS_U64
4811     int has_large_oids = 0;
4812 #endif
4813
4814     PERL_UNUSED_ARG(cname);
4815     TRACEME(("retrieve_hook (#%d)", (int)cxt->tagnum));
4816     ASSERT(!cname, ("no bless-into class given here, got %s", cname));
4817
4818 #ifndef HAS_U64
4819     assert(!large);
4820     PERL_UNUSED_ARG(large);
4821 #endif
4822
4823     /*
4824      * Read flags, which tell us about the type, and whether we need
4825      * to recurse.
4826      */
4827
4828     GETMARK(flags);
4829
4830     /*
4831      * Create the (empty) object, and mark it as seen.
4832      *
4833      * This must be done now, because tags are incremented, and during
4834      * serialization, the object tag was affected before recursion could
4835      * take place.
4836      */
4837
4838     obj_type = flags & SHF_TYPE_MASK;
4839     switch (obj_type) {
4840     case SHT_SCALAR:
4841         sv = newSV(0);
4842         break;
4843     case SHT_ARRAY:
4844         sv = (SV *) newAV();
4845         break;
4846     case SHT_HASH:
4847         sv = (SV *) newHV();
4848         break;
4849     case SHT_EXTRA:
4850         /*
4851          * Read <extra> flag to know the type of the object.
4852          * Record associated magic type for later.
4853          */
4854         GETMARK(extra_type);
4855         switch (extra_type) {
4856         case SHT_TSCALAR:
4857             sv = newSV(0);
4858             mtype = 'q';
4859             break;
4860         case SHT_TARRAY:
4861             sv = (SV *) newAV();
4862             mtype = 'P';
4863             break;
4864         case SHT_THASH:
4865             sv = (SV *) newHV();
4866             mtype = 'P';
4867             break;
4868         default:
4869             return retrieve_other(aTHX_ cxt, 0);/* Let it croak */
4870         }
4871         break;
4872     default:
4873         return retrieve_other(aTHX_ cxt, 0);    /* Let it croak */
4874     }
4875     SEEN0_NN(sv, 0);                            /* Don't bless yet */
4876
4877     /*
4878      * Whilst flags tell us to recurse, do so.
4879      *
4880      * We don't need to remember the addresses returned by retrieval, because
4881      * all the references will be obtained through indirection via the object
4882      * tags in the object-ID list.
4883      *
4884      * We need to decrement the reference count for these objects
4885      * because, if the user doesn't save a reference to them in the hook,
4886      * they must be freed when this context is cleaned.
4887      */
4888
4889     while (flags & SHF_NEED_RECURSE) {
4890         TRACEME(("retrieve_hook recursing..."));
4891         rv = retrieve(aTHX_ cxt, 0);
4892         if (!rv)
4893             return (SV *) 0;
4894         SvREFCNT_dec(rv);
4895         TRACEME(("retrieve_hook back with rv=0x%" UVxf,
4896                  PTR2UV(rv)));
4897         GETMARK(flags);
4898     }
4899
4900     if (flags & SHF_IDX_CLASSNAME) {
4901         SV **sva;
4902         I32 idx;
4903
4904         /*
4905          * Fetch index from 'aclass'
4906          */
4907
4908         if (flags & SHF_LARGE_CLASSLEN)
4909             RLEN(idx);
4910         else
4911             GETMARK(idx);
4912
4913         sva = av_fetch(cxt->aclass, idx, FALSE);
4914         if (!sva)
4915             CROAK(("Class name #%" IVdf " should have been seen already",
4916                    (IV) idx));
4917
4918         classname = SvPVX(*sva);        /* We know it's a PV, by construction */
4919         TRACEME(("class ID %d => %s", (int)idx, classname));
4920
4921     } else {
4922         /*
4923          * Decode class name length and read that name.
4924          *
4925          * NOTA BENE: even if the length is stored on one byte, we don't read
4926          * on the stack.  Just like retrieve_blessed(), we limit the name to
4927          * LG_BLESS bytes.  This is an arbitrary decision.
4928          */
4929         char *malloced_classname = NULL;
4930
4931         if (flags & SHF_LARGE_CLASSLEN)
4932             RLEN(len);
4933         else
4934             GETMARK(len);
4935
4936         TRACEME(("** allocating %ld bytes for class name", (long)len+1));
4937         if (len > I32_MAX) /* security */
4938             CROAK(("Corrupted classname length %lu", (long)len));
4939         else if (len > LG_BLESS) { /* security: signed len */
4940             PL_nomemok = TRUE;     /* handle error by ourselves */
4941             New(10003, classname, len+1, char);
4942             PL_nomemok = FALSE;
4943             if (!classname)
4944                 CROAK(("Out of memory with len %u", (unsigned)len+1));
4945             malloced_classname = classname;
4946         }
4947
4948         SAFEPVREAD(classname, (I32)len, malloced_classname);
4949         classname[len] = '\0';          /* Mark string end */
4950
4951         /*
4952          * Record new classname.
4953          */
4954
4955         if (!av_store(cxt->aclass, cxt->classnum++,
4956                       newSVpvn(classname, len))) {
4957             Safefree(malloced_classname);
4958             return (SV *) 0;
4959         }
4960     }
4961
4962     TRACEME(("class name: %s", classname));
4963
4964     /*
4965      * Decode user-frozen string length and read it in an SV.
4966      *
4967      * For efficiency reasons, we read data directly into the SV buffer.
4968      * To understand that code, read retrieve_scalar()
4969      */
4970
4971 #ifdef HAS_U64
4972     if (large) {
4973         READ_U64(len2);
4974     }
4975     else
4976 #endif
4977     if (flags & SHF_LARGE_STRLEN) {
4978         U32 len32;
4979         RLEN(len32);
4980         len2 = len32;
4981     }
4982     else
4983         GETMARK(len2);
4984
4985     frozen = NEWSV(10002, len2 ? len2 : 1);
4986     if (len2) {
4987         SAFEREAD(SvPVX(frozen), len2, frozen);
4988     }
4989     SvCUR_set(frozen, len2);
4990     *SvEND(frozen) = '\0';
4991     (void) SvPOK_only(frozen);          /* Validates string pointer */
4992     if (cxt->s_tainted)                 /* Is input source tainted? */
4993         SvTAINT(frozen);
4994
4995     TRACEME(("frozen string: %d bytes", (int)len2));
4996
4997     /*
4998      * Decode object-ID list length, if present.
4999      */
5000
5001     if (flags & SHF_HAS_LIST) {
5002         if (flags & SHF_LARGE_LISTLEN) {
5003             RLEN(len3);
5004             if (len3 < 0) {
5005 #ifdef HAS_U64
5006                 ++has_large_oids;
5007                 len3 = -len3;
5008 #else
5009                 CROAK(("Large object ids in hook data not supported on 32-bit platforms"));
5010 #endif
5011                 
5012             }
5013         }
5014         else
5015             GETMARK(len3);
5016         if (len3) {
5017             av = newAV();
5018             av_extend(av, len3 + 1);    /* Leave room for [0] */
5019             AvFILLp(av) = len3;         /* About to be filled anyway */
5020         }
5021     }
5022
5023     TRACEME(("has %d object IDs to link", (int)len3));
5024
5025     /*
5026      * Read object-ID list into array.
5027      * Because we pre-extended it, we can cheat and fill it manually.
5028      *
5029      * We read object tags and we can convert them into SV* on the fly
5030      * because we know all the references listed in there (as tags)
5031      * have been already serialized, hence we have a valid correspondence
5032      * between each of those tags and the recreated SV.
5033      */
5034
5035     if (av) {
5036         SV **ary = AvARRAY(av);
5037         int i;
5038         for (i = 1; i <= len3; i++) {   /* We leave [0] alone */
5039             ntag_t tag;
5040             SV **svh;
5041             SV *xsv;
5042
5043 #ifdef HAS_U64
5044             if (has_large_oids) {
5045                 READ_U64(tag);
5046             }
5047             else {
5048                 U32 tmp;
5049                 READ_I32(tmp);
5050                 tag = ntohl(tmp);
5051             }
5052 #else
5053             READ_I32(tag);
5054             tag = ntohl(tag);
5055 #endif
5056
5057             svh = av_fetch(cxt->aseen, tag, FALSE);
5058             if (!svh) {
5059                 if (tag == cxt->where_is_undef) {
5060                     /* av_fetch uses PL_sv_undef internally, hence this
5061                        somewhat gruesome hack. */
5062                     xsv = &PL_sv_undef;
5063                     svh = &xsv;
5064                 } else {
5065                     CROAK(("Object #%" IVdf
5066                            " should have been retrieved already",
5067                            (IV) tag));
5068                 }
5069             }
5070             xsv = *svh;
5071             ary[i] = SvREFCNT_inc(xsv);
5072         }
5073     }
5074
5075     /*
5076      * Look up the STORABLE_attach hook
5077      * If blessing is disabled, just return what we've got.
5078      */
5079     if (!(cxt->flags & FLAG_BLESS_OK)) {
5080         TRACEME(("skipping bless because flags is %d", cxt->flags));
5081         return sv;
5082     }
5083
5084     /*
5085      * Bless the object and look up the STORABLE_thaw hook.
5086      */
5087     stash = gv_stashpv(classname, GV_ADD);
5088
5089     /* Handle attach case; again can't use pkg_can because it only
5090      * caches one method */
5091     attach = gv_fetchmethod_autoload(stash, "STORABLE_attach", FALSE);
5092     if (attach && isGV(attach)) {
5093         SV* attached;
5094         SV* attach_hook = newRV_inc((SV*) GvCV(attach));
5095
5096         if (av)
5097             CROAK(("STORABLE_attach called with unexpected references"));
5098         av = newAV();
5099         av_extend(av, 1);
5100         AvFILLp(av) = 0;
5101         AvARRAY(av)[0] = SvREFCNT_inc(frozen);
5102         rv = newSVpv(classname, 0);
5103         attached = scalar_call(aTHX_ rv, attach_hook, clone, av, G_SCALAR);
5104         /* Free memory after a call */
5105         SvREFCNT_dec(rv);
5106         SvREFCNT_dec(frozen);
5107         av_undef(av);
5108         sv_free((SV *) av);
5109         SvREFCNT_dec(attach_hook);
5110         if (attached &&
5111             SvROK(attached) && 
5112             sv_derived_from(attached, classname)
5113             ) {
5114             UNSEE();
5115             /* refcnt of unneeded sv is 2 at this point
5116                (one from newHV, second from SEEN call) */
5117             SvREFCNT_dec(sv);
5118             SvREFCNT_dec(sv);
5119             /* we need to free RV but preserve value that RV point to */
5120             sv = SvRV(attached);
5121             SEEN0_NN(sv, 0);
5122             SvRV_set(attached, NULL);
5123             SvREFCNT_dec(attached);
5124             if (!(flags & SHF_IDX_CLASSNAME) && classname != buf)
5125                 Safefree(classname);
5126             return sv;
5127         }
5128         CROAK(("STORABLE_attach did not return a %s object", classname));
5129     }
5130
5131     /*
5132      * Bless the object and look up the STORABLE_thaw hook.
5133      */
5134
5135     BLESS(sv, stash);
5136
5137     hook = pkg_can(aTHX_ cxt->hook, stash, "STORABLE_thaw");
5138     if (!hook) {
5139         /*
5140          * Hook not found.  Maybe they did not require the module where this
5141          * hook is defined yet?
5142          *
5143          * If the load below succeeds, we'll be able to find the hook.
5144          * Still, it only works reliably when each class is defined in a
5145          * file of its own.
5146          */
5147
5148         TRACEME(("No STORABLE_thaw defined for objects of class %s", classname));
5149         TRACEME(("Going to load module '%s'", classname));
5150         load_module(PERL_LOADMOD_NOIMPORT, newSVpv(classname, 0), Nullsv);
5151
5152         /*
5153          * We cache results of pkg_can, so we need to uncache before attempting
5154          * the lookup again.
5155          */
5156
5157         pkg_uncache(aTHX_ cxt->hook, SvSTASH(sv), "STORABLE_thaw");
5158         hook = pkg_can(aTHX_ cxt->hook, SvSTASH(sv), "STORABLE_thaw");
5159
5160         if (!hook)
5161             CROAK(("No STORABLE_thaw defined for objects of class %s "
5162                    "(even after a \"require %s;\")", classname, classname));
5163     }
5164
5165     /*
5166      * If we don't have an 'av' yet, prepare one.
5167      * Then insert the frozen string as item [0].
5168      */
5169
5170     if (!av) {
5171         av = newAV();
5172         av_extend(av, 1);
5173         AvFILLp(av) = 0;
5174     }
5175     AvARRAY(av)[0] = SvREFCNT_inc(frozen);
5176
5177     /*
5178      * Call the hook as:
5179      *
5180      *   $object->STORABLE_thaw($cloning, $frozen, @refs);
5181      *
5182      * where $object is our blessed (empty) object, $cloning is a boolean
5183      * telling whether we're running a deep clone, $frozen is the frozen
5184      * string the user gave us in his serializing hook, and @refs, which may
5185      * be empty, is the list of extra references he returned along for us
5186      * to serialize.
5187      *
5188      * In effect, the hook is an alternate creation routine for the class,
5189      * the object itself being already created by the runtime.
5190      */
5191
5192     TRACEME(("calling STORABLE_thaw on %s at 0x%" UVxf " (%" IVdf " args)",
5193              classname, PTR2UV(sv), (IV) AvFILLp(av) + 1));
5194
5195     rv = newRV_inc(sv);
5196     (void) scalar_call(aTHX_ rv, hook, clone, av, G_SCALAR|G_DISCARD);
5197     SvREFCNT_dec(rv);
5198
5199     /*
5200      * Final cleanup.
5201      */
5202
5203     SvREFCNT_dec(frozen);
5204     av_undef(av);
5205     sv_free((SV *) av);
5206     if (!(flags & SHF_IDX_CLASSNAME) && classname != buf)
5207         Safefree(classname);
5208
5209     /*
5210      * If we had an <extra> type, then the object was not as simple, and
5211      * we need to restore extra magic now.
5212      */
5213
5214     if (!extra_type)
5215         return sv;
5216
5217     TRACEME(("retrieving magic object for 0x%" UVxf "...", PTR2UV(sv)));
5218
5219     rv = retrieve(aTHX_ cxt, 0);        /* Retrieve <magic object> */
5220
5221     TRACEME(("restoring the magic object 0x%" UVxf " part of 0x%" UVxf,
5222              PTR2UV(rv), PTR2UV(sv)));
5223
5224     switch (extra_type) {
5225     case SHT_TSCALAR:
5226         sv_upgrade(sv, SVt_PVMG);
5227         break;
5228     case SHT_TARRAY:
5229         sv_upgrade(sv, SVt_PVAV);
5230         AvREAL_off((AV *)sv);
5231         break;
5232     case SHT_THASH:
5233         sv_upgrade(sv, SVt_PVHV);
5234         break;
5235     default:
5236         CROAK(("Forgot to deal with extra type %d", extra_type));
5237         break;
5238     }
5239
5240     /*
5241      * Adding the magic only now, well after the STORABLE_thaw hook was called
5242      * means the hook cannot know it deals with an object whose variable is
5243      * tied.  But this is happening when retrieving $o in the following case:
5244      *
5245      *  my %h;
5246      *  tie %h, 'FOO';
5247      *  my $o = bless \%h, 'BAR';
5248      *
5249      * The 'BAR' class is NOT the one where %h is tied into.  Therefore, as
5250      * far as the 'BAR' class is concerned, the fact that %h is not a REAL
5251      * hash but a tied one should not matter at all, and remain transparent.
5252      * This means the magic must be restored by Storable AFTER the hook is
5253      * called.
5254      *
5255      * That looks very reasonable to me, but then I've come up with this
5256      * after a bug report from David Nesting, who was trying to store such
5257      * an object and caused Storable to fail.  And unfortunately, it was
5258      * also the easiest way to retrofit support for blessed ref to tied objects
5259      * into the existing design.  -- RAM, 17/02/2001
5260      */
5261
5262     sv_magic(sv, rv, mtype, (char *)NULL, 0);
5263     SvREFCNT_dec(rv);                   /* Undo refcnt inc from sv_magic() */
5264
5265     return sv;
5266 }
5267
5268 static SV *retrieve_hook(pTHX_ stcxt_t *cxt, const char *cname) {
5269     return retrieve_hook_common(aTHX_ cxt, cname, FALSE);
5270 }
5271
5272 /*
5273  * retrieve_ref
5274  *
5275  * Retrieve reference to some other scalar.
5276  * Layout is SX_REF <object>, with SX_REF already read.
5277  */
5278 static SV *retrieve_ref(pTHX_ stcxt_t *cxt, const char *cname)
5279 {
5280     SV *rv;
5281     SV *sv;
5282     HV *stash;
5283
5284     TRACEME(("retrieve_ref (#%d)", (int)cxt->tagnum));
5285
5286     /*
5287      * We need to create the SV that holds the reference to the yet-to-retrieve
5288      * object now, so that we may record the address in the seen table.
5289      * Otherwise, if the object to retrieve references us, we won't be able
5290      * to resolve the SX_OBJECT we'll see at that point! Hence we cannot
5291      * do the retrieve first and use rv = newRV(sv) since it will be too late
5292      * for SEEN() recording.
5293      */
5294
5295     rv = NEWSV(10002, 0);
5296     if (cname)
5297         stash = gv_stashpv(cname, GV_ADD);
5298     else
5299         stash = 0;
5300     SEEN_NN(rv, stash, 0);      /* Will return if rv is null */
5301     sv = retrieve(aTHX_ cxt, 0);/* Retrieve <object> */
5302     if (!sv)
5303         return (SV *) 0;        /* Failed */
5304
5305     /*
5306      * WARNING: breaks RV encapsulation.
5307      *
5308      * Now for the tricky part. We have to upgrade our existing SV, so that
5309      * it is now an RV on sv... Again, we cheat by duplicating the code
5310      * held in newSVrv(), since we already got our SV from retrieve().
5311      *
5312      * We don't say:
5313      *
5314      *          SvRV(rv) = SvREFCNT_inc(sv);
5315      *
5316      * here because the reference count we got from retrieve() above is
5317      * already correct: if the object was retrieved from the file, then
5318      * its reference count is one. Otherwise, if it was retrieved via
5319      * an SX_OBJECT indication, a ref count increment was done.
5320      */
5321
5322     if (cname) {
5323         /* No need to do anything, as rv will already be PVMG.  */
5324         assert (SvTYPE(rv) == SVt_RV || SvTYPE(rv) >= SVt_PV);
5325     } else {
5326         sv_upgrade(rv, SVt_RV);
5327     }
5328
5329     SvRV_set(rv, sv);           /* $rv = \$sv */
5330     SvROK_on(rv);
5331     /*if (cxt->entry && ++cxt->ref_cnt > MAX_REF_CNT) {
5332         CROAK(("Max. recursion depth with nested refs exceeded"));
5333     }*/
5334
5335     TRACEME(("ok (retrieve_ref at 0x%" UVxf ")", PTR2UV(rv)));
5336
5337     return rv;
5338 }
5339
5340 /*
5341  * retrieve_weakref
5342  *
5343  * Retrieve weak reference to some other scalar.
5344  * Layout is SX_WEAKREF <object>, with SX_WEAKREF already read.
5345  */
5346 static SV *retrieve_weakref(pTHX_ stcxt_t *cxt, const char *cname)
5347 {
5348     SV *sv;
5349
5350     TRACEME(("retrieve_weakref (#%d)", (int)cxt->tagnum));
5351
5352     sv = retrieve_ref(aTHX_ cxt, cname);
5353     if (sv) {
5354 #ifdef SvWEAKREF
5355         sv_rvweaken(sv);
5356 #else
5357         WEAKREF_CROAK();
5358 #endif
5359     }
5360     return sv;
5361 }
5362
5363 /*
5364  * retrieve_overloaded
5365  *
5366  * Retrieve reference to some other scalar with overloading.
5367  * Layout is SX_OVERLOAD <object>, with SX_OVERLOAD already read.
5368  */
5369 static SV *retrieve_overloaded(pTHX_ stcxt_t *cxt, const char *cname)
5370 {
5371     SV *rv;
5372     SV *sv;
5373     HV *stash;
5374
5375     TRACEME(("retrieve_overloaded (#%d)", (int)cxt->tagnum));
5376
5377     /*
5378      * Same code as retrieve_ref(), duplicated to avoid extra call.
5379      */
5380
5381     rv = NEWSV(10002, 0);
5382     stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5383     SEEN_NN(rv, stash, 0);           /* Will return if rv is null */
5384     cxt->in_retrieve_overloaded = 1; /* so sv_bless doesn't call S_reset_amagic */
5385     sv = retrieve(aTHX_ cxt, 0);     /* Retrieve <object> */
5386     cxt->in_retrieve_overloaded = 0;
5387     if (!sv)
5388         return (SV *) 0;        /* Failed */
5389
5390     /*
5391      * WARNING: breaks RV encapsulation.
5392      */
5393
5394     SvUPGRADE(rv, SVt_RV);
5395     SvRV_set(rv, sv);           /* $rv = \$sv */
5396     SvROK_on(rv);
5397
5398     /*
5399      * Restore overloading magic.
5400      */
5401
5402     stash = SvTYPE(sv) ? (HV *) SvSTASH (sv) : 0;
5403     if (!stash) {
5404         CROAK(("Cannot restore overloading on %s(0x%" UVxf
5405                ") (package <unknown>)",
5406                sv_reftype(sv, FALSE),
5407                PTR2UV(sv)));
5408     }
5409     if (!Gv_AMG(stash)) {
5410         const char *package = HvNAME_get(stash);
5411         TRACEME(("No overloading defined for package %s", package));
5412         TRACEME(("Going to load module '%s'", package));
5413         load_module(PERL_LOADMOD_NOIMPORT, newSVpv(package, 0), Nullsv);
5414         if (!Gv_AMG(stash)) {
5415             CROAK(("Cannot restore overloading on %s(0x%" UVxf
5416                    ") (package %s) (even after a \"require %s;\")",
5417                    sv_reftype(sv, FALSE),
5418                    PTR2UV(sv),
5419                    package, package));
5420         }
5421     }
5422
5423     SvAMAGIC_on(rv);
5424
5425     TRACEME(("ok (retrieve_overloaded at 0x%" UVxf ")", PTR2UV(rv)));
5426
5427     return rv;
5428 }
5429
5430 /*
5431  * retrieve_weakoverloaded
5432  *
5433  * Retrieve weak overloaded reference to some other scalar.
5434  * Layout is SX_WEAKOVERLOADED <object>, with SX_WEAKOVERLOADED already read.
5435  */
5436 static SV *retrieve_weakoverloaded(pTHX_ stcxt_t *cxt, const char *cname)
5437 {
5438     SV *sv;
5439
5440     TRACEME(("retrieve_weakoverloaded (#%d)", (int)cxt->tagnum));
5441
5442     sv = retrieve_overloaded(aTHX_ cxt, cname);
5443     if (sv) {
5444 #ifdef SvWEAKREF
5445         sv_rvweaken(sv);
5446 #else
5447         WEAKREF_CROAK();
5448 #endif
5449     }
5450     return sv;
5451 }
5452
5453 /*
5454  * retrieve_tied_array
5455  *
5456  * Retrieve tied array
5457  * Layout is SX_TIED_ARRAY <object>, with SX_TIED_ARRAY already read.
5458  */
5459 static SV *retrieve_tied_array(pTHX_ stcxt_t *cxt, const char *cname)
5460 {
5461     SV *tv;
5462     SV *sv;
5463     HV *stash;
5464
5465     TRACEME(("retrieve_tied_array (#%d)", (int)cxt->tagnum));
5466
5467     if (!(cxt->flags & FLAG_TIE_OK)) {
5468         CROAK(("Tying is disabled."));
5469     }
5470
5471     tv = NEWSV(10002, 0);
5472     stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5473     SEEN_NN(tv, stash, 0);              /* Will return if tv is null */
5474     sv = retrieve(aTHX_ cxt, 0);        /* Retrieve <object> */
5475     if (!sv)
5476         return (SV *) 0;                /* Failed */
5477
5478     sv_upgrade(tv, SVt_PVAV);
5479     sv_magic(tv, sv, 'P', (char *)NULL, 0);
5480     SvREFCNT_dec(sv);                   /* Undo refcnt inc from sv_magic() */
5481
5482     TRACEME(("ok (retrieve_tied_array at 0x%" UVxf ")", PTR2UV(tv)));
5483
5484     return tv;
5485 }
5486
5487 /*
5488  * retrieve_tied_hash
5489  *
5490  * Retrieve tied hash
5491  * Layout is SX_TIED_HASH <object>, with SX_TIED_HASH already read.
5492  */
5493 static SV *retrieve_tied_hash(pTHX_ stcxt_t *cxt, const char *cname)
5494 {
5495     SV *tv;
5496     SV *sv;
5497     HV *stash;
5498
5499     TRACEME(("retrieve_tied_hash (#%d)", (int)cxt->tagnum));
5500
5501     if (!(cxt->flags & FLAG_TIE_OK)) {
5502         CROAK(("Tying is disabled."));
5503     }
5504
5505     tv = NEWSV(10002, 0);
5506     stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5507     SEEN_NN(tv, stash, 0);              /* Will return if tv is null */
5508     sv = retrieve(aTHX_ cxt, 0);        /* Retrieve <object> */
5509     if (!sv)
5510         return (SV *) 0;                /* Failed */
5511
5512     sv_upgrade(tv, SVt_PVHV);
5513     sv_magic(tv, sv, 'P', (char *)NULL, 0);
5514     SvREFCNT_dec(sv);                   /* Undo refcnt inc from sv_magic() */
5515
5516     TRACEME(("ok (retrieve_tied_hash at 0x%" UVxf ")", PTR2UV(tv)));
5517
5518     return tv;
5519 }
5520
5521 /*
5522  * retrieve_tied_scalar
5523  *
5524  * Retrieve tied scalar
5525  * Layout is SX_TIED_SCALAR <object>, with SX_TIED_SCALAR already read.
5526  */
5527 static SV *retrieve_tied_scalar(pTHX_ stcxt_t *cxt, const char *cname)
5528 {
5529     SV *tv;
5530     SV *sv, *obj = NULL;
5531     HV *stash;
5532
5533     TRACEME(("retrieve_tied_scalar (#%d)", (int)cxt->tagnum));
5534
5535     if (!(cxt->flags & FLAG_TIE_OK)) {
5536         CROAK(("Tying is disabled."));
5537     }
5538
5539     tv = NEWSV(10002, 0);
5540     stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5541     SEEN_NN(tv, stash, 0);              /* Will return if rv is null */
5542     sv = retrieve(aTHX_ cxt, 0);        /* Retrieve <object> */
5543     if (!sv) {
5544         return (SV *) 0;                /* Failed */
5545     }
5546     else if (SvTYPE(sv) != SVt_NULL) {
5547         obj = sv;
5548     }
5549
5550     sv_upgrade(tv, SVt_PVMG);
5551     sv_magic(tv, obj, 'q', (char *)NULL, 0);
5552
5553     if (obj) {
5554         /* Undo refcnt inc from sv_magic() */
5555         SvREFCNT_dec(obj);
5556     }
5557
5558     TRACEME(("ok (retrieve_tied_scalar at 0x%" UVxf ")", PTR2UV(tv)));
5559
5560     return tv;
5561 }
5562
5563 /*
5564  * retrieve_tied_key
5565  *
5566  * Retrieve reference to value in a tied hash.
5567  * Layout is SX_TIED_KEY <object> <key>, with SX_TIED_KEY already read.
5568  */
5569 static SV *retrieve_tied_key(pTHX_ stcxt_t *cxt, const char *cname)
5570 {
5571     SV *tv;
5572     SV *sv;
5573     SV *key;
5574     HV *stash;
5575
5576     TRACEME(("retrieve_tied_key (#%d)", (int)cxt->tagnum));
5577
5578     if (!(cxt->flags & FLAG_TIE_OK)) {
5579         CROAK(("Tying is disabled."));
5580     }
5581
5582     tv = NEWSV(10002, 0);
5583     stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5584     SEEN_NN(tv, stash, 0);              /* Will return if tv is null */
5585     sv = retrieve(aTHX_ cxt, 0);        /* Retrieve <object> */
5586     if (!sv)
5587         return (SV *) 0;                /* Failed */
5588
5589     key = retrieve(aTHX_ cxt, 0);       /* Retrieve <key> */
5590     if (!key)
5591         return (SV *) 0;                /* Failed */
5592
5593     sv_upgrade(tv, SVt_PVMG);
5594     sv_magic(tv, sv, 'p', (char *)key, HEf_SVKEY);
5595     SvREFCNT_dec(key);                  /* Undo refcnt inc from sv_magic() */
5596     SvREFCNT_dec(sv);                   /* Undo refcnt inc from sv_magic() */
5597
5598     return tv;
5599 }
5600
5601 /*
5602  * retrieve_tied_idx
5603  *
5604  * Retrieve reference to value in a tied array.
5605  * Layout is SX_TIED_IDX <object> <idx>, with SX_TIED_IDX already read.
5606  */
5607 static SV *retrieve_tied_idx(pTHX_ stcxt_t *cxt, const char *cname)
5608 {
5609     SV *tv;
5610     SV *sv;
5611     HV *stash;
5612     I32 idx;
5613
5614     TRACEME(("retrieve_tied_idx (#%d)", (int)cxt->tagnum));
5615
5616     if (!(cxt->flags & FLAG_TIE_OK)) {
5617         CROAK(("Tying is disabled."));
5618     }
5619
5620     tv = NEWSV(10002, 0);
5621     stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5622     SEEN_NN(tv, stash, 0);              /* Will return if tv is null */
5623     sv = retrieve(aTHX_ cxt, 0);        /* Retrieve <object> */
5624     if (!sv)
5625         return (SV *) 0;                /* Failed */
5626
5627     RLEN(idx);                          /* Retrieve <idx> */
5628
5629     sv_upgrade(tv, SVt_PVMG);
5630     sv_magic(tv, sv, 'p', (char *)NULL, idx);
5631     SvREFCNT_dec(sv);                   /* Undo refcnt inc from sv_magic() */
5632
5633     return tv;
5634 }
5635
5636 /*
5637  * get_lstring
5638  *
5639  * Helper to read a string
5640  */
5641 static SV *get_lstring(pTHX_ stcxt_t *cxt, UV len, int isutf8, const char *cname)
5642 {
5643     SV *sv;
5644     HV *stash;
5645
5646     TRACEME(("get_lstring (#%d), len = %" UVuf, (int)cxt->tagnum, len));
5647
5648     /*
5649      * Allocate an empty scalar of the suitable length.
5650      */
5651
5652     sv = NEWSV(10002, len);
5653     stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5654     SEEN_NN(sv, stash, 0);      /* Associate this new scalar with tag "tagnum" */
5655
5656     if (len ==  0) {
5657         SvPVCLEAR(sv);
5658         return sv;
5659     }
5660
5661     /*
5662      * WARNING: duplicates parts of sv_setpv and breaks SV data encapsulation.
5663      *
5664      * Now, for efficiency reasons, read data directly inside the SV buffer,
5665      * and perform the SV final settings directly by duplicating the final
5666      * work done by sv_setpv. Since we're going to allocate lots of scalars
5667      * this way, it's worth the hassle and risk.
5668      */
5669
5670     SAFEREAD(SvPVX(sv), len, sv);
5671     SvCUR_set(sv, len);                 /* Record C string length */
5672     *SvEND(sv) = '\0';                  /* Ensure it's null terminated anyway */
5673     (void) SvPOK_only(sv);              /* Validate string pointer */
5674     if (cxt->s_tainted)                 /* Is input source tainted? */
5675         SvTAINT(sv);                    /* External data cannot be trusted */
5676
5677     /* Check for CVE-215-1592 */
5678     if (cname && len == 13 && strEQc(cname, "CGITempFile")
5679         && strEQc(SvPVX(sv), "mt-config.cgi")) {
5680 #if defined(USE_CPERL) && defined(WARN_SECURITY)
5681         Perl_warn_security(aTHX_
5682             "Movable-Type CVE-2015-1592 Storable metasploit attack");
5683 #else
5684         Perl_warn(aTHX_
5685             "SECURITY: Movable-Type CVE-2015-1592 Storable metasploit attack");
5686 #endif
5687     }
5688
5689     if (isutf8) {
5690         TRACEME(("large utf8 string len %" UVuf " '%s'", len,
5691                  len >= 2048 ? "<string too long>" : SvPVX(sv)));
5692 #ifdef HAS_UTF8_SCALARS
5693         SvUTF8_on(sv);
5694 #else
5695         if (cxt->use_bytes < 0)
5696             cxt->use_bytes
5697                 = (SvTRUE(get_sv("Storable::drop_utf8", GV_ADD))
5698                    ? 1 : 0);
5699         if (cxt->use_bytes == 0)
5700             UTF8_CROAK();
5701 #endif
5702     } else {
5703         TRACEME(("large string len %" UVuf " '%s'", len,
5704                  len >= 2048 ? "<string too long>" : SvPVX(sv)));
5705     }
5706     TRACEME(("ok (get_lstring at 0x%" UVxf ")", PTR2UV(sv)));
5707
5708     return sv;
5709 }
5710
5711 /*
5712  * retrieve_lscalar
5713  *
5714  * Retrieve defined long (string) scalar.
5715  *
5716  * Layout is SX_LSCALAR <length> <data>, with SX_LSCALAR already read.
5717  * The scalar is "long" in that <length> is larger than LG_SCALAR so it
5718  * was not stored on a single byte, but in 4 bytes. For strings longer than
5719  * 4 byte (>2GB) see retrieve_lobject.
5720  */
5721 static SV *retrieve_lscalar(pTHX_ stcxt_t *cxt, const char *cname)
5722 {
5723     U32 len;
5724     RLEN(len);
5725     return get_lstring(aTHX_ cxt, len, 0, cname);
5726 }
5727
5728 /*
5729  * retrieve_scalar
5730  *
5731  * Retrieve defined short (string) scalar.
5732  *
5733  * Layout is SX_SCALAR <length> <data>, with SX_SCALAR already read.
5734  * The scalar is "short" so <length> is single byte. If it is 0, there
5735  * is no <data> section.
5736  */
5737 static SV *retrieve_scalar(pTHX_ stcxt_t *cxt, const char *cname)
5738 {
5739     int len;
5740     /*SV *sv;
5741       HV *stash;*/
5742
5743     GETMARK(len);
5744     TRACEME(("retrieve_scalar (#%d), len = %d", (int)cxt->tagnum, len));
5745     return get_lstring(aTHX_ cxt, (UV)len, 0, cname);
5746 }
5747
5748 /*
5749  * retrieve_utf8str
5750  *
5751  * Like retrieve_scalar(), but tag result as utf8.
5752  * If we're retrieving UTF8 data in a non-UTF8 perl, croaks.
5753  */
5754 static SV *retrieve_utf8str(pTHX_ stcxt_t *cxt, const char *cname)
5755 {
5756     int len;
5757     /*SV *sv;*/
5758
5759     TRACEME(("retrieve_utf8str"));
5760     GETMARK(len);
5761     return get_lstring(aTHX_ cxt, (UV)len, 1, cname);
5762 }
5763
5764 /*
5765  * retrieve_lutf8str
5766  *
5767  * Like retrieve_lscalar(), but tag result as utf8.
5768  * If we're retrieving UTF8 data in a non-UTF8 perl, croaks.
5769  */
5770 static SV *retrieve_lutf8str(pTHX_ stcxt_t *cxt, const char *cname)
5771 {
5772     U32 len;
5773
5774     TRACEME(("retrieve_lutf8str"));
5775
5776     RLEN(len);
5777     return get_lstring(aTHX_ cxt, (UV)len, 1, cname);
5778 }
5779
5780 /*
5781  * retrieve_vstring
5782  *
5783  * Retrieve a vstring, and then retrieve the stringy scalar following it,
5784  * attaching the vstring to the scalar via magic.
5785  * If we're retrieving a vstring in a perl without vstring magic, croaks.
5786  *
5787  * The vstring layout mirrors an SX_SCALAR string:
5788  * SX_VSTRING <length> <data> with SX_VSTRING already read.
5789  */
5790 static SV *retrieve_vstring(pTHX_ stcxt_t *cxt, const char *cname)
5791 {
5792 #ifdef SvVOK
5793     char s[256];
5794     int len;
5795     SV *sv;
5796
5797     GETMARK(len);
5798     TRACEME(("retrieve_vstring (#%d), len = %d", (int)cxt->tagnum, len));
5799
5800     READ(s, len);
5801     sv = retrieve(aTHX_ cxt, cname);
5802     if (!sv)
5803         return (SV *) 0;                /* Failed */
5804     sv_magic(sv,NULL,PERL_MAGIC_vstring,s,len);
5805     /* 5.10.0 and earlier seem to need this */
5806     SvRMAGICAL_on(sv);
5807
5808     TRACEME(("ok (retrieve_vstring at 0x%" UVxf ")", PTR2UV(sv)));
5809     return sv;
5810 #else
5811     VSTRING_CROAK();
5812     return Nullsv;
5813 #endif
5814 }
5815
5816 /*
5817  * retrieve_lvstring
5818  *
5819  * Like retrieve_vstring, but for longer vstrings.
5820  */
5821 static SV *retrieve_lvstring(pTHX_ stcxt_t *cxt, const char *cname)
5822 {
5823 #ifdef SvVOK
5824     char *s;
5825     U32 len;
5826     SV *sv;
5827
5828     RLEN(len);
5829     TRACEME(("retrieve_lvstring (#%d), len = %" UVuf,
5830              (int)cxt->tagnum, (UV)len));
5831
5832     /* Since we'll no longer produce such large vstrings, reject them
5833        here too.
5834     */
5835     if (len >= I32_MAX) {
5836         CROAK(("vstring too large to fetch"));
5837     }
5838
5839     New(10003, s, len+1, char);
5840     SAFEPVREAD(s, (I32)len, s);
5841
5842     sv = retrieve(aTHX_ cxt, cname);
5843     if (!sv) {
5844         Safefree(s);
5845         return (SV *) 0;                /* Failed */
5846     }
5847     sv_magic(sv,NULL,PERL_MAGIC_vstring,s,len);
5848     /* 5.10.0 and earlier seem to need this */
5849     SvRMAGICAL_on(sv);
5850
5851     Safefree(s);
5852
5853     TRACEME(("ok (retrieve_lvstring at 0x%" UVxf ")", PTR2UV(sv)));
5854     return sv;
5855 #else
5856     VSTRING_CROAK();
5857     return Nullsv;
5858 #endif
5859 }
5860
5861 /*
5862  * retrieve_integer
5863  *
5864  * Retrieve defined integer.
5865  * Layout is SX_INTEGER <data>, whith SX_INTEGER already read.
5866  */
5867 static SV *retrieve_integer(pTHX_ stcxt_t *cxt, const char *cname)
5868 {
5869     SV *sv;
5870     HV *stash;
5871     IV iv;
5872
5873     TRACEME(("retrieve_integer (#%d)", (int)cxt->tagnum));
5874
5875     READ(&iv, sizeof(iv));
5876     sv = newSViv(iv);
5877     stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5878     SEEN_NN(sv, stash, 0);      /* Associate this new scalar with tag "tagnum" */
5879
5880     TRACEME(("integer %" IVdf, iv));
5881     TRACEME(("ok (retrieve_integer at 0x%" UVxf ")", PTR2UV(sv)));
5882
5883     return sv;
5884 }
5885
5886 /*
5887  * retrieve_lobject
5888  *
5889  * Retrieve overlong scalar, array or hash.
5890  * Layout is SX_LOBJECT type U64_len ...
5891  */
5892 static SV *retrieve_lobject(pTHX_ stcxt_t *cxt, const char *cname)
5893 {
5894     int type;
5895 #ifdef HAS_U64
5896     UV  len;
5897     SV *sv;
5898     int hash_flags = 0;
5899 #endif
5900
5901     TRACEME(("retrieve_lobject (#%d)", (int)cxt->tagnum));
5902
5903     GETMARK(type);
5904     TRACEME(("object type %d", type));
5905 #ifdef HAS_U64
5906
5907     if (type == SX_FLAG_HASH) {
5908         /* we write the flags immediately after the op.  I could have
5909            changed the writer, but this may allow someone to recover
5910            data they're already frozen, though such a very large hash
5911            seems unlikely.
5912         */
5913         GETMARK(hash_flags);
5914     }
5915     else if (type == SX_HOOK) {
5916         return retrieve_hook_common(aTHX_ cxt, cname, TRUE);
5917     }
5918
5919     READ_U64(len);
5920     TRACEME(("wlen %" UVuf, len));
5921     switch (type) {
5922     case SX_OBJECT:
5923         {
5924             /* not a large object, just a large index */
5925             SV **svh = av_fetch(cxt->aseen, len, FALSE);
5926             if (!svh)
5927                 CROAK(("Object #%" UVuf " should have been retrieved already",
5928                       len));
5929             sv = *svh;
5930             TRACEME(("had retrieved #%" UVuf " at 0x%" UVxf, len, PTR2UV(sv)));
5931             SvREFCNT_inc(sv);
5932         }
5933         break;
5934     case SX_LSCALAR:
5935         sv = get_lstring(aTHX_ cxt, len, 0, cname);
5936         break;
5937     case SX_LUTF8STR:
5938         sv = get_lstring(aTHX_ cxt, len, 1, cname);
5939         break;
5940     case SX_ARRAY:
5941         sv = get_larray(aTHX_ cxt, len, cname);
5942         break;
5943     /* <5.12 you could store larger hashes, but cannot iterate over them.
5944        So we reject them, it's a bug. */
5945     case SX_FLAG_HASH:
5946         sv = get_lhash(aTHX_ cxt, len, hash_flags, cname);
5947         break;
5948     case SX_HASH:
5949         sv = get_lhash(aTHX_ cxt, len, 0, cname);
5950         break;
5951     default:
5952         CROAK(("Unexpected type %d in retrieve_lobject\n", type));
5953     }
5954
5955     TRACEME(("ok (retrieve_lobject at 0x%" UVxf ")", PTR2UV(sv)));
5956     return sv;
5957 #else
5958     PERL_UNUSED_ARG(cname);
5959
5960     /* previously this (brokenly) checked the length value and only failed if 
5961        the length was over 4G.
5962        Since this op should only occur with objects over 4GB (or 2GB) we can just
5963        reject it.
5964     */
5965     CROAK(("Invalid large object op for this 32bit system"));
5966 #endif
5967 }
5968
5969 /*
5970  * retrieve_netint
5971  *
5972  * Retrieve defined integer in network order.
5973  * Layout is SX_NETINT <data>, whith SX_NETINT already read.
5974  */
5975 static SV *retrieve_netint(pTHX_ stcxt_t *cxt, const char *cname)
5976 {
5977     SV *sv;
5978     HV *stash;
5979     I32 iv;
5980
5981     TRACEME(("retrieve_netint (#%d)", (int)cxt->tagnum));
5982
5983     READ_I32(iv);
5984 #ifdef HAS_NTOHL
5985     sv = newSViv((int) ntohl(iv));
5986     TRACEME(("network integer %d", (int) ntohl(iv)));
5987 #else
5988     sv = newSViv(iv);
5989     TRACEME(("network integer (as-is) %d", iv));
5990 #endif
5991     stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5992     SEEN_NN(sv, stash, 0);      /* Associate this new scalar with tag "tagnum" */
5993
5994     TRACEME(("ok (retrieve_netint at 0x%" UVxf ")", PTR2UV(sv)));
5995
5996     return sv;
5997 }
5998
5999 /*
6000  * retrieve_double
6001  *
6002  * Retrieve defined double.
6003  * Layout is SX_DOUBLE <data>, whith SX_DOUBLE already read.
6004  */
6005 static SV *retrieve_double(pTHX_ stcxt_t *cxt, const char *cname)
6006 {
6007     SV *sv;
6008     HV *stash;
6009     NV nv;
6010
6011     TRACEME(("retrieve_double (#%d)", (int)cxt->tagnum));
6012
6013     READ(&nv, sizeof(nv));
6014     sv = newSVnv(nv);
6015     stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
6016     SEEN_NN(sv, stash, 0);      /* Associate this new scalar with tag "tagnum" */
6017
6018     TRACEME(("double %" NVff, nv));
6019     TRACEME(("ok (retrieve_double at 0x%" UVxf ")", PTR2UV(sv)));
6020
6021     return sv;
6022 }
6023
6024 /*
6025  * retrieve_byte
6026  *
6027  * Retrieve defined byte (small integer within the [-128, +127] range).
6028  * Layout is SX_BYTE <data>, whith SX_BYTE already read.
6029  */
6030 static SV *retrieve_byte(pTHX_ stcxt_t *cxt, const char *cname)
6031 {
6032     SV *sv;
6033     HV *stash;
6034     int siv;
6035 #ifdef _MSC_VER
6036     /* MSVC 2017 doesn't handle the AIX workaround well */
6037     int tmp;
6038 #else
6039     signed char tmp;    /* Workaround for AIX cc bug --H.Merijn Brand */
6040 #endif
6041
6042     TRACEME(("retrieve_byte (#%d)", (int)cxt->tagnum));
6043
6044     GETMARK(siv);
6045     TRACEME(("small integer read as %d", (unsigned char) siv));
6046     tmp = (unsigned char) siv - 128;
6047     sv = newSViv(tmp);
6048     stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
6049     SEEN_NN(sv, stash, 0);      /* Associate this new scalar with tag "tagnum" */
6050
6051     TRACEME(("byte %d", tmp));
6052     TRACEME(("ok (retrieve_byte at 0x%" UVxf ")", PTR2UV(sv)));
6053
6054     return sv;
6055 }
6056
6057 /*
6058  * retrieve_undef
6059  *
6060  * Return the undefined value.
6061  */
6062 static SV *retrieve_undef(pTHX_ stcxt_t *cxt, const char *cname)
6063 {
6064     SV *sv;
6065     HV *stash;
6066
6067     TRACEME(("retrieve_undef"));
6068
6069     sv = newSV(0);
6070     stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
6071     SEEN_NN(sv, stash, 0);
6072
6073     return sv;
6074 }
6075
6076 /*
6077  * retrieve_sv_undef
6078  *
6079  * Return the immortal undefined value.
6080  */
6081 static SV *retrieve_sv_undef(pTHX_ stcxt_t *cxt, const char *cname)
6082 {
6083     SV *sv = &PL_sv_undef;
6084     HV *stash;
6085
6086     TRACEME(("retrieve_sv_undef"));
6087
6088     /* Special case PL_sv_undef, as av_fetch uses it internally to mark
6089        deleted elements, and will return NULL (fetch failed) whenever it
6090        is fetched.  */
6091     if (cxt->where_is_undef == UNSET_NTAG_T) {
6092         cxt->where_is_undef = cxt->tagnum;
6093     }
6094     stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
6095     SEEN_NN(sv, stash, 1);
6096     return sv;
6097 }
6098
6099 /*
6100  * retrieve_sv_yes
6101  *
6102  * Return the immortal yes value.
6103  */
6104 static SV *retrieve_sv_yes(pTHX_ stcxt_t *cxt, const char *cname)
6105 {
6106     SV *sv = &PL_sv_yes;
6107     HV *stash;
6108
6109     TRACEME(("retrieve_sv_yes"));
6110
6111     stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
6112     SEEN_NN(sv, stash, 1);
6113     return sv;
6114 }
6115
6116 /*
6117  * retrieve_sv_no
6118  *
6119  * Return the immortal no value.
6120  */
6121 static SV *retrieve_sv_no(pTHX_ stcxt_t *cxt, const char *cname)
6122 {
6123     SV *sv = &PL_sv_no;
6124     HV *stash;
6125
6126     TRACEME(("retrieve_sv_no"));
6127
6128     stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
6129     SEEN_NN(sv, stash, 1);
6130     return sv;
6131 }
6132
6133 /*
6134  * retrieve_svundef_elem
6135  *
6136  * Return &PL_sv_placeholder, representing &PL_sv_undef in an array.  This
6137  * is a bit of a hack, but we already use SX_SV_UNDEF to mean a nonexistent
6138  * element, for historical reasons.
6139  */
6140 static SV *retrieve_svundef_elem(pTHX_ stcxt_t *cxt, const char *cname)
6141 {
6142     TRACEME(("retrieve_svundef_elem"));
6143
6144     /* SEEN reads the contents of its SV argument, which we are not
6145        supposed to do with &PL_sv_placeholder. */
6146     SEEN_NN(&PL_sv_undef, cname, 1);
6147
6148     return &PL_sv_placeholder;
6149 }
6150
6151 /*
6152  * retrieve_array
6153  *
6154  * Retrieve a whole array.
6155  * Layout is SX_ARRAY <size> followed by each item, in increasing index order.
6156  * Each item is stored as <object>.
6157  *
6158  * When we come here, SX_ARRAY has been read already.
6159  */
6160 static SV *retrieve_array(pTHX_ stcxt_t *cxt, const char *cname)
6161 {
6162     I32 len, i;
6163     AV *av;
6164     SV *sv;
6165     HV *stash;
6166     bool seen_null = FALSE;
6167
6168     TRACEME(("retrieve_array (#%d)", (int)cxt->tagnum));
6169
6170     /*
6171      * Read length, and allocate array, then pre-extend it.
6172      */
6173
6174     RLEN(len);
6175     TRACEME(("size = %d", (int)len));
6176     av = newAV();
6177     stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
6178     SEEN_NN(av, stash, 0); /* Will return if array not allocated nicely */
6179     if (len)
6180         av_extend(av, len);
6181     else
6182         return (SV *) av;       /* No data follow if array is empty */
6183
6184     /*
6185      * Now get each item in turn...
6186      */
6187
6188     for (i = 0; i < len; i++) {
6189         TRACEME(("(#%d) item", (int)i));
6190         sv = retrieve(aTHX_ cxt, 0);    /* Retrieve item */
6191         if (!sv)
6192             return (SV *) 0;
6193         if (sv == &PL_sv_undef) {
6194             seen_null = TRUE;
6195             continue;
6196         }
6197         if (sv == &PL_sv_placeholder)
6198             sv = &PL_sv_undef;
6199         if (av_store(av, i, sv) == 0)
6200             return (SV *) 0;
6201     }
6202     if (seen_null) av_fill(av, len-1);
6203
6204     TRACEME(("ok (retrieve_array at 0x%" UVxf ")", PTR2UV(av)));
6205
6206     return (SV *) av;
6207 }
6208
6209 #ifdef HAS_U64
6210
6211 /* internal method with len already read */
6212
6213 static SV *get_larray(pTHX_ stcxt_t *cxt, UV len, const char *cname)
6214 {
6215     UV i;
6216     AV *av;
6217     SV *sv;
6218     HV *stash;
6219     bool seen_null = FALSE;
6220
6221     TRACEME(("get_larray (#%d) %lu", (int)cxt->tagnum, (unsigned long)len));
6222
6223     /*
6224      * allocate array, then pre-extend it.
6225      */
6226
6227     av = newAV();
6228     stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
6229     SEEN_NN(av, stash, 0); /* Will return if array not allocated nicely */
6230     assert(len);
6231     av_extend(av, len);
6232
6233     /*
6234      * Now get each item in turn...
6235      */
6236
6237     for (i = 0; i < len; i++) {
6238         TRACEME(("(#%d) item", (int)i));
6239         sv = retrieve(aTHX_ cxt, 0);            /* Retrieve item */
6240         if (!sv)
6241             return (SV *) 0;
6242         if (sv == &PL_sv_undef) {
6243             seen_null = TRUE;
6244             continue;
6245         }
6246         if (sv == &PL_sv_placeholder)
6247             sv = &PL_sv_undef;
6248         if (av_store(av, i, sv) == 0)
6249             return (SV *) 0;
6250     }
6251     if (seen_null) av_fill(av, len-1);
6252
6253     TRACEME(("ok (get_larray at 0x%" UVxf ")", PTR2UV(av)));
6254
6255     return (SV *) av;
6256 }
6257
6258 /*
6259  * get_lhash
6260  *
6261  * Retrieve a overlong hash table.
6262  * <len> is already read. What follows is each key/value pair, in random order.
6263  * Keys are stored as <length> <data>, the <data> section being omitted
6264  * if length is 0.
6265  * Values are stored as <object>.
6266  *
6267  */
6268 static SV *get_lhash(pTHX_ stcxt_t *cxt, UV len, int hash_flags, const char *cname)
6269 {
6270     UV size;
6271     UV i;
6272     HV *hv;
6273     SV *sv;
6274     HV *stash;
6275
6276     TRACEME(("get_lhash (#%d)", (int)cxt->tagnum));
6277
6278 #ifdef HAS_RESTRICTED_HASHES
6279     PERL_UNUSED_ARG(hash_flags);
6280 #else        
6281     if (hash_flags & SHV_RESTRICTED) {
6282         if (cxt->derestrict < 0)
6283             cxt->derestrict = (SvTRUE
6284                 (get_sv("Storable::downgrade_restricted", GV_ADD))
6285                                ? 1 : 0);
6286         if (cxt->derestrict == 0)
6287             RESTRICTED_HASH_CROAK();
6288     }
6289 #endif
6290
6291     TRACEME(("size = %lu", (unsigned long)len));
6292     hv = newHV();
6293     stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
6294     SEEN_NN(hv, stash, 0);      /* Will return if table not allocated properly */
6295     if (len == 0)
6296         return (SV *) hv;       /* No data follow if table empty */
6297     TRACEME(("split %lu", (unsigned long)len+1));
6298     hv_ksplit(hv, len+1);       /* pre-extend hash to save multiple splits */
6299
6300     /*
6301      * Now get each key/value pair in turn...
6302      */
6303
6304     for (i = 0; i < len; i++) {
6305         /*
6306          * Get value first.
6307          */
6308
6309         TRACEME(("(#%d) value", (int)i));
6310         sv = retrieve(aTHX_ cxt, 0);
6311         if (!sv)
6312             return (SV *) 0;
6313
6314         /*
6315          * Get key.
6316          * Since we're reading into kbuf, we must ensure we're not
6317          * recursing between the read and the hv_store() where it's used.
6318          * Hence the key comes after the value.
6319          */
6320
6321         RLEN(size);             /* Get key size */
6322         KBUFCHK((STRLEN)size);  /* Grow hash key read pool if needed */
6323         if (size)
6324             READ(kbuf, size);
6325         kbuf[size] = '\0';      /* Mark string end, just in case */
6326         TRACEME(("(#%d) key '%s'", (int)i, kbuf));
6327
6328         /*
6329          * Enter key/value pair into hash table.
6330          */
6331
6332         if (hv_store(hv, kbuf, (U32) size, sv, 0) == 0)
6333             return (SV *) 0;
6334     }
6335
6336     TRACEME(("ok (get_lhash at 0x%" UVxf ")", PTR2UV(hv)));
6337     return (SV *) hv;
6338 }
6339 #endif
6340
6341 /*
6342  * retrieve_hash
6343  *
6344  * Retrieve a whole hash table.
6345  * Layout is SX_HASH <size> followed by each key/value pair, in random order.
6346  * Keys are stored as <length> <data>, the <data> section being omitted
6347  * if length is 0.
6348  * Values are stored as <object>.
6349  *
6350  * When we come here, SX_HASH has been read already.
6351  */
6352 static SV *retrieve_hash(pTHX_ stcxt_t *cxt, const char *cname)
6353 {
6354     I32 len;
6355     I32 size;
6356     I32 i;
6357     HV *hv;
6358     SV *sv;
6359     HV *stash;
6360
6361     TRACEME(("retrieve_hash (#%d)", (int)cxt->tagnum));
6362
6363     /*
6364      * Read length, allocate table.
6365      */
6366
6367     RLEN(len);
6368     TRACEME(("size = %d", (int)len));
6369     hv = newHV();
6370     stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
6371     SEEN_NN(hv, stash, 0);      /* Will return if table not allocated properly */
6372     if (len == 0)
6373         return (SV *) hv;       /* No data follow if table empty */
6374     TRACEME(("split %d", (int)len+1));
6375     hv_ksplit(hv, len+1);       /* pre-extend hash to save multiple splits */
6376
6377     /*
6378      * Now get each key/value pair in turn...
6379      */
6380
6381     for (i = 0; i < len; i++) {
6382         /*
6383          * Get value first.
6384          */
6385
6386         TRACEME(("(#%d) value", (int)i));
6387         sv = retrieve(aTHX_ cxt, 0);
6388         if (!sv)
6389             return (SV *) 0;
6390
6391         /*
6392          * Get key.
6393          * Since we're reading into kbuf, we must ensure we're not
6394          * recursing between the read and the hv_store() where it's used.
6395          * Hence the key comes after the value.
6396          */
6397
6398         RLEN(size);             /* Get key size */
6399         KBUFCHK((STRLEN)size);  /* Grow hash key read pool if needed */
6400         if (size)
6401             READ(kbuf, size);
6402         kbuf[size] = '\0';      /* Mark string end, just in case */
6403         TRACEME(("(#%d) key '%s'", (int)i, kbuf));
6404
6405         /*
6406          * Enter key/value pair into hash table.
6407          */
6408
6409         if (hv_store(hv, kbuf, (U32) size, sv, 0) == 0)
6410             return (SV *) 0;
6411     }
6412
6413     TRACEME(("ok (retrieve_hash at 0x%" UVxf ")", PTR2UV(hv)));
6414
6415     return (SV *) hv;
6416 }
6417
6418 /*
6419  * retrieve_hash
6420  *
6421  * Retrieve a whole hash table.
6422  * Layout is SX_HASH <size> followed by each key/value pair, in random order.
6423  * Keys are stored as <length> <data>, the <data> section being omitted
6424  * if length is 0.
6425  * Values are stored as <object>.
6426  *
6427  * When we come here, SX_HASH has been read already.
6428  */
6429 static SV *retrieve_flag_hash(pTHX_ stcxt_t *cxt, const char *cname)
6430 {
6431     dVAR;
6432     I32 len;
6433     I32 size;
6434     I32 i;
6435     HV *hv;
6436     SV *sv;
6437     HV *stash;
6438     int hash_flags;
6439
6440     GETMARK(hash_flags);
6441     TRACEME(("retrieve_flag_hash (#%d)", (int)cxt->tagnum));
6442     /*
6443      * Read length, allocate table.
6444      */
6445
6446 #ifndef HAS_RESTRICTED_HASHES
6447     if (hash_flags & SHV_RESTRICTED) {
6448         if (cxt->derestrict < 0)
6449             cxt->derestrict = (SvTRUE
6450                 (get_sv("Storable::downgrade_restricted", GV_ADD))
6451                                ? 1 : 0);
6452         if (cxt->derestrict == 0)
6453             RESTRICTED_HASH_CROAK();
6454     }
6455 #endif
6456
6457     RLEN(len);
6458     TRACEME(("size = %d, flags = %d", (int)len, hash_flags));
6459     hv = newHV();
6460     stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
6461     SEEN_NN(hv, stash, 0);      /* Will return if table not allocated properly */
6462     if (len == 0)
6463         return (SV *) hv;       /* No data follow if table empty */
6464     TRACEME(("split %d", (int)len+1));
6465     hv_ksplit(hv, len+1);       /* pre-extend hash to save multiple splits */
6466
6467     /*
6468      * Now get each key/value pair in turn...
6469      */
6470
6471     for (i = 0; i < len; i++) {
6472         int flags;
6473         int store_flags = 0;
6474         /*
6475          * Get value first.
6476          */
6477
6478         TRACEME(("(#%d) value", (int)i));
6479         sv = retrieve(aTHX_ cxt, 0);
6480         if (!sv)
6481             return (SV *) 0;
6482
6483         GETMARK(flags);
6484 #ifdef HAS_RESTRICTED_HASHES
6485         if ((hash_flags & SHV_RESTRICTED) && (flags & SHV_K_LOCKED))
6486             SvREADONLY_on(sv);
6487 #endif
6488
6489         if (flags & SHV_K_ISSV) {
6490             /* XXX you can't set a placeholder with an SV key.
6491                Then again, you can't get an SV key.
6492                Without messing around beyond what the API is supposed to do.
6493             */
6494             SV *keysv;
6495             TRACEME(("(#%d) keysv, flags=%d", (int)i, flags));
6496             keysv = retrieve(aTHX_ cxt, 0);
6497             if (!keysv)
6498                 return (SV *) 0;
6499
6500             if (!hv_store_ent(hv, keysv, sv, 0))
6501                 return (SV *) 0;
6502         } else {
6503             /*
6504              * Get key.
6505              * Since we're reading into kbuf, we must ensure we're not
6506              * recursing between the read and the hv_store() where it's used.
6507              * Hence the key comes after the value.
6508              */
6509
6510             if (flags & SHV_K_PLACEHOLDER) {
6511                 SvREFCNT_dec (sv);
6512                 sv = &PL_sv_placeholder;
6513                 store_flags |= HVhek_PLACEHOLD;
6514             }
6515             if (flags & SHV_K_UTF8) {
6516 #ifdef HAS_UTF8_HASHES
6517                 store_flags |= HVhek_UTF8;
6518 #else
6519                 if (cxt->use_bytes < 0)
6520                     cxt->use_bytes
6521                         = (SvTRUE(get_sv("Storable::drop_utf8", GV_ADD))
6522                            ? 1 : 0);
6523                 if (cxt->use_bytes == 0)
6524                     UTF8_CROAK();
6525 #endif
6526             }
6527 #ifdef HAS_UTF8_HASHES
6528             if (flags & SHV_K_WASUTF8)
6529                 store_flags |= HVhek_WASUTF8;
6530 #endif
6531
6532             RLEN(size);         /* Get key size */
6533             KBUFCHK((STRLEN)size);/* Grow hash key read pool if needed */
6534             if (size)
6535                 READ(kbuf, size);
6536             kbuf[size] = '\0';  /* Mark string end, just in case */
6537             TRACEME(("(#%d) key '%s' flags %X store_flags %X", (int)i, kbuf,
6538                      flags, store_flags));
6539
6540             /*
6541              * Enter key/value pair into hash table.
6542              */
6543
6544 #ifdef HAS_RESTRICTED_HASHES
6545             if (hv_store_flags(hv, kbuf, size, sv, 0, store_flags) == 0)
6546                 return (SV *) 0;
6547 #else
6548             if (!(store_flags & HVhek_PLACEHOLD))
6549                 if (hv_store(hv, kbuf, size, sv, 0) == 0)
6550                     return (SV *) 0;
6551 #endif
6552         }
6553     }
6554 #ifdef HAS_RESTRICTED_HASHES
6555     if (hash_flags & SHV_RESTRICTED)
6556         SvREADONLY_on(hv);
6557 #endif
6558
6559     TRACEME(("ok (retrieve_hash at 0x%" UVxf ")", PTR2UV(hv)));
6560
6561     return (SV *) hv;
6562 }
6563
6564 /*
6565  * retrieve_code
6566  *
6567  * Return a code reference.
6568  */
6569 static SV *retrieve_code(pTHX_ stcxt_t *cxt, const char *cname)
6570 {
6571     dSP;
6572     I32 type, count;
6573     IV tagnum;
6574     SV *cv;
6575     SV *sv, *text, *sub, *errsv;
6576     HV *stash;
6577
6578     TRACEME(("retrieve_code (#%d)", (int)cxt->tagnum));
6579
6580     /*
6581      *  Insert dummy SV in the aseen array so that we don't screw
6582      *  up the tag numbers.  We would just make the internal
6583      *  scalar an untagged item in the stream, but
6584      *  retrieve_scalar() calls SEEN().  So we just increase the
6585      *  tag number.
6586      */
6587     tagnum = cxt->tagnum;
6588     sv = newSViv(0);
6589     stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
6590     SEEN_NN(sv, stash, 0);
6591
6592     /*
6593      * Retrieve the source of the code reference
6594      * as a small or large scalar
6595      */
6596
6597     GETMARK(type);
6598     switch (type) {
6599     case SX_SCALAR:
6600         text = retrieve_scalar(aTHX_ cxt, cname);
6601         break;
6602     case SX_LSCALAR:
6603         text = retrieve_lscalar(aTHX_ cxt, cname);
6604         break;
6605     case SX_UTF8STR:
6606         text = retrieve_utf8str(aTHX_ cxt, cname);
6607         break;
6608     case SX_LUTF8STR:
6609         text = retrieve_lutf8str(aTHX_ cxt, cname);
6610         break;
6611     default:
6612         CROAK(("Unexpected type %d in retrieve_code\n", (int)type));
6613     }
6614
6615     if (!text) {
6616         CROAK(("Unable to retrieve code\n"));
6617     }
6618
6619     /*
6620      * prepend "sub " to the source
6621      */
6622
6623     sub = newSVpvs("sub ");
6624     if (SvUTF8(text))
6625         SvUTF8_on(sub);
6626     sv_catpv(sub, SvPV_nolen(text)); /* XXX no sv_catsv! */
6627     SvREFCNT_dec(text);
6628
6629     /*
6630      * evaluate the source to a code reference and use the CV value
6631      */
6632
6633     if (cxt->eval == NULL) {
6634         cxt->eval = get_sv("Storable::Eval", GV_ADD);
6635         SvREFCNT_inc(cxt->eval);
6636     }
6637     if (!SvTRUE(cxt->eval)) {
6638         if (cxt->forgive_me == 0 ||
6639             (cxt->forgive_me < 0 &&
6640              !(cxt->forgive_me = SvTRUE
6641                (get_sv("Storable::forgive_me", GV_ADD)) ? 1 : 0))
6642             ) {
6643             CROAK(("Can't eval, please set $Storable::Eval to a true value"));
6644         } else {
6645             sv = newSVsv(sub);
6646             /* fix up the dummy entry... */
6647             av_store(cxt->aseen, tagnum, SvREFCNT_inc(sv));
6648             return sv;
6649         }
6650     }
6651
6652     ENTER;
6653     SAVETMPS;
6654
6655     errsv = get_sv("@", GV_ADD);
6656     SvPVCLEAR(errsv);   /* clear $@ */
6657     if (SvROK(cxt->eval) && SvTYPE(SvRV(cxt->eval)) == SVt_PVCV) {
6658         PUSHMARK(sp);
6659         XPUSHs(sv_2mortal(newSVsv(sub)));
6660         PUTBACK;
6661         count = call_sv(cxt->eval, G_SCALAR);
6662         if (count != 1)
6663             CROAK(("Unexpected return value from $Storable::Eval callback\n"));
6664     } else {
6665         eval_sv(sub, G_SCALAR);
6666     }
6667     SPAGAIN;
6668     cv = POPs;
6669     PUTBACK;
6670
6671     if (SvTRUE(errsv)) {
6672         CROAK(("code %s caused an error: %s",
6673                SvPV_nolen(sub), SvPV_nolen(errsv)));
6674     }
6675
6676     if (cv && SvROK(cv) && SvTYPE(SvRV(cv)) == SVt_PVCV) {
6677         sv = SvRV(cv);
6678     } else {
6679         CROAK(("code %s did not evaluate to a subroutine reference\n",
6680                SvPV_nolen(sub)));
6681     }
6682
6683     SvREFCNT_inc(sv); /* XXX seems to be necessary */
6684     SvREFCNT_dec(sub);
6685
6686     FREETMPS;
6687     LEAVE;
6688     /* fix up the dummy entry... */
6689     av_store(cxt->aseen, tagnum, SvREFCNT_inc(sv));
6690
6691     return sv;
6692 }
6693
6694 static SV *retrieve_regexp(pTHX_ stcxt_t *cxt, const char *cname) {
6695 #if PERL_VERSION_GE(5,8,0)
6696     int op_flags;
6697     U32 re_len;
6698     STRLEN flags_len;
6699     SV *re;
6700     SV *flags;
6701     SV *re_ref;
6702     SV *sv;
6703     dSP;
6704     I32 count;
6705     HV *stash;
6706
6707     ENTER;
6708     SAVETMPS;
6709
6710     GETMARK(op_flags);
6711     if (op_flags & SHR_U32_RE_LEN) {
6712         RLEN(re_len);
6713     }
6714     else
6715         GETMARK(re_len);
6716
6717     re = sv_2mortal(NEWSV(10002, re_len ? re_len : 1));
6718     READ(SvPVX(re), re_len);
6719     SvCUR_set(re, re_len);
6720     *SvEND(re) = '\0';
6721     SvPOK_only(re);
6722
6723     GETMARK(flags_len);
6724     flags = sv_2mortal(NEWSV(10002, flags_len ? flags_len : 1));
6725     READ(SvPVX(flags), flags_len);
6726     SvCUR_set(flags, flags_len);
6727     *SvEND(flags) = '\0';
6728     SvPOK_only(flags);
6729
6730     PUSHMARK(SP);
6731
6732     XPUSHs(re);
6733     XPUSHs(flags);
6734
6735     PUTBACK;
6736
6737     count = call_pv("Storable::_make_re", G_SCALAR);
6738
6739     SPAGAIN;
6740
6741     if (count != 1)
6742         CROAK(("Bad count %d calling _make_re", (int)count));
6743
6744     re_ref = POPs;
6745
6746     PUTBACK;
6747
6748     if (!SvROK(re_ref))
6749       CROAK(("_make_re didn't return a reference"));
6750
6751     sv = SvRV(re_ref);
6752     SvREFCNT_inc(sv);
6753     stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
6754     SEEN_NN(sv, stash, 0);
6755     
6756     FREETMPS;
6757     LEAVE;
6758
6759     return sv;
6760 #else
6761     CROAK(("retrieve_regexp does not work with 5.6 or earlier"));
6762 #endif
6763 }
6764
6765 /*
6766  * old_retrieve_array
6767  *
6768  * Retrieve a whole array in pre-0.6 binary format.
6769  *
6770  * Layout is SX_ARRAY <size> followed by each item, in increasing index order.
6771  * Each item is stored as SX_ITEM <object> or SX_IT_UNDEF for "holes".
6772  *
6773  * When we come here, SX_ARRAY has been read already.
6774  */
6775 static SV *old_retrieve_array(pTHX_ stcxt_t *cxt, const char *cname)
6776 {
6777     I32 len;
6778     I32 i;
6779     AV *av;
6780     SV *sv;
6781     int c;
6782
6783     PERL_UNUSED_ARG(cname);
6784     TRACEME(("old_retrieve_array (#%d)", (int)cxt->tagnum));
6785
6786     /*
6787      * Read length, and allocate array, then pre-extend it.
6788      */
6789
6790     RLEN(len);
6791     TRACEME(("size = %d", (int)len));
6792     av = newAV();
6793     SEEN0_NN(av, 0);    /* Will return if array not allocated nicely */
6794     if (len)
6795         av_extend(av, len);
6796     else
6797         return (SV *) av;       /* No data follow if array is empty */
6798
6799     /*
6800      * Now get each item in turn...
6801      */
6802
6803     for (i = 0; i < len; i++) {
6804         GETMARK(c);
6805         if (c == SX_IT_UNDEF) {
6806             TRACEME(("(#%d) undef item", (int)i));
6807             continue;           /* av_extend() already filled us with undef */
6808         }
6809         if (c != SX_ITEM)
6810             (void) retrieve_other(aTHX_ cxt, 0);/* Will croak out */
6811         TRACEME(("(#%d) item", (int)i));
6812         sv = retrieve(aTHX_ cxt, 0);            /* Retrieve item */
6813         if (!sv)
6814             return (SV *) 0;
6815         if (av_store(av, i, sv) == 0)
6816             return (SV *) 0;
6817     }
6818
6819     TRACEME(("ok (old_retrieve_array at 0x%" UVxf ")", PTR2UV(av)));
6820
6821     return (SV *) av;
6822 }
6823
6824 /*
6825  * old_retrieve_hash
6826  *
6827  * Retrieve a whole hash table in pre-0.6 binary format.
6828  *
6829  * Layout is SX_HASH <size> followed by each key/value pair, in random order.
6830  * Keys are stored as SX_KEY <length> <data>, the <data> section being omitted
6831  * if length is 0.
6832  * Values are stored as SX_VALUE <object> or SX_VL_UNDEF for "holes".
6833  *
6834  * When we come here, SX_HASH has been read already.
6835  */
6836 static SV *old_retrieve_hash(pTHX_ stcxt_t *cxt, const char *cname)
6837 {
6838     I32 len;
6839     I32 size;
6840     I32 i;
6841     HV *hv;
6842     SV *sv = (SV *) 0;
6843     int c;
6844     SV *sv_h_undef = (SV *) 0;  /* hv_store() bug */
6845
6846     PERL_UNUSED_ARG(cname);
6847     TRACEME(("old_retrieve_hash (#%d)", (int)cxt->tagnum));
6848
6849     /*
6850      * Read length, allocate table.
6851      */
6852
6853     RLEN(len);
6854     TRACEME(("size = %d", (int)len));
6855     hv = newHV();
6856     SEEN0_NN(hv, 0);            /* Will return if table not allocated properly */
6857     if (len == 0)
6858         return (SV *) hv;       /* No data follow if table empty */
6859     TRACEME(("split %d", (int)len+1));
6860     hv_ksplit(hv, len+1);       /* pre-extend hash to save multiple splits */
6861
6862     /*
6863      * Now get each key/value pair in turn...
6864      */
6865
6866     for (i = 0; i < len; i++) {
6867         /*
6868          * Get value first.
6869          */
6870
6871         GETMARK(c);
6872         if (c == SX_VL_UNDEF) {
6873             TRACEME(("(#%d) undef value", (int)i));
6874             /*
6875              * Due to a bug in hv_store(), it's not possible to pass
6876              * &PL_sv_undef to hv_store() as a value, otherwise the
6877              * associated key will not be creatable any more. -- RAM, 14/01/97
6878              */
6879             if (!sv_h_undef)
6880                 sv_h_undef = newSVsv(&PL_sv_undef);
6881             sv = SvREFCNT_inc(sv_h_undef);
6882         } else if (c == SX_VALUE) {
6883             TRACEME(("(#%d) value", (int)i));
6884             sv = retrieve(aTHX_ cxt, 0);
6885             if (!sv)
6886                 return (SV *) 0;
6887         } else
6888             (void) retrieve_other(aTHX_ cxt, 0); /* Will croak out */
6889
6890         /*
6891          * Get key.
6892          * Since we're reading into kbuf, we must ensure we're not
6893          * recursing between the read and the hv_store() where it's used.
6894          * Hence the key comes after the value.
6895          */
6896
6897         GETMARK(c);
6898         if (c != SX_KEY)
6899             (void) retrieve_other(aTHX_ cxt, 0); /* Will croak out */
6900         RLEN(size);                             /* Get key size */
6901         KBUFCHK((STRLEN)size);                  /* Grow hash key read pool if needed */
6902         if (size)
6903             READ(kbuf, size);
6904         kbuf[size] = '\0';                      /* Mark string end, just in case */
6905         TRACEME(("(#%d) key '%s'", (int)i, kbuf));
6906
6907         /*
6908          * Enter key/value pair into hash table.
6909          */
6910
6911         if (hv_store(hv, kbuf, (U32) size, sv, 0) == 0)
6912             return (SV *) 0;
6913     }
6914
6915     TRACEME(("ok (retrieve_hash at 0x%" UVxf ")", PTR2UV(hv)));
6916
6917     return (SV *) hv;
6918 }
6919
6920 /***
6921  *** Retrieval engine.
6922  ***/
6923
6924 /*
6925  * magic_check
6926  *
6927  * Make sure the stored data we're trying to retrieve has been produced
6928  * on an ILP compatible system with the same byteorder. It croaks out in
6929  * case an error is detected. [ILP = integer-long-pointer sizes]
6930  * Returns null if error is detected, &PL_sv_undef otherwise.
6931  *
6932  * Note that there's no byte ordering info emitted when network order was
6933  * used at store time.
6934  */
6935 static SV *magic_check(pTHX_ stcxt_t *cxt)
6936 {
6937     /* The worst case for a malicious header would be old magic (which is
6938        longer), major, minor, byteorder length byte of 255, 255 bytes of
6939        garbage, sizeof int, long, pointer, NV.
6940        So the worse of that we can read is 255 bytes of garbage plus 4.
6941        Err, I am assuming 8 bit bytes here. Please file a bug report if you're
6942        compiling perl on a system with chars that are larger than 8 bits.
6943        (Even Crays aren't *that* perverse).
6944     */
6945     unsigned char buf[4 + 255];
6946     unsigned char *current;
6947     int c;
6948     int length;
6949     int use_network_order;
6950     int use_NV_size;
6951     int old_magic = 0;
6952     int version_major;
6953     int version_minor = 0;
6954
6955     TRACEME(("magic_check"));
6956
6957     /*
6958      * The "magic number" is only for files, not when freezing in memory.
6959      */
6960
6961     if (cxt->fio) {
6962         /* This includes the '\0' at the end.  I want to read the extra byte,
6963            which is usually going to be the major version number.  */
6964         STRLEN len = sizeof(magicstr);
6965         STRLEN old_len;
6966
6967         READ(buf, (SSize_t)(len));      /* Not null-terminated */
6968
6969         /* Point at the byte after the byte we read.  */
6970         current = buf + --len;  /* Do the -- outside of macros.  */
6971
6972         if (memNE(buf, magicstr, len)) {
6973             /*
6974              * Try to read more bytes to check for the old magic number, which
6975              * was longer.
6976              */
6977
6978             TRACEME(("trying for old magic number"));
6979
6980             old_len = sizeof(old_magicstr) - 1;
6981             READ(current + 1, (SSize_t)(old_len - len));
6982
6983             if (memNE(buf, old_magicstr, old_len))
6984                 CROAK(("File is not a perl storable"));
6985             old_magic++;
6986             current = buf + old_len;
6987         }
6988         use_network_order = *current;
6989     } else {
6990         GETMARK(use_network_order);
6991     }
6992
6993     /*
6994      * Starting with 0.6, the "use_network_order" byte flag is also used to
6995      * indicate the version number of the binary, and therefore governs the
6996      * setting of sv_retrieve_vtbl. See magic_write().
6997      */
6998     if (old_magic && use_network_order > 1) {
6999         /*  0.1 dump - use_network_order is really byte order length */
7000         version_major = -1;
7001     }
7002     else {
7003         version_major = use_network_order >> 1;
7004     }
7005     cxt->retrieve_vtbl = (SV*(**)(pTHX_ stcxt_t *cxt, const char *cname)) (version_major > 0 ? sv_retrieve : sv_old_retrieve);
7006
7007     TRACEME(("magic_check: netorder = 0x%x", use_network_order));
7008
7009
7010     /*
7011      * Starting with 0.7 (binary major 2), a full byte is dedicated to the
7012      * minor version of the protocol.  See magic_write().
7013      */
7014
7015     if (version_major > 1)
7016         GETMARK(version_minor);
7017
7018     cxt->ver_major = version_major;
7019     cxt->ver_minor = version_minor;
7020
7021     TRACEME(("binary image version is %d.%d", version_major, version_minor));
7022
7023     /*
7024      * Inter-operability sanity check: we can't retrieve something stored
7025      * using a format more recent than ours, because we have no way to
7026      * know what has changed, and letting retrieval go would mean a probable
7027      * failure reporting a "corrupted" storable file.
7028      */
7029
7030     if (
7031         version_major > STORABLE_BIN_MAJOR ||
7032         (version_major == STORABLE_BIN_MAJOR &&
7033          version_minor > STORABLE_BIN_MINOR)
7034         ) {
7035         int croak_now = 1;
7036         TRACEME(("but I am version is %d.%d", STORABLE_BIN_MAJOR,
7037                  STORABLE_BIN_MINOR));
7038
7039         if (version_major == STORABLE_BIN_MAJOR) {
7040             TRACEME(("cxt->accept_future_minor is %d",
7041                      cxt->accept_future_minor));
7042             if (cxt->accept_future_minor < 0)
7043                 cxt->accept_future_minor
7044                     = (SvTRUE(get_sv("Storable::accept_future_minor",
7045                                           GV_ADD))
7046                        ? 1 : 0);
7047             if (cxt->accept_future_minor == 1)
7048                 croak_now = 0;  /* Don't croak yet.  */
7049         }
7050         if (croak_now) {
7051             CROAK(("Storable binary image v%d.%d more recent than I am (v%d.%d)",
7052                    version_major, version_minor,
7053                    STORABLE_BIN_MAJOR, STORABLE_BIN_MINOR));
7054         }
7055     }
7056
7057     /*
7058      * If they stored using network order, there's no byte ordering
7059      * information to check.
7060      */
7061
7062     if ((cxt->netorder = (use_network_order & 0x1)))    /* Extra () for -Wall */
7063         return &PL_sv_undef;                    /* No byte ordering info */
7064
7065     /* In C truth is 1, falsehood is 0. Very convenient.  */
7066     use_NV_size = version_major >= 2 && version_minor >= 2;
7067
7068     if (version_major >= 0) {
7069         GETMARK(c);
7070     }
7071     else {
7072         c = use_network_order;
7073     }
7074     length = c + 3 + use_NV_size;
7075     READ(buf, length);  /* Not null-terminated */
7076
7077     TRACEME(("byte order '%.*s' %d", c, buf, c));
7078
7079 #ifdef USE_56_INTERWORK_KLUDGE
7080     /* No point in caching this in the context as we only need it once per
7081        retrieve, and we need to recheck it each read.  */
7082     if (SvTRUE(get_sv("Storable::interwork_56_64bit", GV_ADD))) {
7083         if ((c != (sizeof (byteorderstr_56) - 1))
7084             || memNE(buf, byteorderstr_56, c))
7085             CROAK(("Byte order is not compatible"));
7086     } else
7087 #endif
7088     {
7089         if ((c != (sizeof (byteorderstr) - 1))
7090           || memNE(buf, byteorderstr, c))
7091             CROAK(("Byte order is not compatible"));
7092     }
7093
7094     current = buf + c;
7095
7096     /* sizeof(int) */
7097     if ((int) *current++ != sizeof(int))
7098         CROAK(("Integer size is not compatible"));
7099
7100     /* sizeof(long) */
7101     if ((int) *current++ != sizeof(long))
7102         CROAK(("Long integer size is not compatible"));
7103
7104     /* sizeof(char *) */
7105     if ((int) *current != sizeof(char *))
7106         CROAK(("Pointer size is not compatible"));
7107
7108     if (use_NV_size) {
7109         /* sizeof(NV) */
7110         if ((int) *++current != sizeof(NV))
7111             CROAK(("Double size is not compatible"));
7112     }
7113
7114     return &PL_sv_undef;        /* OK */
7115 }
7116
7117 /*
7118  * retrieve
7119  *
7120  * Recursively retrieve objects from the specified file and return their
7121  * root SV (which may be an AV or an HV for what we care).
7122  * Returns null if there is a problem.
7123  */
7124 static SV *retrieve(pTHX_ stcxt_t *cxt, const char *cname)
7125 {
7126     int type;
7127     SV **svh;
7128     SV *sv;
7129
7130     TRACEME(("retrieve"));
7131
7132     /*
7133      * Grab address tag which identifies the object if we are retrieving
7134      * an older format. Since the new binary format counts objects and no
7135      * longer explicitly tags them, we must keep track of the correspondence
7136      * ourselves.
7137      *
7138      * The following section will disappear one day when the old format is
7139      * no longer supported, hence the final "goto" in the "if" block.
7140      */
7141
7142     if (cxt->hseen) {                   /* Retrieving old binary */
7143         stag_t tag;
7144         if (cxt->netorder) {
7145             I32 nettag;
7146             READ(&nettag, sizeof(I32)); /* Ordered sequence of I32 */
7147             tag = (stag_t) nettag;
7148         } else
7149             READ(&tag, sizeof(stag_t)); /* Original address of the SV */
7150
7151         GETMARK(type);
7152         if (type == SX_OBJECT) {
7153             I32 tagn;
7154             svh = hv_fetch(cxt->hseen, (char *) &tag, sizeof(tag), FALSE);
7155             if (!svh)
7156                 CROAK(("Old tag 0x%" UVxf " should have been mapped already",
7157                        (UV) tag));
7158             tagn = SvIV(*svh);  /* Mapped tag number computed earlier below */
7159
7160             /*
7161              * The following code is common with the SX_OBJECT case below.
7162              */
7163
7164             svh = av_fetch(cxt->aseen, tagn, FALSE);
7165             if (!svh)
7166                 CROAK(("Object #%" IVdf " should have been retrieved already",
7167                        (IV) tagn));
7168             sv = *svh;
7169             TRACEME(("has retrieved #%d at 0x%" UVxf, (int)tagn, PTR2UV(sv)));
7170             SvREFCNT_inc(sv);   /* One more reference to this same sv */
7171             return sv;          /* The SV pointer where object was retrieved */
7172         }
7173
7174         /*
7175          * Map new object, but don't increase tagnum. This will be done
7176          * by each of the retrieve_* functions when they call SEEN().
7177          *
7178          * The mapping associates the "tag" initially present with a unique
7179          * tag number. See test for SX_OBJECT above to see how this is perused.
7180          */
7181
7182         if (!hv_store(cxt->hseen, (char *) &tag, sizeof(tag),
7183                       newSViv(cxt->tagnum), 0))
7184             return (SV *) 0;
7185
7186         goto first_time;
7187     }
7188
7189     /*
7190      * Regular post-0.6 binary format.
7191      */
7192
7193     GETMARK(type);
7194
7195     TRACEME(("retrieve type = %d", type));
7196
7197     /*
7198      * Are we dealing with an object we should have already retrieved?
7199      */
7200
7201     if (type == SX_OBJECT) {
7202         I32 tag;
7203         READ_I32(tag);
7204         tag = ntohl(tag);
7205 #ifndef HAS_U64
7206         /* A 32-bit system can't have over 2**31 objects anyway */
7207         if (tag < 0)
7208             CROAK(("Object #%" IVdf " out of range", (IV)tag));
7209 #endif
7210         /* Older versions of Storable on with 64-bit support on 64-bit
7211            systems can produce values above the 2G boundary (or wrapped above
7212            the 4G boundary, which we can't do much about), treat those as
7213            unsigned.
7214            This same commit stores tag ids over the 2G boundary as long tags
7215            since older Storables will mis-handle them as short tags.
7216          */
7217         svh = av_fetch(cxt->aseen, (U32)tag, FALSE);
7218         if (!svh)
7219             CROAK(("Object #%" IVdf " should have been retrieved already",
7220                    (IV) tag));
7221         sv = *svh;
7222         TRACEME(("had retrieved #%d at 0x%" UVxf, (int)tag, PTR2UV(sv)));
7223         SvREFCNT_inc(sv);       /* One more reference to this same sv */
7224         return sv;              /* The SV pointer where object was retrieved */
7225     } else if (type >= SX_LAST && cxt->ver_minor > STORABLE_BIN_MINOR) {
7226         if (cxt->accept_future_minor < 0)
7227             cxt->accept_future_minor
7228                 = (SvTRUE(get_sv("Storable::accept_future_minor",
7229                                       GV_ADD))
7230                    ? 1 : 0);
7231         if (cxt->accept_future_minor == 1) {
7232             CROAK(("Storable binary image v%d.%d contains data of type %d. "
7233                    "This Storable is v%d.%d and can only handle data types up to %d",
7234                    cxt->ver_major, cxt->ver_minor, type,
7235                    STORABLE_BIN_MAJOR, STORABLE_BIN_MINOR, SX_LAST - 1));
7236         }
7237     }
7238
7239  first_time:    /* Will disappear when support for old format is dropped */
7240
7241     /*
7242      * Okay, first time through for this one.
7243      */
7244
7245     sv = RETRIEVE(cxt, type)(aTHX_ cxt, cname);
7246     if (!sv)
7247         return (SV *) 0;                /* Failed */
7248
7249     /*
7250      * Old binary formats (pre-0.7).
7251      *
7252      * Final notifications, ended by SX_STORED may now follow.
7253      * Currently, the only pertinent notification to apply on the
7254      * freshly retrieved object is either:
7255      *    SX_CLASS <char-len> <classname> for short classnames.
7256      *    SX_LG_CLASS <int-len> <classname> for larger one (rare!).
7257      * Class name is then read into the key buffer pool used by
7258      * hash table key retrieval.
7259      */
7260
7261     if (cxt->ver_major < 2) {
7262         while ((type = GETCHAR()) != SX_STORED) {
7263             I32 len;
7264             HV* stash;
7265             switch (type) {
7266             case SX_CLASS:
7267                 GETMARK(len);           /* Length coded on a single char */
7268                 break;
7269             case SX_LG_CLASS:           /* Length coded on a regular integer */
7270                 RLEN(len);
7271                 break;
7272             case EOF:
7273             default:
7274                 return (SV *) 0;        /* Failed */
7275             }
7276             KBUFCHK((STRLEN)len);       /* Grow buffer as necessary */
7277             if (len)
7278                 READ(kbuf, len);
7279             kbuf[len] = '\0';           /* Mark string end */
7280             stash = gv_stashpvn(kbuf, len, GV_ADD);
7281             BLESS(sv, stash);
7282         }
7283     }
7284
7285     TRACEME(("ok (retrieved 0x%" UVxf ", refcnt=%d, %s)", PTR2UV(sv),
7286              (int)SvREFCNT(sv) - 1, sv_reftype(sv, FALSE)));
7287
7288     return sv;  /* Ok */
7289 }
7290
7291 /*
7292  * do_retrieve
7293  *
7294  * Retrieve data held in file and return the root object.
7295  * Common routine for pretrieve and mretrieve.
7296  */
7297 static SV *do_retrieve(
7298                        pTHX_
7299                        PerlIO *f,
7300                        SV *in,
7301                        int optype,
7302                        int flags)
7303 {
7304     dSTCXT;
7305     SV *sv;
7306     int is_tainted;             /* Is input source tainted? */
7307     int pre_06_fmt = 0;         /* True with pre Storable 0.6 formats */
7308
7309     TRACEMED(("do_retrieve (optype = 0x%x, flags=0x%x)",
7310              (unsigned)optype, (unsigned)flags));
7311
7312     optype |= ST_RETRIEVE;
7313     cxt->flags = flags;
7314
7315     /*
7316      * Sanity assertions for retrieve dispatch tables.
7317      */
7318
7319     ASSERT(sizeof(sv_old_retrieve) == sizeof(sv_retrieve),
7320            ("old and new retrieve dispatch table have same size"));
7321     ASSERT(sv_old_retrieve[(int)SX_LAST] == retrieve_other,
7322            ("SX_LAST entry correctly initialized in old dispatch table"));
7323     ASSERT(sv_retrieve[(int)SX_LAST] == retrieve_other,
7324            ("SX_LAST entry correctly initialized in new dispatch table"));
7325
7326     /*
7327      * Workaround for CROAK leak: if they enter with a "dirty" context,
7328      * free up memory for them now.
7329      */
7330
7331     assert(cxt);
7332     if (cxt->s_dirty)
7333         clean_context(aTHX_ cxt);
7334
7335     /*
7336      * Now that STORABLE_xxx hooks exist, it is possible that they try to
7337      * re-enter retrieve() via the hooks.
7338      */
7339
7340     if (cxt->entry) {
7341         cxt = allocate_context(aTHX_ cxt);
7342         cxt->flags = flags;
7343     }
7344     INIT_TRACEME;
7345
7346     cxt->entry++;
7347
7348     ASSERT(cxt->entry == 1, ("starting new recursion"));
7349     ASSERT(!cxt->s_dirty, ("clean context"));
7350
7351     /*
7352      * Prepare context.
7353      *
7354      * Data is loaded into the memory buffer when f is NULL, unless 'in' is
7355      * also NULL, in which case we're expecting the data to already lie
7356      * in the buffer (dclone case).
7357      */
7358
7359     KBUFINIT();                  /* Allocate hash key reading pool once */
7360
7361     if (!f && in) {
7362 #ifdef SvUTF8_on
7363         if (SvUTF8(in)) {
7364             STRLEN length;
7365             const char *orig = SvPV(in, length);
7366             char *asbytes;
7367             /* This is quite deliberate. I want the UTF8 routines
7368                to encounter the '\0' which perl adds at the end
7369                of all scalars, so that any new string also has
7370                this.
7371             */
7372             STRLEN klen_tmp = length + 1;
7373             bool is_utf8 = TRUE;
7374
7375             /* Just casting the &klen to (STRLEN) won't work
7376                well if STRLEN and I32 are of different widths.
7377                --jhi */
7378             asbytes = (char*)bytes_from_utf8((U8*)orig,
7379                                              &klen_tmp,
7380                                              &is_utf8);
7381             if (is_utf8) {
7382                 CROAK(("Frozen string corrupt - contains characters outside 0-255"));
7383             }
7384             if (asbytes != orig) {
7385                 /* String has been converted.
7386                    There is no need to keep any reference to
7387                    the old string.  */
7388                 in = sv_newmortal();
7389                 /* We donate the SV the malloc()ed string
7390                    bytes_from_utf8 returned us.  */
7391                 SvUPGRADE(in, SVt_PV);
7392                 SvPOK_on(in);
7393                 SvPV_set(in, asbytes);
7394                 SvLEN_set(in, klen_tmp);
7395                 SvCUR_set(in, klen_tmp - 1);
7396             }
7397         }
7398 #endif
7399         MBUF_SAVE_AND_LOAD(in);
7400     }
7401
7402     /*
7403      * Magic number verifications.
7404      *
7405      * This needs to be done before calling init_retrieve_context()
7406      * since the format indication in the file are necessary to conduct
7407      * some of the initializations.
7408      */
7409
7410     cxt->fio = f;                       /* Where I/O are performed */
7411
7412     if (!magic_check(aTHX_ cxt))
7413         CROAK(("Magic number checking on storable %s failed",
7414                cxt->fio ? "file" : "string"));
7415
7416     TRACEME(("data stored in %s format",
7417              cxt->netorder ? "net order" : "native"));
7418
7419     /*
7420      * Check whether input source is tainted, so that we don't wrongly
7421      * taint perfectly good values...
7422      *
7423      * We assume file input is always tainted.  If both 'f' and 'in' are
7424      * NULL, then we come from dclone, and tainted is already filled in
7425      * the context.  That's a kludge, but the whole dclone() thing is
7426      * already quite a kludge anyway! -- RAM, 15/09/2000.
7427      */
7428
7429     is_tainted = f ? 1 : (in ? SvTAINTED(in) : cxt->s_tainted);
7430     TRACEME(("input source is %s", is_tainted ? "tainted" : "trusted"));
7431     init_retrieve_context(aTHX_ cxt, optype, is_tainted);
7432
7433     ASSERT(is_retrieving(aTHX), ("within retrieve operation"));
7434
7435     sv = retrieve(aTHX_ cxt, 0); /* Recursively retrieve object, get root SV */
7436
7437     /*
7438      * Final cleanup.
7439      */
7440
7441     if (!f && in)
7442         MBUF_RESTORE();
7443
7444     pre_06_fmt = cxt->hseen != NULL;    /* Before we clean context */
7445
7446     /*
7447      * The "root" context is never freed.
7448      */
7449
7450     clean_retrieve_context(aTHX_ cxt);
7451     if (cxt->prev)                      /* This context was stacked */
7452         free_context(aTHX_ cxt);        /* It was not the "root" context */
7453
7454     /*
7455      * Prepare returned value.
7456      */
7457
7458     if (!sv) {
7459         TRACEMED(("retrieve ERROR"));
7460         return &PL_sv_undef;            /* Something went wrong, return undef */
7461     }
7462
7463     TRACEMED(("retrieve got %s(0x%" UVxf ")",
7464              sv_reftype(sv, FALSE), PTR2UV(sv)));
7465
7466     /*
7467      * Backward compatibility with Storable-0.5@9 (which we know we
7468      * are retrieving if hseen is non-null): don't create an extra RV
7469      * for objects since we special-cased it at store time.
7470      *
7471      * Build a reference to the SV returned by pretrieve even if it is
7472      * already one and not a scalar, for consistency reasons.
7473      */
7474
7475     if (pre_06_fmt) {                   /* Was not handling overloading by then */
7476         SV *rv;
7477         TRACEMED(("fixing for old formats -- pre 0.6"));
7478         if (sv_type(aTHX_ sv) == svis_REF && (rv = SvRV(sv)) && SvOBJECT(rv)) {
7479             TRACEME(("ended do_retrieve() with an object -- pre 0.6"));
7480             return sv;
7481         }
7482     }
7483
7484     /*
7485      * If reference is overloaded, restore behaviour.
7486      *
7487      * NB: minor glitch here: normally, overloaded refs are stored specially
7488      * so that we can croak when behaviour cannot be re-installed, and also
7489      * avoid testing for overloading magic at each reference retrieval.
7490      *
7491      * Unfortunately, the root reference is implicitly stored, so we must
7492      * check for possible overloading now.  Furthermore, if we don't restore
7493      * overloading, we cannot croak as if the original ref was, because we
7494      * have no way to determine whether it was an overloaded ref or not in
7495      * the first place.
7496      *
7497      * It's a pity that overloading magic is attached to the rv, and not to
7498      * the underlying sv as blessing is.
7499      */
7500
7501     if (SvOBJECT(sv)) {
7502         HV *stash = (HV *) SvSTASH(sv);
7503         SV *rv = newRV_noinc(sv);
7504         if (stash && Gv_AMG(stash)) {
7505             SvAMAGIC_on(rv);
7506             TRACEMED(("restored overloading on root reference"));
7507         }
7508         TRACEMED(("ended do_retrieve() with an object"));
7509         return rv;
7510     }
7511
7512     TRACEMED(("regular do_retrieve() end"));
7513
7514     return newRV_noinc(sv);
7515 }
7516
7517 /*
7518  * pretrieve
7519  *
7520  * Retrieve data held in file and return the root object, undef on error.
7521  */
7522 static SV *pretrieve(pTHX_ PerlIO *f, IV flag)
7523 {
7524     TRACEMED(("pretrieve"));
7525     return do_retrieve(aTHX_ f, Nullsv, 0, (int)flag);
7526 }
7527
7528 /*
7529  * mretrieve
7530  *
7531  * Retrieve data held in scalar and return the root object, undef on error.
7532  */
7533 static SV *mretrieve(pTHX_ SV *sv, IV flag)
7534 {
7535     TRACEMED(("mretrieve"));
7536     return do_retrieve(aTHX_ (PerlIO*) 0, sv, 0, (int)flag);
7537 }
7538
7539 /***
7540  *** Deep cloning
7541  ***/
7542
7543 /*
7544  * dclone
7545  *
7546  * Deep clone: returns a fresh copy of the original referenced SV tree.
7547  *
7548  * This is achieved by storing the object in memory and restoring from
7549  * there. Not that efficient, but it should be faster than doing it from
7550  * pure perl anyway.
7551  */
7552 static SV *dclone(pTHX_ SV *sv)
7553 {
7554     dSTCXT;
7555     STRLEN size;
7556     stcxt_t *real_context;
7557     SV *out;
7558
7559     TRACEMED(("dclone"));
7560
7561     /*
7562      * Workaround for CROAK leak: if they enter with a "dirty" context,
7563      * free up memory for them now.
7564      */
7565
7566     assert(cxt);
7567     if (cxt->s_dirty)
7568         clean_context(aTHX_ cxt);
7569
7570     /*
7571      * Tied elements seem to need special handling.
7572      */
7573
7574     if ((SvTYPE(sv) == SVt_PVLV
7575 #if PERL_VERSION_LT(5,8,0)
7576          || SvTYPE(sv) == SVt_PVMG
7577 #endif
7578          ) && (SvFLAGS(sv) & (SVs_GMG|SVs_SMG|SVs_RMG)) ==
7579         (SVs_GMG|SVs_SMG|SVs_RMG) &&
7580         mg_find(sv, 'p')) {
7581         mg_get(sv);
7582     }
7583
7584     /*
7585      * do_store() optimizes for dclone by not freeing its context, should
7586      * we need to allocate one because we're deep cloning from a hook.
7587      */
7588
7589     if (!do_store(aTHX_ (PerlIO*) 0, sv, ST_CLONE, FALSE, (SV**) 0))
7590         return &PL_sv_undef;                            /* Error during store */
7591
7592     /*
7593      * Because of the above optimization, we have to refresh the context,
7594      * since a new one could have been allocated and stacked by do_store().
7595      */
7596
7597     { dSTCXT; real_context = cxt; }             /* Sub-block needed for macro */
7598     cxt = real_context;                                 /* And we need this temporary... */
7599
7600     /*
7601      * Now, 'cxt' may refer to a new context.
7602      */
7603
7604     assert(cxt);
7605     ASSERT(!cxt->s_dirty, ("clean context"));
7606     ASSERT(!cxt->entry, ("entry will not cause new context allocation"));
7607
7608     size = MBUF_SIZE();
7609     TRACEME(("dclone stored %ld bytes", (long)size));
7610     MBUF_INIT(size);
7611
7612     /*
7613      * Since we're passing do_retrieve() both a NULL file and sv, we need
7614      * to pre-compute the taintedness of the input by setting cxt->tainted
7615      * to whatever state our own input string was.      -- RAM, 15/09/2000
7616      *
7617      * do_retrieve() will free non-root context.
7618      */
7619
7620     cxt->s_tainted = SvTAINTED(sv);
7621     out = do_retrieve(aTHX_ (PerlIO*) 0, Nullsv, ST_CLONE, FLAG_BLESS_OK | FLAG_TIE_OK);
7622
7623     TRACEMED(("dclone returns 0x%" UVxf, PTR2UV(out)));
7624
7625     return out;
7626 }
7627
7628 /***
7629  *** Glue with perl.
7630  ***/
7631
7632 /*
7633  * The Perl IO GV object distinguishes between input and output for sockets
7634  * but not for plain files. To allow Storable to transparently work on
7635  * plain files and sockets transparently, we have to ask xsubpp to fetch the
7636  * right object for us. Hence the OutputStream and InputStream declarations.
7637  *
7638  * Before perl 5.004_05, those entries in the standard typemap are not
7639  * defined in perl include files, so we do that here.
7640  */
7641
7642 #ifndef OutputStream
7643 #define OutputStream    PerlIO *
7644 #define InputStream     PerlIO *
7645 #endif  /* !OutputStream */
7646
7647 static int
7648 storable_free(pTHX_ SV *sv, MAGIC* mg) {
7649     stcxt_t *cxt = (stcxt_t *)SvPVX(sv);
7650
7651     PERL_UNUSED_ARG(mg);
7652 #ifdef USE_PTR_TABLE
7653     if (cxt->pseen)
7654         ptr_table_free(cxt->pseen);
7655 #endif
7656     if (kbuf)
7657         Safefree(kbuf);
7658     if (!cxt->membuf_ro && mbase)
7659         Safefree(mbase);
7660     if (cxt->membuf_ro && (cxt->msaved).arena)
7661         Safefree((cxt->msaved).arena);
7662     return 0;
7663 }
7664
7665 MODULE = Storable       PACKAGE = Storable
7666
7667 PROTOTYPES: ENABLE
7668
7669 BOOT:
7670 {
7671     HV *stash = gv_stashpvn("Storable", 8, GV_ADD);
7672     newCONSTSUB(stash, "BIN_MAJOR", newSViv(STORABLE_BIN_MAJOR));
7673     newCONSTSUB(stash, "BIN_MINOR", newSViv(STORABLE_BIN_MINOR));
7674     newCONSTSUB(stash, "BIN_WRITE_MINOR", newSViv(STORABLE_BIN_WRITE_MINOR));
7675
7676     newCONSTSUB(stash, "CAN_FLOCK", CAN_FLOCK);
7677
7678     init_perinterp(aTHX);
7679     gv_fetchpv("Storable::drop_utf8",   GV_ADDMULTI, SVt_PV);
7680 #ifdef DEBUGME
7681     /* Only disable the used only once warning if we are in debugging mode.  */
7682     gv_fetchpv("Storable::DEBUGME",   GV_ADDMULTI, SVt_PV);
7683 #endif
7684 #ifdef USE_56_INTERWORK_KLUDGE
7685     gv_fetchpv("Storable::interwork_56_64bit",   GV_ADDMULTI, SVt_PV);
7686 #endif
7687     }
7688
7689 void
7690 init_perinterp()
7691 CODE:
7692     init_perinterp(aTHX);
7693
7694 # pstore
7695 #
7696 # Store the transitive data closure of given object to disk.
7697 # Returns undef on error, a true value otherwise.
7698
7699 # net_pstore
7700 #
7701 # Same as pstore(), but network order is used for integers and doubles are
7702 # emitted as strings.
7703
7704 SV *
7705 pstore(f,obj)
7706     OutputStream f
7707     SV*         obj
7708 ALIAS:
7709     net_pstore = 1
7710 PPCODE:
7711     RETVAL = do_store(aTHX_ f, obj, 0, ix, (SV **)0) ? &PL_sv_yes : &PL_sv_undef;
7712     /* do_store() can reallocate the stack, so need a sequence point to ensure
7713        that ST(0) knows about it. Hence using two statements.  */
7714     ST(0) = RETVAL;
7715     XSRETURN(1);
7716
7717 # mstore
7718 #
7719 # Store the transitive data closure of given object to memory.
7720 # Returns undef on error, a scalar value containing the data otherwise.
7721
7722 # net_mstore
7723 #
7724 # Same as mstore(), but network order is used for integers and doubles are
7725 # emitted as strings.
7726
7727 SV *
7728 mstore(obj)
7729     SV* obj
7730 ALIAS:
7731     net_mstore = 1
7732 CODE:
7733     RETVAL = &PL_sv_undef;
7734     if (!do_store(aTHX_ (PerlIO*) 0, obj, 0, ix, &RETVAL))
7735         RETVAL = &PL_sv_undef;
7736 OUTPUT:
7737     RETVAL
7738
7739 SV *
7740 pretrieve(f, flag = 6)
7741     InputStream f
7742     IV          flag
7743 CODE:
7744     RETVAL = pretrieve(aTHX_ f, flag);
7745 OUTPUT:
7746     RETVAL
7747
7748 SV *
7749 mretrieve(sv, flag = 6)
7750     SV* sv
7751     IV  flag
7752 CODE:
7753     RETVAL = mretrieve(aTHX_ sv, flag);
7754 OUTPUT:
7755     RETVAL
7756
7757 SV *
7758 dclone(sv)
7759     SV* sv
7760 CODE:
7761     RETVAL = dclone(aTHX_ sv);
7762 OUTPUT:
7763     RETVAL
7764
7765 void
7766 last_op_in_netorder()
7767 ALIAS:
7768     is_storing = ST_STORE
7769     is_retrieving = ST_RETRIEVE
7770 PREINIT:
7771     bool result;
7772 CODE:
7773     if (ix) {
7774         dSTCXT;
7775         assert(cxt);
7776         result = cxt->entry && (cxt->optype & ix) ? TRUE : FALSE;
7777     } else {
7778         result = !!last_op_in_netorder(aTHX);
7779     }
7780     ST(0) = boolSV(result);
7781
7782
7783 IV
7784 stack_depth()
7785 CODE:
7786     RETVAL = SvIV(get_sv("Storable::recursion_limit", GV_ADD));
7787 OUTPUT:
7788     RETVAL
7789
7790 IV
7791 stack_depth_hash()
7792 CODE:
7793     RETVAL = SvIV(get_sv("Storable::recursion_limit_hash", GV_ADD));
7794 OUTPUT:
7795     RETVAL