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