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