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