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