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