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