2 * Store and retrieve mechanism.
6 * $Id: Storable.xs,v 0.7.1.2 2000/08/14 07:19:27 ram Exp $
8 * Copyright (c) 1995-2000, Raphael Manfredi
10 * You may redistribute only under the terms of the Artistic License,
11 * as specified in the README file that comes with the distribution.
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()
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
22 * Revision 0.7 2000/08/03 22:04:44 ram
23 * Baseline for second beta release.
29 #include <patchlevel.h> /* Perl's one, needed since 5.6 */
32 /*#define DEBUGME /* Debug mode, turns assertions on as well */
33 /*#define DASSERT /* Assertion mode */
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.
40 #ifndef PERLIO_IS_STDIO
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 */
51 * Earlier versions of perl might be used, we can't assume they have the latest!
54 #define newRV_noinc(sv) ((Sv = newRV(sv)), --SvREFCNT(SvRV(Sv)), Sv)
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
61 #ifndef HvSHAREKEYS_off
62 #define HvSHAREKEYS_off(hv) /* Ignore */
69 #define TRACEME(x) do { PerlIO_stdoutf x; PerlIO_stdoutf("\n"); } while (0)
75 #define ASSERT(x,y) do { \
77 PerlIO_stdoutf("ASSERT FAILED (\"%s\", line %d): ", \
78 __FILE__, __LINE__); \
79 PerlIO_stdoutf y; PerlIO_stdoutf("\n"); \
90 #define C(x) ((char) (x)) /* For markers with dynamic retrieval handling */
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 */
118 * Those are only used to retrieve "old" pre-0.6 binary images.
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 */
127 * Those are only used to retrieve "old" pre-0.7 binary images
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 */
135 * Limits between short/long length representation.
138 #define LG_SCALAR 255 /* Large scalar length limit */
139 #define LG_BLESS 127 /* Large classname bless limit */
145 #define ST_STORE 0x1 /* Store operation */
146 #define ST_RETRIEVE 0x2 /* Retrieval operation */
147 #define ST_CLONE 0x4 /* Deep cloning operation */
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).
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.
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 */
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.
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.
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.
183 typedef unsigned long stag_t; /* Used by pre-0.6 binary format */
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
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
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,
200 #define MY_VERSION "Storable(" XS_VERSION ")"
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 */
225 #if defined(MULTIPLICITY) || defined(PERL_OBJECT) || defined(PERL_CAPI)
227 #if (PATCHLEVEL <= 4) && (SUBVERSION < 68)
229 SV *perinterp_sv = perl_get_sv(MY_VERSION, FALSE)
230 #else /* >= perl5.004_68 */
232 SV *perinterp_sv = *hv_fetch(PL_modglobal, \
233 MY_VERSION, sizeof(MY_VERSION)-1, TRUE)
234 #endif /* < perl5.004_68 */
236 #define dSTCXT_PTR(T,name) \
237 T name = (T)(perinterp_sv && SvIOK(perinterp_sv)\
238 ? SvIVX(perinterp_sv) : NULL)
241 dSTCXT_PTR(stcxt_t *, cxt)
245 Newz(0, cxt, 1, stcxt_t); \
246 sv_setiv(perinterp_sv, (IV) cxt)
248 #define SET_STCXT(x) do { \
250 sv_setiv(perinterp_sv, (IV) (x)); \
253 #else /* !MULTIPLICITY && !PERL_OBJECT && !PERL_CAPI */
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
261 #endif /* MULTIPLICITY || PERL_OBJECT || PERL_CAPI */
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.
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).
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.
280 #define CROAK(x) do { cxt->dirty = 1; croak x; } while (0)
283 * End of "thread-safe" related definitions.
287 * key buffer handling
289 #define kbuf (cxt->keybuf).arena
290 #define ksiz (cxt->keybuf).asiz
291 #define KBUFINIT() do { \
293 TRACEME(("** allocating kbuf of 128 bytes")); \
294 New(10003, kbuf, 128, char); \
298 #define KBUFCHK(x) do { \
300 TRACEME(("** extending kbuf to %d bytes", x+1)); \
301 Renew(kbuf, x+1, char); \
307 * memory buffer handling
309 #define mbase (cxt->membuf).arena
310 #define msiz (cxt->membuf).asiz
311 #define mptr (cxt->membuf).aptr
312 #define mend (cxt->membuf).aend
314 #define MGROW (1 << 13)
315 #define MMASK (MGROW - 1)
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))
324 #define MBUF_INIT(x) do { \
326 TRACEME(("** allocating mbase of %d bytes", MGROW)); \
327 New(10003, mbase, MGROW, char); \
334 mend = mbase + msiz; \
337 #define MBUF_TRUNC(x) mptr = mbase + x
338 #define MBUF_SIZE() (mptr - mbase)
341 * Use SvPOKp(), because SvPOK() fails on tainted scalars.
342 * See store_scalar() for other usage of this workaround.
344 #define MBUF_LOAD(v) do { \
346 CROAK(("Not a scalar string")); \
347 mptr = mbase = SvPV(v, msiz); \
348 mend = mbase + msiz; \
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); \
357 mptr = mbase + offset; \
358 mend = mbase + nsz; \
361 #define MBUF_CHK(x) do { \
362 if ((mptr + (x)) > mend) \
366 #define MBUF_GETC(x) do { \
368 x = (int) (unsigned char) *mptr++; \
373 #define MBUF_GETINT(x) do { \
374 if ((mptr + sizeof(int)) <= mend) { \
375 if (int_aligned(mptr)) \
378 memcpy(&x, mptr, sizeof(int)); \
379 mptr += sizeof(int); \
384 #define MBUF_READ(x,s) do { \
385 if ((mptr + (s)) <= mend) { \
386 memcpy(x, mptr, s); \
392 #define MBUF_SAFEREAD(x,s,z) do { \
393 if ((mptr + (s)) <= mend) { \
394 memcpy(x, mptr, s); \
402 #define MBUF_PUTC(c) do { \
404 *mptr++ = (char) c; \
407 *mptr++ = (char) c; \
411 #define MBUF_PUTINT(i) do { \
412 MBUF_CHK(sizeof(int)); \
413 if (int_aligned(mptr)) \
416 memcpy(mptr, &i, sizeof(int)); \
417 mptr += sizeof(int); \
420 #define MBUF_WRITE(x,s) do { \
422 memcpy(mptr, x, s); \
429 * Keep only the low 32 bits of a pointer (used for tags, which are not
434 #define LOW_32BITS(x) ((I32) (x))
436 #define LOW_32BITS(x) ((I32) ((unsigned long) (x) & 0xffffffffUL))
440 * Possible return values for sv_type().
444 #define svis_SCALAR 1
448 #define svis_TIED_ITEM 5
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
464 * Types for SX_HOOK (2 bits).
472 * Before 0.6, the magic string was "perl-store" (binary version number 0).
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
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.
487 static char old_magicstr[] = "perl-store"; /* Magic number before 0.6 */
488 static char magicstr[] = "pst0"; /* Used as a magic number */
490 #define STORABLE_BIN_MAJOR 2 /* Binary major "version" */
491 #define STORABLE_BIN_MINOR 1 /* Binary minor "version" */
494 * Useful store shortcuts...
497 #define PUTMARK(x) do { \
500 else if (PerlIO_putc(cxt->fio, x) == EOF) \
505 #define WLEN(x) do { \
506 if (cxt->netorder) { \
507 int y = (int) htonl(x); \
510 else if (PerlIO_write(cxt->fio, &y, sizeof(y)) != sizeof(y)) \
515 else if (PerlIO_write(cxt->fio, &x, sizeof(x)) != sizeof(x)) \
520 #define WLEN(x) do { \
523 else if (PerlIO_write(cxt->fio, &x, sizeof(x)) != sizeof(x)) \
528 #define WRITE(x,y) do { \
531 else if (PerlIO_write(cxt->fio, x, y) != y) \
535 #define STORE_SCALAR(pv, len) do { \
536 if (len <= LG_SCALAR) { \
537 unsigned char clen = (unsigned char) len; \
538 PUTMARK(SX_SCALAR); \
543 PUTMARK(SX_LSCALAR); \
550 * Store undef in arrays and hashes without recursing through store().
552 #define STORE_UNDEF() do { \
558 * Useful retrieve shortcuts...
562 (cxt->fio ? PerlIO_getc(cxt->fio) : (mptr >= mend ? EOF : (int) *mptr++))
564 #define GETMARK(x) do { \
567 else if ((x = PerlIO_getc(cxt->fio)) == EOF) \
572 #define RLEN(x) do { \
575 else if (PerlIO_read(cxt->fio, &x, sizeof(x)) != sizeof(x)) \
578 x = (int) ntohl(x); \
581 #define RLEN(x) do { \
584 else if (PerlIO_read(cxt->fio, &x, sizeof(x)) != sizeof(x)) \
589 #define READ(x,y) do { \
592 else if (PerlIO_read(cxt->fio, x, y) != y) \
596 #define SAFEREAD(x,y,z) do { \
598 MBUF_SAFEREAD(x,y,z); \
599 else if (PerlIO_read(cxt->fio, x, y) != y) { \
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.
611 #define SEEN(y) do { \
614 if (av_store(cxt->aseen, cxt->tagnum++, SvREFCNT_inc(y)) == 0) \
616 TRACEME(("aseen(#%d) = 0x%lx (refcnt=%d)", cxt->tagnum-1, \
617 (unsigned long) y, SvREFCNT(y)-1)); \
621 * Bless `s' in `p', via a temporary reference, required by sv_bless().
623 #define BLESS(s,p) do { \
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); \
635 static SV *retrieve();
638 * Dynamic dispatching table for SV store.
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);
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 */
659 #define SV_STORE(x) (*sv_store[x])
662 * Dynamic dispatching tables for SV retrieval.
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);
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 */
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);
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 */
746 #define RETRIEVE(c,x) (*(c)->retrieve_vtbl[(x) >= SX_ERROR ? SX_ERROR : (x)])
748 static SV *mbuf2sv();
749 static int store_blessed();
752 *** Context management.
758 * Called once per "thread" (interpreter) to initialize some global context.
760 static void init_perinterp() {
763 cxt->netorder = 0; /* true if network order used */
764 cxt->forgive_me = -1; /* whether to be forgiving... */
770 * Initialize a new store context for real recursion.
772 static void init_store_context(cxt, f, optype, network_order)
778 TRACEME(("init_store_context"));
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 */
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.
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%.
801 cxt->hseen = newHV(); /* Table where seen objects are stored */
802 HvSHAREKEYS_off(cxt->hseen);
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.
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.
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.
818 * It is reported fixed in 5.005, hence the #if.
821 #define HBUCKETS 4096 /* Buckets for %hseen */
822 HvMAX(cxt->hseen) = HBUCKETS - 1; /* keys %hseen = $HBUCKETS; */
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
830 * We turn the shared key optimization on.
833 cxt->hclass = newHV(); /* Where seen classnames are stored */
836 HvMAX(cxt->hclass) = HBUCKETS - 1; /* keys %hclass = $HBUCKETS; */
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.
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
848 cxt->hook = newHV(); /* Table where hooks are cached */
852 * clean_store_context
854 * Clean store context by
856 static void clean_store_context(cxt)
861 TRACEME(("clean_store_context"));
863 ASSERT(cxt->optype & ST_STORE, ("was performing a store()"));
866 * Insert real values into hashes where we stored faked pointers.
869 hv_iterinit(cxt->hseen);
870 while (he = hv_iternext(cxt->hseen))
871 HeVAL(he) = &PL_sv_undef;
873 hv_iterinit(cxt->hclass);
874 while (he = hv_iternext(cxt->hclass))
875 HeVAL(he) = &PL_sv_undef;
878 * And now dispose of them...
881 hv_undef(cxt->hseen);
882 sv_free((SV *) cxt->hseen);
884 hv_undef(cxt->hclass);
885 sv_free((SV *) cxt->hclass);
888 sv_free((SV *) cxt->hook);
895 * init_retrieve_context
897 * Initialize a new retrieve context for real recursion.
899 static void init_retrieve_context(cxt, optype)
903 TRACEME(("init_retrieve_context"));
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.
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
914 cxt->hook = newHV(); /* Caches STORABLE_thaw */
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.
923 cxt->hseen = (cxt->retrieve_vtbl == sv_old_retrieve) ? newHV() : 0;
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 */
934 * clean_retrieve_context
936 * Clean retrieve context by
938 static void clean_retrieve_context(cxt)
941 TRACEME(("clean_retrieve_context"));
943 ASSERT(cxt->optype & ST_RETRIEVE, ("was performing a retrieve()"));
945 av_undef(cxt->aseen);
946 sv_free((SV *) cxt->aseen);
948 av_undef(cxt->aclass);
949 sv_free((SV *) cxt->aclass);
952 sv_free((SV *) cxt->hook);
955 sv_free((SV *) cxt->hseen); /* optional HV, for backward compat. */
964 * A workaround for the CROAK bug: cleanup the last context.
966 static void clean_context(cxt)
969 TRACEME(("clean_context"));
971 ASSERT(cxt->dirty, ("dirty context"));
973 if (cxt->optype & ST_RETRIEVE)
974 clean_retrieve_context(cxt);
976 clean_store_context(cxt);
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().
985 static stcxt_t *allocate_context(parent_cxt)
990 TRACEME(("allocate_context"));
992 ASSERT(!parent_cxt->dirty, ("parent context clean"));
994 Newz(0, cxt, 1, stcxt_t);
995 cxt->prev = parent_cxt;
1004 * Free current context, which cannot be the "root" one.
1005 * Make the context underneath globally visible via SET_STCXT().
1007 static void free_context(cxt)
1010 stcxt_t *prev = cxt->prev;
1012 TRACEME(("free_context"));
1014 ASSERT(!cxt->dirty, ("clean context"));
1015 ASSERT(prev, ("not freeing root context"));
1033 * Tells whether we're in the middle of a store operation.
1039 return cxt->entry && (cxt->optype & ST_STORE);
1045 * Tells whether we're in the middle of a retrieve operation.
1051 return cxt->entry && (cxt->optype & ST_RETRIEVE);
1055 * last_op_in_netorder
1057 * Returns whether last operation was made using network order.
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.
1062 int last_op_in_netorder()
1066 return cxt->netorder;
1070 *** Hook lookup and calling routines.
1076 * A wrapper on gv_fetchmethod_autoload() which caches results.
1078 * Returns the routine reference as an SV*, or null if neither the package
1079 * nor its ancestors know about the method.
1081 static SV *pkg_fetchmeth(cache, pkg, method)
1091 * The following code is the same as the one performed by UNIVERSAL::can
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));
1100 sv = newSVsv(&PL_sv_undef);
1101 TRACEME(("%s->%s: not found", HvNAME(pkg), method));
1105 * Cache the result, ignoring failure: if we can't store the value,
1106 * it just won't be cached.
1109 (void) hv_store(cache, HvNAME(pkg), strlen(HvNAME(pkg)), sv, 0);
1111 return SvOK(sv) ? sv : (SV *) 0;
1117 * Force cached value to be undef: hook ignored even if present.
1119 static void pkg_hide(cache, pkg, method)
1124 (void) hv_store(cache,
1125 HvNAME(pkg), strlen(HvNAME(pkg)), newSVsv(&PL_sv_undef), 0);
1131 * Our own "UNIVERSAL::can", which caches results.
1133 * Returns the routine reference as an SV*, or null if the object does not
1134 * know about the method.
1136 static SV *pkg_can(cache, pkg, method)
1144 TRACEME(("pkg_can for %s->%s", HvNAME(pkg), method));
1147 * Look into the cache to see whether we already have determined
1148 * where the routine was, if any.
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.
1154 svh = hv_fetch(cache, HvNAME(pkg), strlen(HvNAME(pkg)), FALSE);
1158 TRACEME(("cached %s->%s: not found", HvNAME(pkg), method));
1161 TRACEME(("cached %s->%s: 0x%lx", HvNAME(pkg), method,
1162 (unsigned long) sv));
1167 TRACEME(("not cached yet"));
1168 return pkg_fetchmeth(cache, pkg, method); /* Fetch and cache */
1174 * Call routine as obj->hook(av) in scalar context.
1175 * Propagates the single returned value if not called in void context.
1177 static SV *scalar_call(obj, hook, cloning, av, flags)
1188 TRACEME(("scalar_call (cloning=%d)", cloning));
1195 XPUSHs(sv_2mortal(newSViv(cloning))); /* Cloning flag */
1197 SV **ary = AvARRAY(av);
1198 int cnt = AvFILLp(av) + 1;
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])));
1208 TRACEME(("calling..."));
1209 count = perl_call_sv(hook, flags); /* Go back to Perl code */
1210 TRACEME(("count = %d", count));
1216 SvREFCNT_inc(sv); /* We're returning it, must stay alive! */
1229 * Call routine obj->hook(cloning) in list context.
1230 * Returns the list of returned values in an array.
1232 static AV *array_call(obj, hook, cloning)
1242 TRACEME(("arrary_call (cloning=%d)", cloning));
1248 XPUSHs(obj); /* Target object */
1249 XPUSHs(sv_2mortal(newSViv(cloning))); /* Cloning flag */
1252 count = perl_call_sv(hook, G_ARRAY); /* Go back to Perl code */
1257 for (i = count - 1; i >= 0; i--) {
1259 av_store(av, i, SvREFCNT_inc(sv));
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'.
1275 * Return true if the class was known, false if the ID was just generated.
1277 static int known_class(cxt, name, len, classnum)
1279 char *name; /* Class name */
1280 int len; /* Name length */
1284 HV *hclass = cxt->hclass;
1286 TRACEME(("known_class (%s)", name));
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.
1293 svh = hv_fetch(hclass, name, len, FALSE);
1295 *classnum = LOW_32BITS(*svh);
1300 * Unknown classname, we need to record it.
1304 if (!hv_store(hclass, name, len, INT2PTR(SV*, cxt->classnum), 0))
1305 CROAK(("Unable to record new classname"));
1307 *classnum = cxt->classnum;
1312 *** Sepcific store routines.
1318 * Store a reference.
1319 * Layout is SX_REF <object> or SX_OVERLOAD <object>.
1321 static int store_ref(cxt, sv)
1325 TRACEME(("store_ref (0x%lx)", (unsigned long) sv));
1328 * Follow reference, and check if target is overloaded.
1334 HV *stash = (HV *) SvSTASH(sv);
1335 if (stash && Gv_AMG(stash)) {
1336 TRACEME(("ref (0x%lx) is overloaded", (unsigned long) sv));
1337 PUTMARK(SX_OVERLOAD);
1343 return store(cxt, sv);
1351 * Layout is SX_LSCALAR <length> <data>, SX_SCALAR <lenght> <data> or SX_UNDEF.
1352 * The <data> section is omitted if <length> is 0.
1354 * If integer or double, the layout is SX_INTEGER <data> or SX_DOUBLE <data>.
1355 * Small integers (within [-127, +127]) are stored as SX_BYTE <byte>.
1357 static int store_scalar(cxt, sv)
1364 U32 flags = SvFLAGS(sv); /* "cc -O" may put it in register */
1366 TRACEME(("store_scalar (0x%lx)", (unsigned long) sv));
1369 * For efficiency, break the SV encapsulation by peaking at the flags
1370 * directly without using the Perl macros to avoid dereferencing
1371 * sv->sv_flags each time we wish to check the flags.
1374 if (!(flags & SVf_OK)) { /* !SvOK(sv) */
1375 if (sv == &PL_sv_undef) {
1376 TRACEME(("immortal undef"));
1377 PUTMARK(SX_SV_UNDEF);
1379 TRACEME(("undef at 0x%x", sv));
1386 * Always store the string representation of a scalar if it exists.
1387 * Gisle Aas provided me with this test case, better than a long speach:
1389 * perl -MDevel::Peek -le '$a="abc"; $a+0; Dump($a)'
1390 * SV = PVNV(0x80c8520)
1392 * FLAGS = (NOK,POK,pNOK,pPOK)
1395 * PV = 0x80c83d0 "abc"\0
1399 * Write SX_SCALAR, length, followed by the actual data.
1401 * Otherwise, write an SX_BYTE, SX_INTEGER or an SX_DOUBLE as
1402 * appropriate, followed by the actual (binary) data. A double
1403 * is written as a string if network order, for portability.
1405 * NOTE: instead of using SvNOK(sv), we test for SvNOKp(sv).
1406 * The reason is that when the scalar value is tainted, the SvNOK(sv)
1409 * The test for a read-only scalar with both POK and NOK set is meant
1410 * to quickly detect &PL_sv_yes and &PL_sv_no without having to pay the
1411 * address comparison for each scalar we store.
1414 #define SV_MAYBE_IMMORTAL (SVf_READONLY|SVf_POK|SVf_NOK)
1416 if ((flags & SV_MAYBE_IMMORTAL) == SV_MAYBE_IMMORTAL) {
1417 if (sv == &PL_sv_yes) {
1418 TRACEME(("immortal yes"));
1420 } else if (sv == &PL_sv_no) {
1421 TRACEME(("immortal no"));
1424 pv = SvPV(sv, len); /* We know it's SvPOK */
1425 goto string; /* Share code below */
1427 } else if (flags & SVp_POK) { /* SvPOKp(sv) => string */
1431 * Will come here from below with pv and len set if double & netorder,
1432 * or from above if it was readonly, POK and NOK but neither &PL_sv_yes
1437 STORE_SCALAR(pv, len);
1438 TRACEME(("ok (scalar 0x%lx '%s', length = %d)",
1439 (unsigned long) sv, SvPVX(sv), len));
1441 } else if (flags & SVp_NOK) { /* SvNOKp(sv) => double */
1445 * Watch for number being an integer in disguise.
1447 if (nv == (NV) (iv = I_V(nv))) {
1448 TRACEME(("double %lf is actually integer %ld", nv, iv));
1449 goto integer; /* Share code below */
1452 if (cxt->netorder) {
1453 TRACEME(("double %lf stored as string", nv));
1455 goto string; /* Share code above */
1459 WRITE(&nv, sizeof(nv));
1461 TRACEME(("ok (double 0x%lx, value = %lf)", (unsigned long) sv, nv));
1463 } else if (flags & SVp_IOK) { /* SvIOKp(sv) => integer */
1467 * Will come here from above with iv set if double is an integer.
1472 * Optimize small integers into a single byte, otherwise store as
1473 * a real integer (converted into network order if they asked).
1476 if (iv >= -128 && iv <= 127) {
1477 unsigned char siv = (unsigned char) (iv + 128); /* [0,255] */
1480 TRACEME(("small integer stored as %d", siv));
1481 } else if (cxt->netorder) {
1484 niv = (int) htonl(iv);
1485 TRACEME(("using network order"));
1488 TRACEME(("as-is for network order"));
1491 WRITE(&niv, sizeof(niv));
1493 PUTMARK(SX_INTEGER);
1494 WRITE(&iv, sizeof(iv));
1497 TRACEME(("ok (integer 0x%lx, value = %d)", (unsigned long) sv, iv));
1500 CROAK(("Can't determine type of %s(0x%lx)", sv_reftype(sv, FALSE),
1501 (unsigned long) sv));
1503 return 0; /* Ok, no recursion on scalars */
1511 * Layout is SX_ARRAY <size> followed by each item, in increading index order.
1512 * Each item is stored as <object>.
1514 static int store_array(cxt, av)
1519 I32 len = av_len(av) + 1;
1523 TRACEME(("store_array (0x%lx)", (unsigned long) av));
1526 * Signal array by emitting SX_ARRAY, followed by the array length.
1531 TRACEME(("size = %d", len));
1534 * Now store each item recursively.
1537 for (i = 0; i < len; i++) {
1538 sav = av_fetch(av, i, 0);
1540 TRACEME(("(#%d) undef item", i));
1544 TRACEME(("(#%d) item", i));
1545 if (ret = store(cxt, *sav))
1549 TRACEME(("ok (array)"));
1558 * Borrowed from perl source file pp_ctl.c, where it is used by pp_sort.
1565 return sv_cmp(*(SV * const *) a, *(SV * const *) b);
1572 * Store an hash table.
1574 * Layout is SX_HASH <size> followed by each key/value pair, in random order.
1575 * Values are stored as <object>.
1576 * Keys are stored as <length> <data>, the <data> section being omitted
1579 static int store_hash(cxt, hv)
1583 I32 len = HvKEYS(hv);
1589 TRACEME(("store_hash (0x%lx)", (unsigned long) hv));
1592 * Signal hash by emitting SX_HASH, followed by the table length.
1597 TRACEME(("size = %d", len));
1600 * Save possible iteration state via each() on that table.
1603 riter = HvRITER(hv);
1604 eiter = HvEITER(hv);
1608 * Now store each item recursively.
1610 * If canonical is defined to some true value then store each
1611 * key/value pair in sorted order otherwise the order is random.
1612 * Canonical order is irrelevant when a deep clone operation is performed.
1614 * Fetch the value from perl only once per store() operation, and only
1619 !(cxt->optype & ST_CLONE) && (cxt->canonical == 1 ||
1620 (cxt->canonical < 0 && (cxt->canonical =
1621 SvTRUE(perl_get_sv("Storable::canonical", TRUE)) ? 1 : 0)))
1624 * Storing in order, sorted by key.
1625 * Run through the hash, building up an array of keys in a
1626 * mortal array, sort the array and then run through the
1632 TRACEME(("using canonical order"));
1634 for (i = 0; i < len; i++) {
1635 HE *he = hv_iternext(hv);
1636 SV *key = hv_iterkeysv(he);
1637 av_store(av, AvFILLp(av)+1, key); /* av_push(), really */
1640 qsort((char *) AvARRAY(av), len, sizeof(SV *), sortcmp);
1642 for (i = 0; i < len; i++) {
1645 SV *key = av_shift(av);
1646 HE *he = hv_fetch_ent(hv, key, 0, 0);
1647 SV *val = HeVAL(he);
1649 return 1; /* Internal error, not I/O error */
1652 * Store value first.
1655 TRACEME(("(#%d) value 0x%lx", i, (unsigned long) val));
1657 if (ret = store(cxt, val))
1662 * Keys are written after values to make sure retrieval
1663 * can be optimal in terms of memory usage, where keys are
1664 * read into a fixed unique buffer called kbuf.
1665 * See retrieve_hash() for details.
1668 keyval = hv_iterkey(he, &keylen);
1669 TRACEME(("(#%d) key '%s'", i, keyval));
1672 WRITE(keyval, keylen);
1676 * Free up the temporary array
1685 * Storing in "random" order (in the order the keys are stored
1686 * within the the hash). This is the default and will be faster!
1689 for (i = 0; i < len; i++) {
1692 SV *val = hv_iternextsv(hv, &key, &len);
1695 return 1; /* Internal error, not I/O error */
1698 * Store value first.
1701 TRACEME(("(#%d) value 0x%lx", i, (unsigned long) val));
1703 if (ret = store(cxt, val))
1708 * Keys are written after values to make sure retrieval
1709 * can be optimal in terms of memory usage, where keys are
1710 * read into a fixed unique buffer called kbuf.
1711 * See retrieve_hash() for details.
1714 TRACEME(("(#%d) key '%s'", i, key));
1721 TRACEME(("ok (hash 0x%lx)", (unsigned long) hv));
1724 HvRITER(hv) = riter; /* Restore hash iterator state */
1725 HvEITER(hv) = eiter;
1733 * When storing a tied object (be it a tied scalar, array or hash), we lay out
1734 * a special mark, followed by the underlying tied object. For instance, when
1735 * dealing with a tied hash, we store SX_TIED_HASH <hash object>, where
1736 * <hash object> stands for the serialization of the tied hash.
1738 static int store_tied(cxt, sv)
1744 int svt = SvTYPE(sv);
1747 TRACEME(("store_tied (0x%lx)", (unsigned long) sv));
1750 * We have a small run-time penalty here because we chose to factorise
1751 * all tieds objects into the same routine, and not have a store_tied_hash,
1752 * a store_tied_array, etc...
1754 * Don't use a switch() statement, as most compilers don't optimize that
1755 * well for 2/3 values. An if() else if() cascade is just fine. We put
1756 * tied hashes first, as they are the most likely beasts.
1759 if (svt == SVt_PVHV) {
1760 TRACEME(("tied hash"));
1761 PUTMARK(SX_TIED_HASH); /* Introduces tied hash */
1762 } else if (svt == SVt_PVAV) {
1763 TRACEME(("tied array"));
1764 PUTMARK(SX_TIED_ARRAY); /* Introduces tied array */
1766 TRACEME(("tied scalar"));
1767 PUTMARK(SX_TIED_SCALAR); /* Introduces tied scalar */
1771 if (!(mg = mg_find(sv, mtype)))
1772 CROAK(("No magic '%c' found while storing tied %s", mtype,
1773 (svt == SVt_PVHV) ? "hash" :
1774 (svt == SVt_PVAV) ? "array" : "scalar"));
1777 * The mg->mg_obj found by mg_find() above actually points to the
1778 * underlying tied Perl object implementation. For instance, if the
1779 * original SV was that of a tied array, then mg->mg_obj is an AV.
1781 * Note that we store the Perl object as-is. We don't call its FETCH
1782 * method along the way. At retrieval time, we won't call its STORE
1783 * method either, but the tieing magic will be re-installed. In itself,
1784 * that ensures that the tieing semantics are preserved since futher
1785 * accesses on the retrieved object will indeed call the magic methods...
1788 if (ret = store(cxt, mg->mg_obj))
1791 TRACEME(("ok (tied)"));
1799 * Stores a reference to an item within a tied structure:
1801 * . \$h{key}, stores both the (tied %h) object and 'key'.
1802 * . \$a[idx], stores both the (tied @a) object and 'idx'.
1804 * Layout is therefore either:
1805 * SX_TIED_KEY <object> <key>
1806 * SX_TIED_IDX <object> <index>
1808 static int store_tied_item(cxt, sv)
1815 TRACEME(("store_tied_item (0x%lx)", (unsigned long) sv));
1817 if (!(mg = mg_find(sv, 'p')))
1818 CROAK(("No magic 'p' found while storing reference to tied item"));
1821 * We discriminate between \$h{key} and \$a[idx] via mg_ptr.
1825 TRACEME(("store_tied_item: storing a ref to a tied hash item"));
1826 PUTMARK(SX_TIED_KEY);
1827 TRACEME(("store_tied_item: storing OBJ 0x%lx",
1828 (unsigned long) mg->mg_obj));
1830 if (ret = store(cxt, mg->mg_obj))
1833 TRACEME(("store_tied_item: storing PTR 0x%lx",
1834 (unsigned long) mg->mg_ptr));
1836 if (ret = store(cxt, (SV *) mg->mg_ptr))
1839 I32 idx = mg->mg_len;
1841 TRACEME(("store_tied_item: storing a ref to a tied array item "));
1842 PUTMARK(SX_TIED_IDX);
1843 TRACEME(("store_tied_item: storing OBJ 0x%lx",
1844 (unsigned long) mg->mg_obj));
1846 if (ret = store(cxt, mg->mg_obj))
1849 TRACEME(("store_tied_item: storing IDX %d", idx));
1854 TRACEME(("ok (tied item)"));
1860 * store_hook -- dispatched manually, not via sv_store[]
1862 * The blessed SV is serialized by a hook.
1866 * SX_HOOK <flags> <len> <classname> <len2> <str> [<len3> <object-IDs>]
1868 * where <flags> indicates how long <len>, <len2> and <len3> are, whether
1869 * the trailing part [] is present, the type of object (scalar, array or hash).
1870 * There is also a bit which says how the classname is stored between:
1875 * and when the <index> form is used (classname already seen), the "large
1876 * classname" bit in <flags> indicates how large the <index> is.
1878 * The serialized string returned by the hook is of length <len2> and comes
1879 * next. It is an opaque string for us.
1881 * Those <len3> object IDs which are listed last represent the extra references
1882 * not directly serialized by the hook, but which are linked to the object.
1884 * When recursion is mandated to resolve object-IDs not yet seen, we have
1885 * instead, with <header> being flags with bits set to indicate the object type
1886 * and that recursion was indeed needed:
1888 * SX_HOOK <header> <object> <header> <object> <flags>
1890 * that same header being repeated between serialized objects obtained through
1891 * recursion, until we reach flags indicating no recursion, at which point
1892 * we know we've resynchronized with a single layout, after <flags>.
1894 static int store_hook(cxt, sv, type, pkg, hook)
1906 int count; /* really len3 + 1 */
1907 unsigned char flags;
1910 int recursed = 0; /* counts recursion */
1911 int obj_type; /* object type, on 2 bits */
1914 int clone = cxt->optype & ST_CLONE;
1916 TRACEME(("store_hook, class \"%s\", tagged #%d", HvNAME(pkg), cxt->tagnum));
1919 * Determine object type on 2 bits.
1924 obj_type = SHT_SCALAR;
1927 obj_type = SHT_ARRAY;
1930 obj_type = SHT_HASH;
1933 CROAK(("Unexpected object type (%d) in store_hook()", type));
1935 flags = SHF_NEED_RECURSE | obj_type;
1937 class = HvNAME(pkg);
1938 len = strlen(class);
1941 * To call the hook, we need to fake a call like:
1943 * $object->STORABLE_freeze($cloning);
1945 * but we don't have the $object here. For instance, if $object is
1946 * a blessed array, what we have in `sv' is the array, and we can't
1947 * call a method on those.
1949 * Therefore, we need to create a temporary reference to the object and
1950 * make the call on that reference.
1953 TRACEME(("about to call STORABLE_freeze on class %s", class));
1955 ref = newRV_noinc(sv); /* Temporary reference */
1956 av = array_call(ref, hook, clone); /* @a = $object->STORABLE_freeze($c) */
1958 SvREFCNT_dec(ref); /* Reclaim temporary reference */
1960 count = AvFILLp(av) + 1;
1961 TRACEME(("store_hook, array holds %d items", count));
1964 * If they return an empty list, it means they wish to ignore the
1965 * hook for this class (and not just this instance -- that's for them
1966 * to handle if they so wish).
1968 * Simply disable the cached entry for the hook (it won't be recomputed
1969 * since it's present in the cache) and recurse to store_blessed().
1974 * They must not change their mind in the middle of a serialization.
1977 if (hv_fetch(cxt->hclass, class, len, FALSE))
1978 CROAK(("Too late to ignore hooks for %s class \"%s\"",
1979 (cxt->optype & ST_CLONE) ? "cloning" : "storing", class));
1981 pkg_hide(cxt->hook, pkg, "STORABLE_freeze");
1983 ASSERT(!pkg_can(cxt->hook, pkg, "STORABLE_freeze"), ("hook invisible"));
1984 TRACEME(("Ignoring STORABLE_freeze in class \"%s\"", class));
1986 return store_blessed(cxt, sv, type, pkg);
1990 * Get frozen string.
1994 pv = SvPV(ary[0], len2);
1997 * Allocate a class ID if not already done.
2000 if (!known_class(cxt, class, len, &classnum)) {
2001 TRACEME(("first time we see class %s, ID = %d", class, classnum));
2002 classnum = -1; /* Mark: we must store classname */
2004 TRACEME(("already seen class %s, ID = %d", class, classnum));
2008 * If they returned more than one item, we need to serialize some
2009 * extra references if not already done.
2011 * Loop over the array, starting at postion #1, and for each item,
2012 * ensure it is a reference, serialize it if not already done, and
2013 * replace the entry with the tag ID of the corresponding serialized
2016 * We CHEAT by not calling av_fetch() and read directly within the
2020 for (i = 1; i < count; i++) {
2025 CROAK(("Item #%d from hook in %s is not a reference", i, class));
2026 xsv = SvRV(xsv); /* Follow ref to know what to look for */
2029 * Look in hseen and see if we have a tag already.
2030 * Serialize entry if not done already, and get its tag.
2033 if (svh = hv_fetch(cxt->hseen, (char *) &xsv, sizeof(xsv), FALSE))
2034 goto sv_seen; /* Avoid moving code too far to the right */
2036 TRACEME(("listed object %d at 0x%lx is unknown",
2037 i-1, (unsigned long) xsv));
2040 * We need to recurse to store that object and get it to be known
2041 * so that we can resolve the list of object-IDs at retrieve time.
2043 * The first time we do this, we need to emit the proper header
2044 * indicating that we recursed, and what the type of object is (the
2045 * object we're storing via a user-hook). Indeed, during retrieval,
2046 * we'll have to create the object before recursing to retrieve the
2047 * others, in case those would point back at that object.
2050 /* [SX_HOOK] <flags> <object>*/
2055 if (ret = store(cxt, xsv)) /* Given by hook for us to store */
2058 svh = hv_fetch(cxt->hseen, (char *) &xsv, sizeof(xsv), FALSE);
2060 CROAK(("Could not serialize item #%d from hook in %s", i, class));
2063 * Replace entry with its tag (not a real SV, so no refcnt increment)
2069 TRACEME(("listed object %d at 0x%lx is tag #%d",
2070 i-1, (unsigned long) xsv, (I32) *svh));
2074 * Compute leading flags.
2078 if (((classnum == -1) ? len : classnum) > LG_SCALAR)
2079 flags |= SHF_LARGE_CLASSLEN;
2081 flags |= SHF_IDX_CLASSNAME;
2082 if (len2 > LG_SCALAR)
2083 flags |= SHF_LARGE_STRLEN;
2085 flags |= SHF_HAS_LIST;
2086 if (count > (LG_SCALAR + 1))
2087 flags |= SHF_LARGE_LISTLEN;
2090 * We're ready to emit either serialized form:
2092 * SX_HOOK <flags> <len> <classname> <len2> <str> [<len3> <object-IDs>]
2093 * SX_HOOK <flags> <index> <len2> <str> [<len3> <object-IDs>]
2095 * If we recursed, the SX_HOOK has already been emitted.
2098 TRACEME(("SX_HOOK (recursed=%d) flags=0x%x class=%d len=%d len2=%d len3=%d",
2099 recursed, flags, classnum, len, len2, count-1));
2101 /* SX_HOOK <flags> */
2106 /* <len> <classname> or <index> */
2107 if (flags & SHF_IDX_CLASSNAME) {
2108 if (flags & SHF_LARGE_CLASSLEN)
2111 unsigned char cnum = (unsigned char) classnum;
2115 if (flags & SHF_LARGE_CLASSLEN)
2118 unsigned char clen = (unsigned char) len;
2121 WRITE(class, len); /* Final \0 is omitted */
2124 /* <len2> <frozen-str> */
2125 if (flags & SHF_LARGE_STRLEN)
2128 unsigned char clen = (unsigned char) len2;
2132 WRITE(pv, len2); /* Final \0 is omitted */
2134 /* [<len3> <object-IDs>] */
2135 if (flags & SHF_HAS_LIST) {
2136 int len3 = count - 1;
2137 if (flags & SHF_LARGE_LISTLEN)
2140 unsigned char clen = (unsigned char) len3;
2145 * NOTA BENE, for 64-bit machines: the ary[i] below does not yield a
2146 * real pointer, rather a tag number, well under the 32-bit limit.
2149 for (i = 1; i < count; i++) {
2150 I32 tagval = htonl(LOW_32BITS(ary[i]));
2151 WRITE(&tagval, sizeof(I32));
2152 TRACEME(("object %d, tag #%d", i-1, ntohl(tagval)));
2157 * Free the array. We need extra care for indices after 0, since they
2158 * don't hold real SVs but integers cast.
2162 AvFILLp(av) = 0; /* Cheat, nothing after 0 interests us */
2170 * store_blessed -- dispatched manually, not via sv_store[]
2172 * Check whether there is a STORABLE_xxx hook defined in the class or in one
2173 * of its ancestors. If there is, then redispatch to store_hook();
2175 * Otherwise, the blessed SV is stored using the following layout:
2177 * SX_BLESS <flag> <len> <classname> <object>
2179 * where <flag> indicates whether <len> is stored on 0 or 4 bytes, depending
2180 * on the high-order bit in flag: if 1, then length follows on 4 bytes.
2181 * Otherwise, the low order bits give the length, thereby giving a compact
2182 * representation for class names less than 127 chars long.
2184 * Each <classname> seen is remembered and indexed, so that the next time
2185 * an object in the blessed in the same <classname> is stored, the following
2188 * SX_IX_BLESS <flag> <index> <object>
2190 * where <index> is the classname index, stored on 0 or 4 bytes depending
2191 * on the high-order bit in flag (same encoding as above for <len>).
2193 static int store_blessed(cxt, sv, type, pkg)
2204 TRACEME(("store_blessed, type %d, class \"%s\"", type, HvNAME(pkg)));
2207 * Look for a hook for this blessed SV and redirect to store_hook()
2211 hook = pkg_can(cxt->hook, pkg, "STORABLE_freeze");
2213 return store_hook(cxt, sv, type, pkg, hook);
2216 * This is a blessed SV without any serialization hook.
2219 class = HvNAME(pkg);
2220 len = strlen(class);
2222 TRACEME(("blessed 0x%lx in %s, no hook: tagged #%d",
2223 (unsigned long) sv, class, cxt->tagnum));
2226 * Determine whether it is the first time we see that class name (in which
2227 * case it will be stored in the SX_BLESS form), or whether we already
2228 * saw that class name before (in which case the SX_IX_BLESS form will be
2232 if (known_class(cxt, class, len, &classnum)) {
2233 TRACEME(("already seen class %s, ID = %d", class, classnum));
2234 PUTMARK(SX_IX_BLESS);
2235 if (classnum <= LG_BLESS) {
2236 unsigned char cnum = (unsigned char) classnum;
2239 unsigned char flag = (unsigned char) 0x80;
2244 TRACEME(("first time we see class %s, ID = %d", class, classnum));
2246 if (len <= LG_BLESS) {
2247 unsigned char clen = (unsigned char) len;
2250 unsigned char flag = (unsigned char) 0x80;
2252 WLEN(len); /* Don't BER-encode, this should be rare */
2254 WRITE(class, len); /* Final \0 is omitted */
2258 * Now emit the <object> part.
2261 return SV_STORE(type)(cxt, sv);
2267 * We don't know how to store the item we reached, so return an error condition.
2268 * (it's probably a GLOB, some CODE reference, etc...)
2270 * If they defined the `forgive_me' variable at the Perl level to some
2271 * true value, then don't croak, just warn, and store a placeholder string
2274 static int store_other(cxt, sv)
2279 static char buf[80];
2281 TRACEME(("store_other"));
2284 * Fetch the value from perl only once per store() operation.
2288 cxt->forgive_me == 0 ||
2289 (cxt->forgive_me < 0 && !(cxt->forgive_me =
2290 SvTRUE(perl_get_sv("Storable::forgive_me", TRUE)) ? 1 : 0))
2292 CROAK(("Can't store %s items", sv_reftype(sv, FALSE)));
2294 warn("Can't store item %s(0x%lx)",
2295 sv_reftype(sv, FALSE), (unsigned long) sv);
2298 * Store placeholder string as a scalar instead...
2301 (void) sprintf(buf, "You lost %s(0x%lx)\0", sv_reftype(sv, FALSE),
2302 (unsigned long) sv);
2305 STORE_SCALAR(buf, len);
2306 TRACEME(("ok (dummy \"%s\", length = %d)", buf, len));
2312 *** Store driving routines
2318 * WARNING: partially duplicates Perl's sv_reftype for speed.
2320 * Returns the type of the SV, identified by an integer. That integer
2321 * may then be used to index the dynamic routine dispatch table.
2323 static int sv_type(sv)
2326 switch (SvTYPE(sv)) {
2331 * No need to check for ROK, that can't be set here since there
2332 * is no field capable of hodling the xrv_rv reference.
2340 * Starting from SVt_PV, it is possible to have the ROK flag
2341 * set, the pointer to the other SV being either stored in
2342 * the xrv_rv (in the case of a pure SVt_RV), or as the
2343 * xpv_pv field of an SVt_PV and its heirs.
2345 * However, those SV cannot be magical or they would be an
2346 * SVt_PVMG at least.
2348 return SvROK(sv) ? svis_REF : svis_SCALAR;
2350 case SVt_PVLV: /* Workaround for perl5.004_04 "LVALUE" bug */
2351 if (SvRMAGICAL(sv) && (mg_find(sv, 'p')))
2352 return svis_TIED_ITEM;
2355 if (SvRMAGICAL(sv) && (mg_find(sv, 'q')))
2357 return SvROK(sv) ? svis_REF : svis_SCALAR;
2359 if (SvRMAGICAL(sv) && (mg_find(sv, 'P')))
2363 if (SvRMAGICAL(sv) && (mg_find(sv, 'P')))
2376 * Recursively store objects pointed to by the sv to the specified file.
2378 * Layout is <content> or SX_OBJECT <tagnum> if we reach an already stored
2379 * object (one for which storage has started -- it may not be over if we have
2380 * a self-referenced structure). This data set forms a stored <object>.
2382 static int store(cxt, sv)
2390 HV *hseen = cxt->hseen;
2392 TRACEME(("store (0x%lx)", (unsigned long) sv));
2395 * If object has already been stored, do not duplicate data.
2396 * Simply emit the SX_OBJECT marker followed by its tag data.
2397 * The tag is always written in network order.
2399 * NOTA BENE, for 64-bit machines: the "*svh" below does not yield a
2400 * real pointer, rather a tag number (watch the insertion code below).
2401 * That means it pobably safe to assume it is well under the 32-bit limit,
2402 * and makes the truncation safe.
2403 * -- RAM, 14/09/1999
2406 svh = hv_fetch(hseen, (char *) &sv, sizeof(sv), FALSE);
2408 I32 tagval = htonl(LOW_32BITS(*svh));
2410 TRACEME(("object 0x%lx seen as #%d",
2411 (unsigned long) sv, ntohl(tagval)));
2414 WRITE(&tagval, sizeof(I32));
2419 * Allocate a new tag and associate it with the address of the sv being
2420 * stored, before recursing...
2422 * In order to avoid creating new SvIVs to hold the tagnum we just
2423 * cast the tagnum to a SV pointer and store that in the hash. This
2424 * means that we must clean up the hash manually afterwards, but gives
2425 * us a 15% throughput increase.
2430 if (!hv_store(hseen,
2431 (char *) &sv, sizeof(sv), INT2PTR(SV*, cxt->tagnum), 0))
2435 * Store `sv' and everything beneath it, using appropriate routine.
2436 * Abort immediately if we get a non-zero status back.
2441 TRACEME(("storing 0x%lx tag #%d, type %d...",
2442 (unsigned long) sv, cxt->tagnum, type));
2445 HV *pkg = SvSTASH(sv);
2446 ret = store_blessed(cxt, sv, type, pkg);
2448 ret = SV_STORE(type)(cxt, sv);
2450 TRACEME(("%s (stored 0x%lx, refcnt=%d, %s)",
2451 ret ? "FAILED" : "ok", (unsigned long) sv,
2452 SvREFCNT(sv), sv_reftype(sv, FALSE)));
2460 * Write magic number and system information into the file.
2461 * Layout is <magic> <network> [<len> <byteorder> <sizeof int> <sizeof long>
2462 * <sizeof ptr>] where <len> is the length of the byteorder hexa string.
2463 * All size and lenghts are written as single characters here.
2465 * Note that no byte ordering info is emitted when <network> is true, since
2466 * integers will be emitted in network order in that case.
2468 static int magic_write(cxt)
2471 char buf[256]; /* Enough room for 256 hexa digits */
2473 int use_network_order = cxt->netorder;
2475 TRACEME(("magic_write on fd=%d", cxt->fio ? fileno(cxt->fio) : -1));
2478 WRITE(magicstr, strlen(magicstr)); /* Don't write final \0 */
2481 * Starting with 0.6, the "use_network_order" byte flag is also used to
2482 * indicate the version number of the binary image, encoded in the upper
2483 * bits. The bit 0 is always used to indicate network order.
2487 ((use_network_order ? 0x1 : 0x0) | (STORABLE_BIN_MAJOR << 1));
2491 * Starting with 0.7, a full byte is dedicated to the minor version of
2492 * the binary format, which is incremented only when new markers are
2493 * introduced, for instance, but when backward compatibility is preserved.
2496 PUTMARK((unsigned char) STORABLE_BIN_MINOR);
2498 if (use_network_order)
2499 return 0; /* Don't bother with byte ordering */
2501 sprintf(buf, "%lx", (unsigned long) BYTEORDER);
2502 c = (unsigned char) strlen(buf);
2504 WRITE(buf, (unsigned int) c); /* Don't write final \0 */
2505 PUTMARK((unsigned char) sizeof(int));
2506 PUTMARK((unsigned char) sizeof(long));
2507 PUTMARK((unsigned char) sizeof(char *));
2509 TRACEME(("ok (magic_write byteorder = 0x%lx [%d], I%d L%d P%d)",
2510 (unsigned long) BYTEORDER, (int) c,
2511 sizeof(int), sizeof(long), sizeof(char *)));
2519 * Common code for store operations.
2521 * When memory store is requested (f = NULL) and a non null SV* is given in
2522 * `res', it is filled with a new SV created out of the memory buffer.
2524 * It is required to provide a non-null `res' when the operation type is not
2525 * dclone() and store() is performed to memory.
2527 static int do_store(f, sv, optype, network_order, res)
2537 ASSERT(!(f == 0 && !(optype & ST_CLONE)) || res,
2538 ("must supply result SV pointer for real recursion to memory"));
2540 TRACEME(("do_store (optype=%d, netorder=%d)",
2541 optype, network_order));
2546 * Workaround for CROAK leak: if they enter with a "dirty" context,
2547 * free up memory for them now.
2554 * Now that STORABLE_xxx hooks exist, it is possible that they try to
2555 * re-enter store() via the hooks. We need to stack contexts.
2559 cxt = allocate_context(cxt);
2563 ASSERT(cxt->entry == 1, ("starting new recursion"));
2564 ASSERT(!cxt->dirty, ("clean context"));
2567 * Ensure sv is actually a reference. From perl, we called something
2569 * pstore(FILE, \@array);
2570 * so we must get the scalar value behing that reference.
2574 CROAK(("Not a reference"));
2575 sv = SvRV(sv); /* So follow it to know what to store */
2578 * If we're going to store to memory, reset the buffer.
2585 * Prepare context and emit headers.
2588 init_store_context(cxt, f, optype, network_order);
2590 if (-1 == magic_write(cxt)) /* Emit magic and ILP info */
2591 return 0; /* Error */
2594 * Recursively store object...
2597 ASSERT(is_storing(), ("within store operation"));
2599 status = store(cxt, sv); /* Just do it! */
2602 * If they asked for a memory store and they provided an SV pointer,
2603 * make an SV string out of the buffer and fill their pointer.
2605 * When asking for ST_REAL, it's MANDATORY for the caller to provide
2606 * an SV, since context cleanup might free the buffer if we did recurse.
2607 * (unless caller is dclone(), which is aware of that).
2610 if (!cxt->fio && res)
2616 * The "root" context is never freed, since it is meant to be always
2617 * handy for the common case where no recursion occurs at all (i.e.
2618 * we enter store() outside of any Storable code and leave it, period).
2619 * We know it's the "root" context because there's nothing stacked
2624 * When deep cloning, we don't free the context: doing so would force
2625 * us to copy the data in the memory buffer. Sicne we know we're
2626 * about to enter do_retrieve...
2629 clean_store_context(cxt);
2630 if (cxt->prev && !(cxt->optype & ST_CLONE))
2633 TRACEME(("do_store returns %d", status));
2641 * Store the transitive data closure of given object to disk.
2642 * Returns 0 on error, a true value otherwise.
2648 TRACEME(("pstore"));
2649 return do_store(f, sv, 0, FALSE, (SV**)0);
2656 * Same as pstore(), but network order is used for integers and doubles are
2657 * emitted as strings.
2659 int net_pstore(f, sv)
2663 TRACEME(("net_pstore"));
2664 return do_store(f, sv, 0, TRUE, (SV**)0);
2674 * Build a new SV out of the content of the internal memory buffer.
2676 static SV *mbuf2sv()
2680 return newSVpv(mbase, MBUF_SIZE());
2686 * Store the transitive data closure of given object to memory.
2687 * Returns undef on error, a scalar value containing the data otherwise.
2695 TRACEME(("mstore"));
2697 if (!do_store((PerlIO*)0, sv, 0, FALSE, &out))
2698 return &PL_sv_undef;
2706 * Same as mstore(), but network order is used for integers and doubles are
2707 * emitted as strings.
2715 TRACEME(("net_mstore"));
2717 if (!do_store((PerlIO*)0, sv, 0, TRUE, &out))
2718 return &PL_sv_undef;
2724 *** Specific retrieve callbacks.
2730 * Return an error via croak, since it is not possible that we get here
2731 * under normal conditions, when facing a file produced via pstore().
2733 static SV *retrieve_other(cxt)
2737 cxt->ver_major != STORABLE_BIN_MAJOR &&
2738 cxt->ver_minor != STORABLE_BIN_MINOR
2740 CROAK(("Corrupted storable %s (binary v%d.%d), current is v%d.%d",
2741 cxt->fio ? "file" : "string",
2742 cxt->ver_major, cxt->ver_minor,
2743 STORABLE_BIN_MAJOR, STORABLE_BIN_MINOR));
2745 CROAK(("Corrupted storable %s (binary v%d.%d)",
2746 cxt->fio ? "file" : "string",
2747 cxt->ver_major, cxt->ver_minor));
2750 return (SV *) 0; /* Just in case */
2754 * retrieve_idx_blessed
2756 * Layout is SX_IX_BLESS <index> <object> with SX_IX_BLESS already read.
2757 * <index> can be coded on either 1 or 5 bytes.
2759 static SV *retrieve_idx_blessed(cxt)
2767 TRACEME(("retrieve_idx_blessed (#%d)", cxt->tagnum));
2769 GETMARK(idx); /* Index coded on a single char? */
2774 * Fetch classname in `aclass'
2777 sva = av_fetch(cxt->aclass, idx, FALSE);
2779 CROAK(("Class name #%d should have been seen already", idx));
2781 class = SvPVX(*sva); /* We know it's a PV, by construction */
2783 TRACEME(("class ID %d => %s", idx, class));
2786 * Retrieve object and bless it.
2799 * Layout is SX_BLESS <len> <classname> <object> with SX_BLESS already read.
2800 * <len> can be coded on either 1 or 5 bytes.
2802 static SV *retrieve_blessed(cxt)
2807 char buf[LG_BLESS + 1]; /* Avoid malloc() if possible */
2810 TRACEME(("retrieve_blessed (#%d)", cxt->tagnum));
2813 * Decode class name length and read that name.
2815 * Short classnames have two advantages: their length is stored on one
2816 * single byte, and the string can be read on the stack.
2819 GETMARK(len); /* Length coded on a single char? */
2822 TRACEME(("** allocating %d bytes for class name", len+1));
2823 New(10003, class, len+1, char);
2826 class[len] = '\0'; /* Mark string end */
2829 * It's a new classname, otherwise it would have been an SX_IX_BLESS.
2832 if (!av_store(cxt->aclass, cxt->classnum++, newSVpvn(class, len)))
2836 * Retrieve object and bless it.
2852 * Layout: SX_HOOK <flags> <len> <classname> <len2> <str> [<len3> <object-IDs>]
2853 * with leading mark already read, as usual.
2855 * When recursion was involved during serialization of the object, there
2856 * is an unknown amount of serialized objects after the SX_HOOK mark. Until
2857 * we reach a <flags> marker with the recursion bit cleared.
2859 static SV *retrieve_hook(cxt)
2863 char buf[LG_BLESS + 1]; /* Avoid malloc() if possible */
2875 int clone = cxt->optype & ST_CLONE;
2877 TRACEME(("retrieve_hook (#%d)", cxt->tagnum));
2880 * Read flags, which tell us about the type, and whether we need to recurse.
2886 * Create the (empty) object, and mark it as seen.
2888 * This must be done now, because tags are incremented, and during
2889 * serialization, the object tag was affected before recursion could
2893 obj_type = flags & SHF_TYPE_MASK;
2899 sv = (SV *) newAV();
2902 sv = (SV *) newHV();
2905 return retrieve_other(cxt); /* Let it croak */
2910 * Whilst flags tell us to recurse, do so.
2912 * We don't need to remember the addresses returned by retrieval, because
2913 * all the references will be obtained through indirection via the object
2914 * tags in the object-ID list.
2917 while (flags & SHF_NEED_RECURSE) {
2918 TRACEME(("retrieve_hook recursing..."));
2922 TRACEME(("retrieve_hook back with rv=0x%lx", (unsigned long) rv));
2926 if (flags & SHF_IDX_CLASSNAME) {
2931 * Fetch index from `aclass'
2934 if (flags & SHF_LARGE_CLASSLEN)
2939 sva = av_fetch(cxt->aclass, idx, FALSE);
2941 CROAK(("Class name #%d should have been seen already", idx));
2943 class = SvPVX(*sva); /* We know it's a PV, by construction */
2944 TRACEME(("class ID %d => %s", idx, class));
2948 * Decode class name length and read that name.
2950 * NOTA BENE: even if the length is stored on one byte, we don't read
2951 * on the stack. Just like retrieve_blessed(), we limit the name to
2952 * LG_BLESS bytes. This is an arbitrary decision.
2955 if (flags & SHF_LARGE_CLASSLEN)
2960 if (len > LG_BLESS) {
2961 TRACEME(("** allocating %d bytes for class name", len+1));
2962 New(10003, class, len+1, char);
2966 class[len] = '\0'; /* Mark string end */
2969 * Record new classname.
2972 if (!av_store(cxt->aclass, cxt->classnum++, newSVpvn(class, len)))
2976 TRACEME(("class name: %s", class));
2979 * Decode user-frozen string length and read it in a SV.
2981 * For efficiency reasons, we read data directly into the SV buffer.
2982 * To understand that code, read retrieve_scalar()
2985 if (flags & SHF_LARGE_STRLEN)
2990 frozen = NEWSV(10002, len2);
2992 SAFEREAD(SvPVX(frozen), len2, frozen);
2993 SvCUR_set(frozen, len2);
2994 *SvEND(frozen) = '\0';
2996 (void) SvPOK_only(frozen); /* Validates string pointer */
2999 TRACEME(("frozen string: %d bytes", len2));
3002 * Decode object-ID list length, if present.
3005 if (flags & SHF_HAS_LIST) {
3006 if (flags & SHF_LARGE_LISTLEN)
3012 av_extend(av, len3 + 1); /* Leave room for [0] */
3013 AvFILLp(av) = len3; /* About to be filled anyway */
3017 TRACEME(("has %d object IDs to link", len3));
3020 * Read object-ID list into array.
3021 * Because we pre-extended it, we can cheat and fill it manually.
3023 * We read object tags and we can convert them into SV* on the fly
3024 * because we know all the references listed in there (as tags)
3025 * have been already serialized, hence we have a valid correspondance
3026 * between each of those tags and the recreated SV.
3030 SV **ary = AvARRAY(av);
3032 for (i = 1; i <= len3; i++) { /* We leave [0] alone */
3037 READ(&tag, sizeof(I32));
3039 svh = av_fetch(cxt->aseen, tag, FALSE);
3041 CROAK(("Object #%d should have been retrieved already", tag));
3043 ary[i] = SvREFCNT_inc(xsv);
3048 * Bless the object and look up the STORABLE_thaw hook.
3052 hook = pkg_can(cxt->hook, SvSTASH(sv), "STORABLE_thaw");
3054 CROAK(("No STORABLE_thaw defined for objects of class %s", class));
3057 * If we don't have an `av' yet, prepare one.
3058 * Then insert the frozen string as item [0].
3066 AvARRAY(av)[0] = SvREFCNT_inc(frozen);
3071 * $object->STORABLE_thaw($cloning, $frozen, @refs);
3073 * where $object is our blessed (empty) object, $cloning is a boolean
3074 * telling whether we're running a deep clone, $frozen is the frozen
3075 * string the user gave us in his serializing hook, and @refs, which may
3076 * be empty, is the list of extra references he returned along for us
3079 * In effect, the hook is an alternate creation routine for the class,
3080 * the object itself being already created by the runtime.
3083 TRACEME(("calling STORABLE_thaw on %s at 0x%lx (%d args)",
3084 class, (unsigned long) sv, AvFILLp(av) + 1));
3087 (void) scalar_call(rv, hook, clone, av, G_SCALAR|G_DISCARD);
3094 SvREFCNT_dec(frozen);
3097 if (!(flags & SHF_IDX_CLASSNAME) && class != buf)
3106 * Retrieve reference to some other scalar.
3107 * Layout is SX_REF <object>, with SX_REF already read.
3109 static SV *retrieve_ref(cxt)
3115 TRACEME(("retrieve_ref (#%d)", cxt->tagnum));
3118 * We need to create the SV that holds the reference to the yet-to-retrieve
3119 * object now, so that we may record the address in the seen table.
3120 * Otherwise, if the object to retrieve references us, we won't be able
3121 * to resolve the SX_OBJECT we'll see at that point! Hence we cannot
3122 * do the retrieve first and use rv = newRV(sv) since it will be too late
3123 * for SEEN() recording.
3126 rv = NEWSV(10002, 0);
3127 SEEN(rv); /* Will return if rv is null */
3128 sv = retrieve(cxt); /* Retrieve <object> */
3130 return (SV *) 0; /* Failed */
3133 * WARNING: breaks RV encapsulation.
3135 * Now for the tricky part. We have to upgrade our existing SV, so that
3136 * it is now an RV on sv... Again, we cheat by duplicating the code
3137 * held in newSVrv(), since we already got our SV from retrieve().
3141 * SvRV(rv) = SvREFCNT_inc(sv);
3143 * here because the reference count we got from retrieve() above is
3144 * already correct: if the object was retrieved from the file, then
3145 * its reference count is one. Otherwise, if it was retrieved via
3146 * an SX_OBJECT indication, a ref count increment was done.
3149 sv_upgrade(rv, SVt_RV);
3150 SvRV(rv) = sv; /* $rv = \$sv */
3153 TRACEME(("ok (retrieve_ref at 0x%lx)", (unsigned long) rv));
3159 * retrieve_overloaded
3161 * Retrieve reference to some other scalar with overloading.
3162 * Layout is SX_OVERLOAD <object>, with SX_OVERLOAD already read.
3164 static SV *retrieve_overloaded(cxt)
3171 TRACEME(("retrieve_overloaded (#%d)", cxt->tagnum));
3174 * Same code as retrieve_ref(), duplicated to avoid extra call.
3177 rv = NEWSV(10002, 0);
3178 SEEN(rv); /* Will return if rv is null */
3179 sv = retrieve(cxt); /* Retrieve <object> */
3181 return (SV *) 0; /* Failed */
3184 * WARNING: breaks RV encapsulation.
3187 sv_upgrade(rv, SVt_RV);
3188 SvRV(rv) = sv; /* $rv = \$sv */
3192 * Restore overloading magic.
3195 stash = (HV *) SvSTASH (sv);
3196 if (!stash || !Gv_AMG(stash))
3197 CROAK(("Cannot restore overloading on %s(0x%lx)", sv_reftype(sv, FALSE),
3198 (unsigned long) sv));
3202 TRACEME(("ok (retrieve_overloaded at 0x%lx)", (unsigned long) rv));
3208 * retrieve_tied_array
3210 * Retrieve tied array
3211 * Layout is SX_TIED_ARRAY <object>, with SX_TIED_ARRAY already read.
3213 static SV *retrieve_tied_array(cxt)
3219 TRACEME(("retrieve_tied_array (#%d)", cxt->tagnum));
3221 tv = NEWSV(10002, 0);
3222 SEEN(tv); /* Will return if tv is null */
3223 sv = retrieve(cxt); /* Retrieve <object> */
3225 return (SV *) 0; /* Failed */
3227 sv_upgrade(tv, SVt_PVAV);
3228 AvREAL_off((AV *)tv);
3229 sv_magic(tv, sv, 'P', Nullch, 0);
3230 SvREFCNT_dec(sv); /* Undo refcnt inc from sv_magic() */
3232 TRACEME(("ok (retrieve_tied_array at 0x%lx)", (unsigned long) tv));
3238 * retrieve_tied_hash
3240 * Retrieve tied hash
3241 * Layout is SX_TIED_HASH <object>, with SX_TIED_HASH already read.
3243 static SV *retrieve_tied_hash(cxt)
3249 TRACEME(("retrieve_tied_hash (#%d)", cxt->tagnum));
3251 tv = NEWSV(10002, 0);
3252 SEEN(tv); /* Will return if tv is null */
3253 sv = retrieve(cxt); /* Retrieve <object> */
3255 return (SV *) 0; /* Failed */
3257 sv_upgrade(tv, SVt_PVHV);
3258 sv_magic(tv, sv, 'P', Nullch, 0);
3259 SvREFCNT_dec(sv); /* Undo refcnt inc from sv_magic() */
3261 TRACEME(("ok (retrieve_tied_hash at 0x%lx)", (unsigned long) tv));
3267 * retrieve_tied_scalar
3269 * Retrieve tied scalar
3270 * Layout is SX_TIED_SCALAR <object>, with SX_TIED_SCALAR already read.
3272 static SV *retrieve_tied_scalar(cxt)
3278 TRACEME(("retrieve_tied_scalar (#%d)", cxt->tagnum));
3280 tv = NEWSV(10002, 0);
3281 SEEN(tv); /* Will return if rv is null */
3282 sv = retrieve(cxt); /* Retrieve <object> */
3284 return (SV *) 0; /* Failed */
3286 sv_upgrade(tv, SVt_PVMG);
3287 sv_magic(tv, sv, 'q', Nullch, 0);
3288 SvREFCNT_dec(sv); /* Undo refcnt inc from sv_magic() */
3290 TRACEME(("ok (retrieve_tied_scalar at 0x%lx)", (unsigned long) tv));
3298 * Retrieve reference to value in a tied hash.
3299 * Layout is SX_TIED_KEY <object> <key>, with SX_TIED_KEY already read.
3301 static SV *retrieve_tied_key(cxt)
3308 TRACEME(("retrieve_tied_key (#%d)", cxt->tagnum));
3310 tv = NEWSV(10002, 0);
3311 SEEN(tv); /* Will return if tv is null */
3312 sv = retrieve(cxt); /* Retrieve <object> */
3314 return (SV *) 0; /* Failed */
3316 key = retrieve(cxt); /* Retrieve <key> */
3318 return (SV *) 0; /* Failed */
3320 sv_upgrade(tv, SVt_PVMG);
3321 sv_magic(tv, sv, 'p', (char *)key, HEf_SVKEY);
3322 SvREFCNT_dec(key); /* Undo refcnt inc from sv_magic() */
3323 SvREFCNT_dec(sv); /* Undo refcnt inc from sv_magic() */
3331 * Retrieve reference to value in a tied array.
3332 * Layout is SX_TIED_IDX <object> <idx>, with SX_TIED_IDX already read.
3334 static SV *retrieve_tied_idx(cxt)
3341 TRACEME(("retrieve_tied_idx (#%d)", cxt->tagnum));
3343 tv = NEWSV(10002, 0);
3344 SEEN(tv); /* Will return if tv is null */
3345 sv = retrieve(cxt); /* Retrieve <object> */
3347 return (SV *) 0; /* Failed */
3349 RLEN(idx); /* Retrieve <idx> */
3351 sv_upgrade(tv, SVt_PVMG);
3352 sv_magic(tv, sv, 'p', Nullch, idx);
3353 SvREFCNT_dec(sv); /* Undo refcnt inc from sv_magic() */
3362 * Retrieve defined long (string) scalar.
3364 * Layout is SX_LSCALAR <length> <data>, with SX_LSCALAR already read.
3365 * The scalar is "long" in that <length> is larger than LG_SCALAR so it
3366 * was not stored on a single byte.
3368 static SV *retrieve_lscalar(cxt)
3375 TRACEME(("retrieve_lscalar (#%d), len = %d", cxt->tagnum, len));
3378 * Allocate an empty scalar of the suitable length.
3381 sv = NEWSV(10002, len);
3382 SEEN(sv); /* Associate this new scalar with tag "tagnum" */
3385 * WARNING: duplicates parts of sv_setpv and breaks SV data encapsulation.
3387 * Now, for efficiency reasons, read data directly inside the SV buffer,
3388 * and perform the SV final settings directly by duplicating the final
3389 * work done by sv_setpv. Since we're going to allocate lots of scalars
3390 * this way, it's worth the hassle and risk.
3393 SAFEREAD(SvPVX(sv), len, sv);
3394 SvCUR_set(sv, len); /* Record C string length */
3395 *SvEND(sv) = '\0'; /* Ensure it's null terminated anyway */
3396 (void) SvPOK_only(sv); /* Validate string pointer */
3397 SvTAINT(sv); /* External data cannot be trusted */
3399 TRACEME(("large scalar len %d '%s'", len, SvPVX(sv)));
3400 TRACEME(("ok (retrieve_lscalar at 0x%lx)", (unsigned long) sv));
3408 * Retrieve defined short (string) scalar.
3410 * Layout is SX_SCALAR <length> <data>, with SX_SCALAR already read.
3411 * The scalar is "short" so <length> is single byte. If it is 0, there
3412 * is no <data> section.
3414 static SV *retrieve_scalar(cxt)
3421 TRACEME(("retrieve_scalar (#%d), len = %d", cxt->tagnum, len));
3424 * Allocate an empty scalar of the suitable length.
3427 sv = NEWSV(10002, len);
3428 SEEN(sv); /* Associate this new scalar with tag "tagnum" */
3431 * WARNING: duplicates parts of sv_setpv and breaks SV data encapsulation.
3436 * newSV did not upgrade to SVt_PV so the scalar is undefined.
3437 * To make it defined with an empty length, upgrade it now...
3439 sv_upgrade(sv, SVt_PV);
3441 *SvEND(sv) = '\0'; /* Ensure it's null terminated anyway */
3442 TRACEME(("ok (retrieve_scalar empty at 0x%lx)", (unsigned long) sv));
3445 * Now, for efficiency reasons, read data directly inside the SV buffer,
3446 * and perform the SV final settings directly by duplicating the final
3447 * work done by sv_setpv. Since we're going to allocate lots of scalars
3448 * this way, it's worth the hassle and risk.
3450 SAFEREAD(SvPVX(sv), len, sv);
3451 SvCUR_set(sv, len); /* Record C string length */
3452 *SvEND(sv) = '\0'; /* Ensure it's null terminated anyway */
3453 TRACEME(("small scalar len %d '%s'", len, SvPVX(sv)));
3456 (void) SvPOK_only(sv); /* Validate string pointer */
3457 SvTAINT(sv); /* External data cannot be trusted */
3459 TRACEME(("ok (retrieve_scalar at 0x%lx)", (unsigned long) sv));
3466 * Retrieve defined integer.
3467 * Layout is SX_INTEGER <data>, whith SX_INTEGER already read.
3469 static SV *retrieve_integer(cxt)
3475 TRACEME(("retrieve_integer (#%d)", cxt->tagnum));
3477 READ(&iv, sizeof(iv));
3479 SEEN(sv); /* Associate this new scalar with tag "tagnum" */
3481 TRACEME(("integer %d", iv));
3482 TRACEME(("ok (retrieve_integer at 0x%lx)", (unsigned long) sv));
3490 * Retrieve defined integer in network order.
3491 * Layout is SX_NETINT <data>, whith SX_NETINT already read.
3493 static SV *retrieve_netint(cxt)
3499 TRACEME(("retrieve_netint (#%d)", cxt->tagnum));
3501 READ(&iv, sizeof(iv));
3503 sv = newSViv((int) ntohl(iv));
3504 TRACEME(("network integer %d", (int) ntohl(iv)));
3507 TRACEME(("network integer (as-is) %d", iv));
3509 SEEN(sv); /* Associate this new scalar with tag "tagnum" */
3511 TRACEME(("ok (retrieve_netint at 0x%lx)", (unsigned long) sv));
3519 * Retrieve defined double.
3520 * Layout is SX_DOUBLE <data>, whith SX_DOUBLE already read.
3522 static SV *retrieve_double(cxt)
3528 TRACEME(("retrieve_double (#%d)", cxt->tagnum));
3530 READ(&nv, sizeof(nv));
3532 SEEN(sv); /* Associate this new scalar with tag "tagnum" */
3534 TRACEME(("double %lf", nv));
3535 TRACEME(("ok (retrieve_double at 0x%lx)", (unsigned long) sv));
3543 * Retrieve defined byte (small integer within the [-128, +127] range).
3544 * Layout is SX_BYTE <data>, whith SX_BYTE already read.
3546 static SV *retrieve_byte(cxt)
3552 TRACEME(("retrieve_byte (#%d)", cxt->tagnum));
3555 TRACEME(("small integer read as %d", (unsigned char) siv));
3556 sv = newSViv((unsigned char) siv - 128);
3557 SEEN(sv); /* Associate this new scalar with tag "tagnum" */
3559 TRACEME(("byte %d", (unsigned char) siv - 128));
3560 TRACEME(("ok (retrieve_byte at 0x%lx)", (unsigned long) sv));
3568 * Return the undefined value.
3570 static SV *retrieve_undef(cxt)
3575 TRACEME(("retrieve_undef"));
3586 * Return the immortal undefined value.
3588 static SV *retrieve_sv_undef(cxt)
3591 SV *sv = &PL_sv_undef;
3593 TRACEME(("retrieve_sv_undef"));
3602 * Return the immortal yes value.
3604 static SV *retrieve_sv_yes(cxt)
3607 SV *sv = &PL_sv_yes;
3609 TRACEME(("retrieve_sv_yes"));
3618 * Return the immortal no value.
3620 static SV *retrieve_sv_no(cxt)
3625 TRACEME(("retrieve_sv_no"));
3634 * Retrieve a whole array.
3635 * Layout is SX_ARRAY <size> followed by each item, in increading index order.
3636 * Each item is stored as <object>.
3638 * When we come here, SX_ARRAY has been read already.
3640 static SV *retrieve_array(cxt)
3648 TRACEME(("retrieve_array (#%d)", cxt->tagnum));
3651 * Read length, and allocate array, then pre-extend it.
3655 TRACEME(("size = %d", len));
3657 SEEN(av); /* Will return if array not allocated nicely */
3661 return (SV *) av; /* No data follow if array is empty */
3664 * Now get each item in turn...
3667 for (i = 0; i < len; i++) {
3668 TRACEME(("(#%d) item", i));
3669 sv = retrieve(cxt); /* Retrieve item */
3672 if (av_store(av, i, sv) == 0)
3676 TRACEME(("ok (retrieve_array at 0x%lx)", (unsigned long) av));
3684 * Retrieve a whole hash table.
3685 * Layout is SX_HASH <size> followed by each key/value pair, in random order.
3686 * Keys are stored as <length> <data>, the <data> section being omitted
3688 * Values are stored as <object>.
3690 * When we come here, SX_HASH has been read already.
3692 static SV *retrieve_hash(cxt)
3700 static SV *sv_h_undef = (SV *) 0; /* hv_store() bug */
3702 TRACEME(("retrieve_hash (#%d)", cxt->tagnum));
3705 * Read length, allocate table.
3709 TRACEME(("size = %d", len));
3711 SEEN(hv); /* Will return if table not allocated properly */
3713 return (SV *) hv; /* No data follow if table empty */
3716 * Now get each key/value pair in turn...
3719 for (i = 0; i < len; i++) {
3724 TRACEME(("(#%d) value", i));
3731 * Since we're reading into kbuf, we must ensure we're not
3732 * recursing between the read and the hv_store() where it's used.
3733 * Hence the key comes after the value.
3736 RLEN(size); /* Get key size */
3737 KBUFCHK(size); /* Grow hash key read pool if needed */
3740 kbuf[size] = '\0'; /* Mark string end, just in case */
3741 TRACEME(("(#%d) key '%s'", i, kbuf));
3744 * Enter key/value pair into hash table.
3747 if (hv_store(hv, kbuf, (U32) size, sv, 0) == 0)
3751 TRACEME(("ok (retrieve_hash at 0x%lx)", (unsigned long) hv));
3757 * old_retrieve_array
3759 * Retrieve a whole array in pre-0.6 binary format.
3761 * Layout is SX_ARRAY <size> followed by each item, in increading index order.
3762 * Each item is stored as SX_ITEM <object> or SX_IT_UNDEF for "holes".
3764 * When we come here, SX_ARRAY has been read already.
3766 static SV *old_retrieve_array(cxt)
3775 TRACEME(("old_retrieve_array (#%d)", cxt->tagnum));
3778 * Read length, and allocate array, then pre-extend it.
3782 TRACEME(("size = %d", len));
3784 SEEN(av); /* Will return if array not allocated nicely */
3788 return (SV *) av; /* No data follow if array is empty */
3791 * Now get each item in turn...
3794 for (i = 0; i < len; i++) {
3796 if (c == SX_IT_UNDEF) {
3797 TRACEME(("(#%d) undef item", i));
3798 continue; /* av_extend() already filled us with undef */
3801 (void) retrieve_other(0); /* Will croak out */
3802 TRACEME(("(#%d) item", i));
3803 sv = retrieve(cxt); /* Retrieve item */
3806 if (av_store(av, i, sv) == 0)
3810 TRACEME(("ok (old_retrieve_array at 0x%lx)", (unsigned long) av));
3818 * Retrieve a whole hash table in pre-0.6 binary format.
3820 * Layout is SX_HASH <size> followed by each key/value pair, in random order.
3821 * Keys are stored as SX_KEY <length> <data>, the <data> section being omitted
3823 * Values are stored as SX_VALUE <object> or SX_VL_UNDEF for "holes".
3825 * When we come here, SX_HASH has been read already.
3827 static SV *old_retrieve_hash(cxt)
3836 static SV *sv_h_undef = (SV *) 0; /* hv_store() bug */
3838 TRACEME(("old_retrieve_hash (#%d)", cxt->tagnum));
3841 * Read length, allocate table.
3845 TRACEME(("size = %d", len));
3847 SEEN(hv); /* Will return if table not allocated properly */
3849 return (SV *) hv; /* No data follow if table empty */
3852 * Now get each key/value pair in turn...
3855 for (i = 0; i < len; i++) {
3861 if (c == SX_VL_UNDEF) {
3862 TRACEME(("(#%d) undef value", i));
3864 * Due to a bug in hv_store(), it's not possible to pass
3865 * &PL_sv_undef to hv_store() as a value, otherwise the
3866 * associated key will not be creatable any more. -- RAM, 14/01/97
3869 sv_h_undef = newSVsv(&PL_sv_undef);
3870 sv = SvREFCNT_inc(sv_h_undef);
3871 } else if (c == SX_VALUE) {
3872 TRACEME(("(#%d) value", i));
3877 (void) retrieve_other(0); /* Will croak out */
3881 * Since we're reading into kbuf, we must ensure we're not
3882 * recursing between the read and the hv_store() where it's used.
3883 * Hence the key comes after the value.
3888 (void) retrieve_other(0); /* Will croak out */
3889 RLEN(size); /* Get key size */
3890 KBUFCHK(size); /* Grow hash key read pool if needed */
3893 kbuf[size] = '\0'; /* Mark string end, just in case */
3894 TRACEME(("(#%d) key '%s'", i, kbuf));
3897 * Enter key/value pair into hash table.
3900 if (hv_store(hv, kbuf, (U32) size, sv, 0) == 0)
3904 TRACEME(("ok (retrieve_hash at 0x%lx)", (unsigned long) hv));
3910 *** Retrieval engine.
3916 * Make sure the stored data we're trying to retrieve has been produced
3917 * on an ILP compatible system with the same byteorder. It croaks out in
3918 * case an error is detected. [ILP = integer-long-pointer sizes]
3919 * Returns null if error is detected, &PL_sv_undef otherwise.
3921 * Note that there's no byte ordering info emitted when network order was
3922 * used at store time.
3924 static SV *magic_check(cxt)
3928 char byteorder[256];
3930 int use_network_order;
3932 int version_minor = 0;
3934 TRACEME(("magic_check"));
3937 * The "magic number" is only for files, not when freezing in memory.
3941 STRLEN len = sizeof(magicstr) - 1;
3944 READ(buf, len); /* Not null-terminated */
3945 buf[len] = '\0'; /* Is now */
3947 if (0 == strcmp(buf, magicstr))
3951 * Try to read more bytes to check for the old magic number, which
3955 old_len = sizeof(old_magicstr) - 1;
3956 READ(&buf[len], old_len - len);
3957 buf[old_len] = '\0'; /* Is now null-terminated */
3959 if (strcmp(buf, old_magicstr))
3960 CROAK(("File is not a perl storable"));
3965 * Starting with 0.6, the "use_network_order" byte flag is also used to
3966 * indicate the version number of the binary, and therefore governs the
3967 * setting of sv_retrieve_vtbl. See magic_write().
3970 GETMARK(use_network_order);
3971 version_major = use_network_order >> 1;
3972 cxt->retrieve_vtbl = version_major ? sv_retrieve : sv_old_retrieve;
3974 TRACEME(("magic_check: netorder = 0x%x", use_network_order));
3978 * Starting with 0.7 (binary major 2), a full byte is dedicated to the
3979 * minor version of the protocol. See magic_write().
3982 if (version_major > 1)
3983 GETMARK(version_minor);
3985 cxt->ver_major = version_major;
3986 cxt->ver_minor = version_minor;
3988 TRACEME(("binary image version is %d.%d", version_major, version_minor));
3991 * Inter-operability sanity check: we can't retrieve something stored
3992 * using a format more recent than ours, because we have no way to
3993 * know what has changed, and letting retrieval go would mean a probable
3994 * failure reporting a "corrupted" storable file.
3998 version_major > STORABLE_BIN_MAJOR ||
3999 (version_major == STORABLE_BIN_MAJOR &&
4000 version_minor > STORABLE_BIN_MINOR)
4002 CROAK(("Storable binary image v%d.%d more recent than I am (v%d.%d)",
4003 version_major, version_minor,
4004 STORABLE_BIN_MAJOR, STORABLE_BIN_MINOR));
4007 * If they stored using network order, there's no byte ordering
4008 * information to check.
4011 if (cxt->netorder = (use_network_order & 0x1))
4012 return &PL_sv_undef; /* No byte ordering info */
4014 sprintf(byteorder, "%lx", (unsigned long) BYTEORDER);
4016 READ(buf, c); /* Not null-terminated */
4017 buf[c] = '\0'; /* Is now */
4019 if (strcmp(buf, byteorder))
4020 CROAK(("Byte order is not compatible"));
4022 GETMARK(c); /* sizeof(int) */
4023 if ((int) c != sizeof(int))
4024 CROAK(("Integer size is not compatible"));
4026 GETMARK(c); /* sizeof(long) */
4027 if ((int) c != sizeof(long))
4028 CROAK(("Long integer size is not compatible"));
4030 GETMARK(c); /* sizeof(char *) */
4031 if ((int) c != sizeof(char *))
4032 CROAK(("Pointer integer size is not compatible"));
4034 return &PL_sv_undef; /* OK */
4040 * Recursively retrieve objects from the specified file and return their
4041 * root SV (which may be an AV or an HV for what we care).
4042 * Returns null if there is a problem.
4044 static SV *retrieve(cxt)
4051 TRACEME(("retrieve"));
4054 * Grab address tag which identifies the object if we are retrieving
4055 * an older format. Since the new binary format counts objects and no
4056 * longer explicitely tags them, we must keep track of the correspondance
4059 * The following section will disappear one day when the old format is
4060 * no longer supported, hence the final "goto" in the "if" block.
4063 if (cxt->hseen) { /* Retrieving old binary */
4065 if (cxt->netorder) {
4067 READ(&nettag, sizeof(I32)); /* Ordered sequence of I32 */
4068 tag = (stag_t) nettag;
4070 READ(&tag, sizeof(stag_t)); /* Original address of the SV */
4073 if (type == SX_OBJECT) {
4075 svh = hv_fetch(cxt->hseen, (char *) &tag, sizeof(tag), FALSE);
4077 CROAK(("Old tag 0x%x should have been mapped already", tag));
4078 tagn = SvIV(*svh); /* Mapped tag number computed earlier below */
4081 * The following code is common with the SX_OBJECT case below.
4084 svh = av_fetch(cxt->aseen, tagn, FALSE);
4086 CROAK(("Object #%d should have been retrieved already", tagn));
4088 TRACEME(("has retrieved #%d at 0x%lx", tagn, (unsigned long) sv));
4089 SvREFCNT_inc(sv); /* One more reference to this same sv */
4090 return sv; /* The SV pointer where object was retrieved */
4094 * Map new object, but don't increase tagnum. This will be done
4095 * by each of the retrieve_* functions when they call SEEN().
4097 * The mapping associates the "tag" initially present with a unique
4098 * tag number. See test for SX_OBJECT above to see how this is perused.
4101 if (!hv_store(cxt->hseen, (char *) &tag, sizeof(tag),
4102 newSViv(cxt->tagnum), 0))
4109 * Regular post-0.6 binary format.
4115 TRACEME(("retrieve type = %d", type));
4118 * Are we dealing with an object we should have already retrieved?
4121 if (type == SX_OBJECT) {
4123 READ(&tag, sizeof(I32));
4125 svh = av_fetch(cxt->aseen, tag, FALSE);
4127 CROAK(("Object #%d should have been retrieved already", tag));
4129 TRACEME(("had retrieved #%d at 0x%lx", tag, (unsigned long) sv));
4130 SvREFCNT_inc(sv); /* One more reference to this same sv */
4131 return sv; /* The SV pointer where object was retrieved */
4134 first_time: /* Will disappear when support for old format is dropped */
4137 * Okay, first time through for this one.
4140 sv = RETRIEVE(cxt, type)(cxt);
4142 return (SV *) 0; /* Failed */
4145 * Old binary formats (pre-0.7).
4147 * Final notifications, ended by SX_STORED may now follow.
4148 * Currently, the only pertinent notification to apply on the
4149 * freshly retrieved object is either:
4150 * SX_CLASS <char-len> <classname> for short classnames.
4151 * SX_LG_CLASS <int-len> <classname> for larger one (rare!).
4152 * Class name is then read into the key buffer pool used by
4153 * hash table key retrieval.
4156 if (cxt->ver_major < 2) {
4157 while ((type = GETCHAR()) != SX_STORED) {
4161 GETMARK(len); /* Length coded on a single char */
4163 case SX_LG_CLASS: /* Length coded on a regular integer */
4168 return (SV *) 0; /* Failed */
4170 KBUFCHK(len); /* Grow buffer as necessary */
4173 kbuf[len] = '\0'; /* Mark string end */
4178 TRACEME(("ok (retrieved 0x%lx, refcnt=%d, %s)", (unsigned long) sv,
4179 SvREFCNT(sv) - 1, sv_reftype(sv, FALSE)));
4187 * Retrieve data held in file and return the root object.
4188 * Common routine for pretrieve and mretrieve.
4190 static SV *do_retrieve(f, in, optype)
4197 struct extendable msave; /* Where potentially valid mbuf is saved */
4199 TRACEME(("do_retrieve (optype = 0x%x)", optype));
4201 optype |= ST_RETRIEVE;
4204 * Sanity assertions for retrieve dispatch tables.
4207 ASSERT(sizeof(sv_old_retrieve) == sizeof(sv_retrieve),
4208 ("old and new retrieve dispatch table have same size"));
4209 ASSERT(sv_old_retrieve[SX_ERROR] == retrieve_other,
4210 ("SX_ERROR entry correctly initialized in old dispatch table"));
4211 ASSERT(sv_retrieve[SX_ERROR] == retrieve_other,
4212 ("SX_ERROR entry correctly initialized in new dispatch table"));
4215 * Workaround for CROAK leak: if they enter with a "dirty" context,
4216 * free up memory for them now.
4223 * Now that STORABLE_xxx hooks exist, it is possible that they try to
4224 * re-enter retrieve() via the hooks.
4228 cxt = allocate_context(cxt);
4232 ASSERT(cxt->entry == 1, ("starting new recursion"));
4233 ASSERT(!cxt->dirty, ("clean context"));
4238 * Data is loaded into the memory buffer when f is NULL, unless `in' is
4239 * also NULL, in which case we're expecting the data to already lie
4240 * in the buffer (dclone case).
4243 KBUFINIT(); /* Allocate hash key reading pool once */
4246 StructCopy(&cxt->membuf, &msave, struct extendable);
4252 * Magic number verifications.
4254 * This needs to be done before calling init_retrieve_context()
4255 * since the format indication in the file are necessary to conduct
4256 * some of the initializations.
4259 cxt->fio = f; /* Where I/O are performed */
4261 if (!magic_check(cxt))
4262 CROAK(("Magic number checking on storable %s failed",
4263 cxt->fio ? "file" : "string"));
4265 TRACEME(("data stored in %s format",
4266 cxt->netorder ? "net order" : "native"));
4268 init_retrieve_context(cxt, optype);
4270 ASSERT(is_retrieving(), ("within retrieve operation"));
4272 sv = retrieve(cxt); /* Recursively retrieve object, get root SV */
4279 StructCopy(&msave, &cxt->membuf, struct extendable);
4282 * The "root" context is never freed.
4285 clean_retrieve_context(cxt);
4286 if (cxt->prev) /* This context was stacked */
4287 free_context(cxt); /* It was not the "root" context */
4290 * Prepare returned value.
4294 TRACEME(("retrieve ERROR"));
4295 return &PL_sv_undef; /* Something went wrong, return undef */
4298 TRACEME(("retrieve got %s(0x%lx)",
4299 sv_reftype(sv, FALSE), (unsigned long) sv));
4302 * Backward compatibility with Storable-0.5@9 (which we know we
4303 * are retrieving if hseen is non-null): don't create an extra RV
4304 * for objects since we special-cased it at store time.
4306 * Build a reference to the SV returned by pretrieve even if it is
4307 * already one and not a scalar, for consistency reasons.
4309 * NB: although context might have been cleaned, the value of `cxt->hseen'
4310 * remains intact, and can be used as a flag.
4313 if (cxt->hseen) { /* Was not handling overloading by then */
4315 if (sv_type(sv) == svis_REF && (rv = SvRV(sv)) && SvOBJECT(rv))
4320 * If reference is overloaded, restore behaviour.
4322 * NB: minor glitch here: normally, overloaded refs are stored specially
4323 * so that we can croak when behaviour cannot be re-installed, and also
4324 * avoid testing for overloading magic at each reference retrieval.
4326 * Unfortunately, the root reference is implicitely stored, so we must
4327 * check for possible overloading now. Furthermore, if we don't restore
4328 * overloading, we cannot croak as if the original ref was, because we
4329 * have no way to determine whether it was an overloaded ref or not in
4332 * It's a pity that overloading magic is attached to the rv, and not to
4333 * the underlying sv as blessing is.
4337 HV *stash = (HV *) SvSTASH (sv);
4338 SV *rv = newRV_noinc(sv);
4339 if (stash && Gv_AMG(stash)) {
4341 TRACEME(("restored overloading on root reference"));
4346 return newRV_noinc(sv);
4352 * Retrieve data held in file and return the root object, undef on error.
4357 TRACEME(("pretrieve"));
4358 return do_retrieve(f, Nullsv, 0);
4364 * Retrieve data held in scalar and return the root object, undef on error.
4369 TRACEME(("mretrieve"));
4370 return do_retrieve((PerlIO*)0, sv, 0);
4380 * Deep clone: returns a fresh copy of the original referenced SV tree.
4382 * This is achieved by storing the object in memory and restoring from
4383 * there. Not that efficient, but it should be faster than doing it from
4391 stcxt_t *real_context;
4394 TRACEME(("dclone"));
4397 * Workaround for CROAK leak: if they enter with a "dirty" context,
4398 * free up memory for them now.
4405 * do_store() optimizes for dclone by not freeing its context, should
4406 * we need to allocate one because we're deep cloning from a hook.
4409 if (!do_store((PerlIO*)0, sv, ST_CLONE, FALSE, (SV**)0))
4410 return &PL_sv_undef; /* Error during store */
4413 * Because of the above optimization, we have to refresh the context,
4414 * since a new one could have been allocated and stacked by do_store().
4417 { dSTCXT; real_context = cxt; } /* Sub-block needed for macro */
4418 cxt = real_context; /* And we need this temporary... */
4421 * Now, `cxt' may refer to a new context.
4424 ASSERT(!cxt->dirty, ("clean context"));
4425 ASSERT(!cxt->entry, ("entry will not cause new context allocation"));
4428 TRACEME(("dclone stored %d bytes", size));
4431 out = do_retrieve((PerlIO*)0, Nullsv, ST_CLONE); /* Will free non-root context */
4433 TRACEME(("dclone returns 0x%lx", (unsigned long) out));
4443 * The Perl IO GV object distinguishes between input and output for sockets
4444 * but not for plain files. To allow Storable to transparently work on
4445 * plain files and sockets transparently, we have to ask xsubpp to fetch the
4446 * right object for us. Hence the OutputStream and InputStream declarations.
4448 * Before perl 5.004_05, those entries in the standard typemap are not
4449 * defined in perl include files, so we do that here.
4452 #ifndef OutputStream
4453 #define OutputStream PerlIO *
4454 #define InputStream PerlIO *
4455 #endif /* !OutputStream */
4457 MODULE = Storable PACKAGE = Storable
4495 last_op_in_netorder()