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