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