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