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 #if BYTEORDER == 0x87654321
437 #define LOW_32BITS(x) ((I32) ((unsigned long) (x) & 0xffffffff00000000UL))
438 #else /* BYTEORDER == 0x12345678 */
439 #define LOW_32BITS(x) ((I32) ((unsigned long) (x) & 0xffffffffUL))
444 * Possible return values for sv_type().
448 #define svis_SCALAR 1
452 #define svis_TIED_ITEM 5
459 #define SHF_TYPE_MASK 0x03
460 #define SHF_LARGE_CLASSLEN 0x04
461 #define SHF_LARGE_STRLEN 0x08
462 #define SHF_LARGE_LISTLEN 0x10
463 #define SHF_IDX_CLASSNAME 0x20
464 #define SHF_NEED_RECURSE 0x40
465 #define SHF_HAS_LIST 0x80
468 * Types for SX_HOOK (2 bits).
476 * Before 0.6, the magic string was "perl-store" (binary version number 0).
478 * Since 0.6 introduced many binary incompatibilities, the magic string has
479 * been changed to "pst0" to allow an old image to be properly retrieved by
480 * a newer Storable, but ensure a newer image cannot be retrieved with an
483 * At 0.7, objects are given the ability to serialize themselves, and the
484 * set of markers is extended, backward compatibility is not jeopardized,
485 * so the binary version number could have remained unchanged. To correctly
486 * spot errors if a file making use of 0.7-specific extensions is given to
487 * 0.6 for retrieval, the binary version was moved to "2". And I'm introducing
488 * a "minor" version, to better track this kind of evolution from now on.
491 static char old_magicstr[] = "perl-store"; /* Magic number before 0.6 */
492 static char magicstr[] = "pst0"; /* Used as a magic number */
494 #define STORABLE_BIN_MAJOR 2 /* Binary major "version" */
495 #define STORABLE_BIN_MINOR 1 /* Binary minor "version" */
498 * Useful store shortcuts...
501 #define PUTMARK(x) do { \
504 else if (PerlIO_putc(cxt->fio, x) == EOF) \
509 #define WLEN(x) do { \
510 if (cxt->netorder) { \
511 int y = (int) htonl(x); \
514 else if (PerlIO_write(cxt->fio, &y, sizeof(y)) != sizeof(y)) \
519 else if (PerlIO_write(cxt->fio, &x, sizeof(x)) != sizeof(x)) \
524 #define WLEN(x) do { \
527 else if (PerlIO_write(cxt->fio, &x, sizeof(x)) != sizeof(x)) \
532 #define WRITE(x,y) do { \
535 else if (PerlIO_write(cxt->fio, x, y) != y) \
539 #define STORE_SCALAR(pv, len) do { \
540 if (len <= LG_SCALAR) { \
541 unsigned char clen = (unsigned char) len; \
542 PUTMARK(SX_SCALAR); \
547 PUTMARK(SX_LSCALAR); \
554 * Store undef in arrays and hashes without recursing through store().
556 #define STORE_UNDEF() do { \
562 * Useful retrieve shortcuts...
566 (cxt->fio ? PerlIO_getc(cxt->fio) : (mptr >= mend ? EOF : (int) *mptr++))
568 #define GETMARK(x) do { \
571 else if ((x = PerlIO_getc(cxt->fio)) == EOF) \
576 #define RLEN(x) do { \
579 else if (PerlIO_read(cxt->fio, &x, sizeof(x)) != sizeof(x)) \
582 x = (int) ntohl(x); \
585 #define RLEN(x) do { \
588 else if (PerlIO_read(cxt->fio, &x, sizeof(x)) != sizeof(x)) \
593 #define READ(x,y) do { \
596 else if (PerlIO_read(cxt->fio, x, y) != y) \
600 #define SAFEREAD(x,y,z) do { \
602 MBUF_SAFEREAD(x,y,z); \
603 else if (PerlIO_read(cxt->fio, x, y) != y) { \
610 * This macro is used at retrieve time, to remember where object 'y', bearing a
611 * given tag 'tagnum', has been retrieved. Next time we see an SX_OBJECT marker,
612 * we'll therefore know where it has been retrieved and will be able to
613 * share the same reference, as in the original stored memory image.
615 #define SEEN(y) do { \
618 if (av_store(cxt->aseen, cxt->tagnum++, SvREFCNT_inc(y)) == 0) \
620 TRACEME(("aseen(#%d) = 0x%lx (refcnt=%d)", cxt->tagnum-1, \
621 (unsigned long) y, SvREFCNT(y)-1)); \
625 * Bless `s' in `p', via a temporary reference, required by sv_bless().
627 #define BLESS(s,p) do { \
630 TRACEME(("blessing 0x%lx in %s", (unsigned long) (s), (p))); \
631 stash = gv_stashpv((p), TRUE); \
632 ref = newRV_noinc(s); \
633 (void) sv_bless(ref, stash); \
639 static SV *retrieve();
642 * Dynamic dispatching table for SV store.
645 static int store_ref(stcxt_t *cxt, SV *sv);
646 static int store_scalar(stcxt_t *cxt, SV *sv);
647 static int store_array(stcxt_t *cxt, AV *av);
648 static int store_hash(stcxt_t *cxt, HV *hv);
649 static int store_tied(stcxt_t *cxt, SV *sv);
650 static int store_tied_item(stcxt_t *cxt, SV *sv);
651 static int store_other(stcxt_t *cxt, SV *sv);
653 static int (*sv_store[])() = {
654 store_ref, /* svis_REF */
655 store_scalar, /* svis_SCALAR */
656 store_array, /* svis_ARRAY */
657 store_hash, /* svis_HASH */
658 store_tied, /* svis_TIED */
659 store_tied_item, /* svis_TIED_ITEM */
660 store_other, /* svis_OTHER */
663 #define SV_STORE(x) (*sv_store[x])
666 * Dynamic dispatching tables for SV retrieval.
669 static SV *retrieve_lscalar(stcxt_t *cxt);
670 static SV *old_retrieve_array(stcxt_t *cxt);
671 static SV *old_retrieve_hash(stcxt_t *cxt);
672 static SV *retrieve_ref(stcxt_t *cxt);
673 static SV *retrieve_undef(stcxt_t *cxt);
674 static SV *retrieve_integer(stcxt_t *cxt);
675 static SV *retrieve_double(stcxt_t *cxt);
676 static SV *retrieve_byte(stcxt_t *cxt);
677 static SV *retrieve_netint(stcxt_t *cxt);
678 static SV *retrieve_scalar(stcxt_t *cxt);
679 static SV *retrieve_tied_array(stcxt_t *cxt);
680 static SV *retrieve_tied_hash(stcxt_t *cxt);
681 static SV *retrieve_tied_scalar(stcxt_t *cxt);
682 static SV *retrieve_other(stcxt_t *cxt);
684 static SV *(*sv_old_retrieve[])() = {
685 0, /* SX_OBJECT -- entry unused dynamically */
686 retrieve_lscalar, /* SX_LSCALAR */
687 old_retrieve_array, /* SX_ARRAY -- for pre-0.6 binaries */
688 old_retrieve_hash, /* SX_HASH -- for pre-0.6 binaries */
689 retrieve_ref, /* SX_REF */
690 retrieve_undef, /* SX_UNDEF */
691 retrieve_integer, /* SX_INTEGER */
692 retrieve_double, /* SX_DOUBLE */
693 retrieve_byte, /* SX_BYTE */
694 retrieve_netint, /* SX_NETINT */
695 retrieve_scalar, /* SX_SCALAR */
696 retrieve_tied_array, /* SX_ARRAY */
697 retrieve_tied_hash, /* SX_HASH */
698 retrieve_tied_scalar, /* SX_SCALAR */
699 retrieve_other, /* SX_SV_UNDEF not supported */
700 retrieve_other, /* SX_SV_YES not supported */
701 retrieve_other, /* SX_SV_NO not supported */
702 retrieve_other, /* SX_BLESS not supported */
703 retrieve_other, /* SX_IX_BLESS not supported */
704 retrieve_other, /* SX_HOOK not supported */
705 retrieve_other, /* SX_OVERLOADED not supported */
706 retrieve_other, /* SX_TIED_KEY not supported */
707 retrieve_other, /* SX_TIED_IDX not supported */
708 retrieve_other, /* SX_ERROR */
711 static SV *retrieve_array(stcxt_t *cxt);
712 static SV *retrieve_hash(stcxt_t *cxt);
713 static SV *retrieve_sv_undef(stcxt_t *cxt);
714 static SV *retrieve_sv_yes(stcxt_t *cxt);
715 static SV *retrieve_sv_no(stcxt_t *cxt);
716 static SV *retrieve_blessed(stcxt_t *cxt);
717 static SV *retrieve_idx_blessed(stcxt_t *cxt);
718 static SV *retrieve_hook(stcxt_t *cxt);
719 static SV *retrieve_overloaded(stcxt_t *cxt);
720 static SV *retrieve_tied_key(stcxt_t *cxt);
721 static SV *retrieve_tied_idx(stcxt_t *cxt);
723 static SV *(*sv_retrieve[])() = {
724 0, /* SX_OBJECT -- entry unused dynamically */
725 retrieve_lscalar, /* SX_LSCALAR */
726 retrieve_array, /* SX_ARRAY */
727 retrieve_hash, /* SX_HASH */
728 retrieve_ref, /* SX_REF */
729 retrieve_undef, /* SX_UNDEF */
730 retrieve_integer, /* SX_INTEGER */
731 retrieve_double, /* SX_DOUBLE */
732 retrieve_byte, /* SX_BYTE */
733 retrieve_netint, /* SX_NETINT */
734 retrieve_scalar, /* SX_SCALAR */
735 retrieve_tied_array, /* SX_ARRAY */
736 retrieve_tied_hash, /* SX_HASH */
737 retrieve_tied_scalar, /* SX_SCALAR */
738 retrieve_sv_undef, /* SX_SV_UNDEF */
739 retrieve_sv_yes, /* SX_SV_YES */
740 retrieve_sv_no, /* SX_SV_NO */
741 retrieve_blessed, /* SX_BLESS */
742 retrieve_idx_blessed, /* SX_IX_BLESS */
743 retrieve_hook, /* SX_HOOK */
744 retrieve_overloaded, /* SX_OVERLOAD */
745 retrieve_tied_key, /* SX_TIED_KEY */
746 retrieve_tied_idx, /* SX_TIED_IDX */
747 retrieve_other, /* SX_ERROR */
750 #define RETRIEVE(c,x) (*(c)->retrieve_vtbl[(x) >= SX_ERROR ? SX_ERROR : (x)])
752 static SV *mbuf2sv();
753 static int store_blessed();
756 *** Context management.
762 * Called once per "thread" (interpreter) to initialize some global context.
764 static void init_perinterp() {
767 cxt->netorder = 0; /* true if network order used */
768 cxt->forgive_me = -1; /* whether to be forgiving... */
774 * Initialize a new store context for real recursion.
776 static void init_store_context(cxt, f, optype, network_order)
782 TRACEME(("init_store_context"));
784 cxt->netorder = network_order;
785 cxt->forgive_me = -1; /* Fetched from perl if needed */
786 cxt->canonical = -1; /* Idem */
787 cxt->tagnum = -1; /* Reset tag numbers */
788 cxt->classnum = -1; /* Reset class numbers */
789 cxt->fio = f; /* Where I/O are performed */
790 cxt->optype = optype; /* A store, or a deep clone */
791 cxt->entry = 1; /* No recursion yet */
794 * The `hseen' table is used to keep track of each SV stored and their
795 * associated tag numbers is special. It is "abused" because the
796 * values stored are not real SV, just integers cast to (SV *),
797 * which explains the freeing below.
799 * It is also one possible bottlneck to achieve good storing speed,
800 * so the "shared keys" optimization is turned off (unlikely to be
801 * of any use here), and the hash table is "pre-extended". Together,
802 * those optimizations increase the throughput by 12%.
805 cxt->hseen = newHV(); /* Table where seen objects are stored */
806 HvSHAREKEYS_off(cxt->hseen);
809 * The following does not work well with perl5.004_04, and causes
810 * a core dump later on, in a completely unrelated spot, which
811 * makes me think there is a memory corruption going on.
813 * Calling hv_ksplit(hseen, HBUCKETS) instead of manually hacking
814 * it below does not make any difference. It seems to work fine
815 * with perl5.004_68 but given the probable nature of the bug,
816 * that does not prove anything.
818 * It's a shame because increasing the amount of buckets raises
819 * store() throughput by 5%, but until I figure this out, I can't
820 * allow for this to go into production.
822 * It is reported fixed in 5.005, hence the #if.
825 #define HBUCKETS 4096 /* Buckets for %hseen */
826 HvMAX(cxt->hseen) = HBUCKETS - 1; /* keys %hseen = $HBUCKETS; */
830 * The `hclass' hash uses the same settings as `hseen' above, but it is
831 * used to assign sequential tags (numbers) to class names for blessed
834 * We turn the shared key optimization on.
837 cxt->hclass = newHV(); /* Where seen classnames are stored */
840 HvMAX(cxt->hclass) = HBUCKETS - 1; /* keys %hclass = $HBUCKETS; */
844 * The `hook' hash table is used to keep track of the references on
845 * the STORABLE_freeze hook routines, when found in some class name.
847 * It is assumed that the inheritance tree will not be changed during
848 * storing, and that no new method will be dynamically created by the
852 cxt->hook = newHV(); /* Table where hooks are cached */
856 * clean_store_context
858 * Clean store context by
860 static void clean_store_context(cxt)
865 TRACEME(("clean_store_context"));
867 ASSERT(cxt->optype & ST_STORE, ("was performing a store()"));
870 * Insert real values into hashes where we stored faked pointers.
873 hv_iterinit(cxt->hseen);
874 while (he = hv_iternext(cxt->hseen))
875 HeVAL(he) = &PL_sv_undef;
877 hv_iterinit(cxt->hclass);
878 while (he = hv_iternext(cxt->hclass))
879 HeVAL(he) = &PL_sv_undef;
882 * And now dispose of them...
885 hv_undef(cxt->hseen);
886 sv_free((SV *) cxt->hseen);
888 hv_undef(cxt->hclass);
889 sv_free((SV *) cxt->hclass);
892 sv_free((SV *) cxt->hook);
899 * init_retrieve_context
901 * Initialize a new retrieve context for real recursion.
903 static void init_retrieve_context(cxt, optype)
907 TRACEME(("init_retrieve_context"));
910 * The hook hash table is used to keep track of the references on
911 * the STORABLE_thaw hook routines, when found in some class name.
913 * It is assumed that the inheritance tree will not be changed during
914 * storing, and that no new method will be dynamically created by the
918 cxt->hook = newHV(); /* Caches STORABLE_thaw */
921 * If retrieving an old binary version, the cxt->retrieve_vtbl variable
922 * was set to sv_old_retrieve. We'll need a hash table to keep track of
923 * the correspondance between the tags and the tag number used by the
924 * new retrieve routines.
927 cxt->hseen = (cxt->retrieve_vtbl == sv_old_retrieve) ? newHV() : 0;
929 cxt->aseen = newAV(); /* Where retrieved objects are kept */
930 cxt->aclass = newAV(); /* Where seen classnames are kept */
931 cxt->tagnum = 0; /* Have to count objects... */
932 cxt->classnum = 0; /* ...and class names as well */
933 cxt->optype = optype;
934 cxt->entry = 1; /* No recursion yet */
938 * clean_retrieve_context
940 * Clean retrieve context by
942 static void clean_retrieve_context(cxt)
945 TRACEME(("clean_retrieve_context"));
947 ASSERT(cxt->optype & ST_RETRIEVE, ("was performing a retrieve()"));
949 av_undef(cxt->aseen);
950 sv_free((SV *) cxt->aseen);
952 av_undef(cxt->aclass);
953 sv_free((SV *) cxt->aclass);
956 sv_free((SV *) cxt->hook);
959 sv_free((SV *) cxt->hseen); /* optional HV, for backward compat. */
968 * A workaround for the CROAK bug: cleanup the last context.
970 static void clean_context(cxt)
973 TRACEME(("clean_context"));
975 ASSERT(cxt->dirty, ("dirty context"));
977 if (cxt->optype & ST_RETRIEVE)
978 clean_retrieve_context(cxt);
980 clean_store_context(cxt);
986 * Allocate a new context and push it on top of the parent one.
987 * This new context is made globally visible via SET_STCXT().
989 static stcxt_t *allocate_context(parent_cxt)
994 TRACEME(("allocate_context"));
996 ASSERT(!parent_cxt->dirty, ("parent context clean"));
998 Newz(0, cxt, 1, stcxt_t);
999 cxt->prev = parent_cxt;
1008 * Free current context, which cannot be the "root" one.
1009 * Make the context underneath globally visible via SET_STCXT().
1011 static void free_context(cxt)
1014 stcxt_t *prev = cxt->prev;
1016 TRACEME(("free_context"));
1018 ASSERT(!cxt->dirty, ("clean context"));
1019 ASSERT(prev, ("not freeing root context"));
1037 * Tells whether we're in the middle of a store operation.
1043 return cxt->entry && (cxt->optype & ST_STORE);
1049 * Tells whether we're in the middle of a retrieve operation.
1055 return cxt->entry && (cxt->optype & ST_RETRIEVE);
1059 * last_op_in_netorder
1061 * Returns whether last operation was made using network order.
1063 * This is typically out-of-band information that might prove useful
1064 * to people wishing to convert native to network order data when used.
1066 int last_op_in_netorder()
1070 return cxt->netorder;
1074 *** Hook lookup and calling routines.
1080 * A wrapper on gv_fetchmethod_autoload() which caches results.
1082 * Returns the routine reference as an SV*, or null if neither the package
1083 * nor its ancestors know about the method.
1085 static SV *pkg_fetchmeth(cache, pkg, method)
1095 * The following code is the same as the one performed by UNIVERSAL::can
1099 gv = gv_fetchmethod_autoload(pkg, method, FALSE);
1100 if (gv && isGV(gv)) {
1101 sv = newRV((SV*) GvCV(gv));
1102 TRACEME(("%s->%s: 0x%lx", HvNAME(pkg), method, (unsigned long) sv));
1104 sv = newSVsv(&PL_sv_undef);
1105 TRACEME(("%s->%s: not found", HvNAME(pkg), method));
1109 * Cache the result, ignoring failure: if we can't store the value,
1110 * it just won't be cached.
1113 (void) hv_store(cache, HvNAME(pkg), strlen(HvNAME(pkg)), sv, 0);
1115 return SvOK(sv) ? sv : (SV *) 0;
1121 * Force cached value to be undef: hook ignored even if present.
1123 static void pkg_hide(cache, pkg, method)
1128 (void) hv_store(cache,
1129 HvNAME(pkg), strlen(HvNAME(pkg)), newSVsv(&PL_sv_undef), 0);
1135 * Our own "UNIVERSAL::can", which caches results.
1137 * Returns the routine reference as an SV*, or null if the object does not
1138 * know about the method.
1140 static SV *pkg_can(cache, pkg, method)
1148 TRACEME(("pkg_can for %s->%s", HvNAME(pkg), method));
1151 * Look into the cache to see whether we already have determined
1152 * where the routine was, if any.
1154 * NOTA BENE: we don't use `method' at all in our lookup, since we know
1155 * that only one hook (i.e. always the same) is cached in a given cache.
1158 svh = hv_fetch(cache, HvNAME(pkg), strlen(HvNAME(pkg)), FALSE);
1162 TRACEME(("cached %s->%s: not found", HvNAME(pkg), method));
1165 TRACEME(("cached %s->%s: 0x%lx", HvNAME(pkg), method,
1166 (unsigned long) sv));
1171 TRACEME(("not cached yet"));
1172 return pkg_fetchmeth(cache, pkg, method); /* Fetch and cache */
1178 * Call routine as obj->hook(av) in scalar context.
1179 * Propagates the single returned value if not called in void context.
1181 static SV *scalar_call(obj, hook, cloning, av, flags)
1192 TRACEME(("scalar_call (cloning=%d)", cloning));
1199 XPUSHs(sv_2mortal(newSViv(cloning))); /* Cloning flag */
1201 SV **ary = AvARRAY(av);
1202 int cnt = AvFILLp(av) + 1;
1204 XPUSHs(ary[0]); /* Frozen string */
1205 for (i = 1; i < cnt; i++) {
1206 TRACEME(("pushing arg #%d (0x%lx)...", i, (unsigned long) ary[i]));
1207 XPUSHs(sv_2mortal(newRV(ary[i])));
1212 TRACEME(("calling..."));
1213 count = perl_call_sv(hook, flags); /* Go back to Perl code */
1214 TRACEME(("count = %d", count));
1220 SvREFCNT_inc(sv); /* We're returning it, must stay alive! */
1233 * Call routine obj->hook(cloning) in array context.
1234 * Returns the list of returned values in an array.
1236 static AV *array_call(obj, hook, cloning)
1246 TRACEME(("arrary_call (cloning=%d), cloning"));
1252 XPUSHs(obj); /* Target object */
1253 XPUSHs(sv_2mortal(newSViv(cloning))); /* Cloning flag */
1256 count = perl_call_sv(hook, G_ARRAY); /* Go back to Perl code */
1261 for (i = count - 1; i >= 0; i--) {
1263 av_store(av, i, SvREFCNT_inc(sv));
1276 * Lookup the class name in the `hclass' table and either assign it a new ID
1277 * or return the existing one, by filling in `classnum'.
1279 * Return true if the class was known, false if the ID was just generated.
1281 static int known_class(cxt, name, len, classnum)
1283 char *name; /* Class name */
1284 int len; /* Name length */
1288 HV *hclass = cxt->hclass;
1290 TRACEME(("known_class (%s)", name));
1293 * Recall that we don't store pointers in this hash table, but tags.
1294 * Therefore, we need LOW_32BITS() to extract the relevant parts.
1297 svh = hv_fetch(hclass, name, len, FALSE);
1299 *classnum = LOW_32BITS(*svh);
1304 * Unknown classname, we need to record it.
1305 * The (IV) cast below is for 64-bit machines, to avoid compiler warnings.
1309 if (!hv_store(hclass, name, len, (SV*)(IV) cxt->classnum, 0))
1310 CROAK(("Unable to record new classname"));
1312 *classnum = cxt->classnum;
1317 *** Sepcific store routines.
1323 * Store a reference.
1324 * Layout is SX_REF <object> or SX_OVERLOAD <object>.
1326 static int store_ref(cxt, sv)
1330 TRACEME(("store_ref (0x%lx)", (unsigned long) sv));
1333 * Follow reference, and check if target is overloaded.
1339 HV *stash = (HV *) SvSTASH(sv);
1340 if (stash && Gv_AMG(stash)) {
1341 TRACEME(("ref (0x%lx) is overloaded", (unsigned long) sv));
1342 PUTMARK(SX_OVERLOAD);
1348 return store(cxt, sv);
1356 * Layout is SX_LSCALAR <length> <data>, SX_SCALAR <lenght> <data> or SX_UNDEF.
1357 * The <data> section is omitted if <length> is 0.
1359 * If integer or double, the layout is SX_INTEGER <data> or SX_DOUBLE <data>.
1360 * Small integers (within [-127, +127]) are stored as SX_BYTE <byte>.
1362 static int store_scalar(cxt, sv)
1369 U32 flags = SvFLAGS(sv); /* "cc -O" may put it in register */
1371 TRACEME(("store_scalar (0x%lx)", (unsigned long) sv));
1374 * For efficiency, break the SV encapsulation by peaking at the flags
1375 * directly without using the Perl macros to avoid dereferencing
1376 * sv->sv_flags each time we wish to check the flags.
1379 if (!(flags & SVf_OK)) { /* !SvOK(sv) */
1380 if (sv == &PL_sv_undef) {
1381 TRACEME(("immortal undef"));
1382 PUTMARK(SX_SV_UNDEF);
1384 TRACEME(("undef at 0x%x", sv));
1391 * Always store the string representation of a scalar if it exists.
1392 * Gisle Aas provided me with this test case, better than a long speach:
1394 * perl -MDevel::Peek -le '$a="abc"; $a+0; Dump($a)'
1395 * SV = PVNV(0x80c8520)
1397 * FLAGS = (NOK,POK,pNOK,pPOK)
1400 * PV = 0x80c83d0 "abc"\0
1404 * Write SX_SCALAR, length, followed by the actual data.
1406 * Otherwise, write an SX_BYTE, SX_INTEGER or an SX_DOUBLE as
1407 * appropriate, followed by the actual (binary) data. A double
1408 * is written as a string if network order, for portability.
1410 * NOTE: instead of using SvNOK(sv), we test for SvNOKp(sv).
1411 * The reason is that when the scalar value is tainted, the SvNOK(sv)
1414 * The test for a read-only scalar with both POK and NOK set is meant
1415 * to quickly detect &PL_sv_yes and &PL_sv_no without having to pay the
1416 * address comparison for each scalar we store.
1419 #define SV_MAYBE_IMMORTAL (SVf_READONLY|SVf_POK|SVf_NOK)
1421 if ((flags & SV_MAYBE_IMMORTAL) == SV_MAYBE_IMMORTAL) {
1422 if (sv == &PL_sv_yes) {
1423 TRACEME(("immortal yes"));
1425 } else if (sv == &PL_sv_no) {
1426 TRACEME(("immortal no"));
1429 pv = SvPV(sv, len); /* We know it's SvPOK */
1430 goto string; /* Share code below */
1432 } else if (flags & SVp_POK) { /* SvPOKp(sv) => string */
1436 * Will come here from below with pv and len set if double & netorder,
1437 * or from above if it was readonly, POK and NOK but neither &PL_sv_yes
1442 STORE_SCALAR(pv, len);
1443 TRACEME(("ok (scalar 0x%lx '%s', length = %d)",
1444 (unsigned long) sv, SvPVX(sv), len));
1446 } else if (flags & SVp_NOK) { /* SvNOKp(sv) => double */
1447 double nv = SvNV(sv);
1450 * Watch for number being an integer in disguise.
1452 if (nv == (double) (iv = I_V(nv))) {
1453 TRACEME(("double %lf is actually integer %ld", nv, iv));
1454 goto integer; /* Share code below */
1457 if (cxt->netorder) {
1458 TRACEME(("double %lf stored as string", nv));
1460 goto string; /* Share code above */
1464 WRITE(&nv, sizeof(nv));
1466 TRACEME(("ok (double 0x%lx, value = %lf)", (unsigned long) sv, nv));
1468 } else if (flags & SVp_IOK) { /* SvIOKp(sv) => integer */
1472 * Will come here from above with iv set if double is an integer.
1477 * Optimize small integers into a single byte, otherwise store as
1478 * a real integer (converted into network order if they asked).
1481 if (iv >= -128 && iv <= 127) {
1482 unsigned char siv = (unsigned char) (iv + 128); /* [0,255] */
1485 TRACEME(("small integer stored as %d", siv));
1486 } else if (cxt->netorder) {
1489 niv = (int) htonl(iv);
1490 TRACEME(("using network order"));
1493 TRACEME(("as-is for network order"));
1496 WRITE(&niv, sizeof(niv));
1498 PUTMARK(SX_INTEGER);
1499 WRITE(&iv, sizeof(iv));
1502 TRACEME(("ok (integer 0x%lx, value = %d)", (unsigned long) sv, iv));
1505 CROAK(("Can't determine type of %s(0x%lx)", sv_reftype(sv, FALSE),
1506 (unsigned long) sv));
1508 return 0; /* Ok, no recursion on scalars */
1516 * Layout is SX_ARRAY <size> followed by each item, in increading index order.
1517 * Each item is stored as <object>.
1519 static int store_array(cxt, av)
1524 I32 len = av_len(av) + 1;
1528 TRACEME(("store_array (0x%lx)", (unsigned long) av));
1531 * Signal array by emitting SX_ARRAY, followed by the array length.
1536 TRACEME(("size = %d", len));
1539 * Now store each item recursively.
1542 for (i = 0; i < len; i++) {
1543 sav = av_fetch(av, i, 0);
1545 TRACEME(("(#%d) undef item", i));
1549 TRACEME(("(#%d) item", i));
1550 if (ret = store(cxt, *sav))
1554 TRACEME(("ok (array)"));
1563 * Borrowed from perl source file pp_ctl.c, where it is used by pp_sort.
1570 return sv_cmp(*(SV * const *) a, *(SV * const *) b);
1577 * Store an hash table.
1579 * Layout is SX_HASH <size> followed by each key/value pair, in random order.
1580 * Values are stored as <object>.
1581 * Keys are stored as <length> <data>, the <data> section being omitted
1584 static int store_hash(cxt, hv)
1588 I32 len = HvKEYS(hv);
1594 TRACEME(("store_hash (0x%lx)", (unsigned long) hv));
1597 * Signal hash by emitting SX_HASH, followed by the table length.
1602 TRACEME(("size = %d", len));
1605 * Save possible iteration state via each() on that table.
1608 riter = HvRITER(hv);
1609 eiter = HvEITER(hv);
1613 * Now store each item recursively.
1615 * If canonical is defined to some true value then store each
1616 * key/value pair in sorted order otherwise the order is random.
1617 * Canonical order is irrelevant when a deep clone operation is performed.
1619 * Fetch the value from perl only once per store() operation, and only
1624 !(cxt->optype & ST_CLONE) && (cxt->canonical == 1 ||
1625 (cxt->canonical < 0 && (cxt->canonical =
1626 SvTRUE(perl_get_sv("Storable::canonical", TRUE)) ? 1 : 0)))
1629 * Storing in order, sorted by key.
1630 * Run through the hash, building up an array of keys in a
1631 * mortal array, sort the array and then run through the
1637 TRACEME(("using canonical order"));
1639 for (i = 0; i < len; i++) {
1640 HE *he = hv_iternext(hv);
1641 SV *key = hv_iterkeysv(he);
1642 av_store(av, AvFILLp(av)+1, key); /* av_push(), really */
1645 qsort((char *) AvARRAY(av), len, sizeof(SV *), sortcmp);
1647 for (i = 0; i < len; i++) {
1650 SV *key = av_shift(av);
1651 HE *he = hv_fetch_ent(hv, key, 0, 0);
1652 SV *val = HeVAL(he);
1654 return 1; /* Internal error, not I/O error */
1657 * Store value first.
1660 TRACEME(("(#%d) value 0x%lx", i, (unsigned long) val));
1662 if (ret = store(cxt, val))
1667 * Keys are written after values to make sure retrieval
1668 * can be optimal in terms of memory usage, where keys are
1669 * read into a fixed unique buffer called kbuf.
1670 * See retrieve_hash() for details.
1673 keyval = hv_iterkey(he, &keylen);
1674 TRACEME(("(#%d) key '%s'", i, keyval));
1677 WRITE(keyval, keylen);
1681 * Free up the temporary array
1690 * Storing in "random" order (in the order the keys are stored
1691 * within the the hash). This is the default and will be faster!
1694 for (i = 0; i < len; i++) {
1697 SV *val = hv_iternextsv(hv, &key, &len);
1700 return 1; /* Internal error, not I/O error */
1703 * Store value first.
1706 TRACEME(("(#%d) value 0x%lx", i, (unsigned long) val));
1708 if (ret = store(cxt, val))
1713 * Keys are written after values to make sure retrieval
1714 * can be optimal in terms of memory usage, where keys are
1715 * read into a fixed unique buffer called kbuf.
1716 * See retrieve_hash() for details.
1719 TRACEME(("(#%d) key '%s'", i, key));
1726 TRACEME(("ok (hash 0x%lx)", (unsigned long) hv));
1729 HvRITER(hv) = riter; /* Restore hash iterator state */
1730 HvEITER(hv) = eiter;
1738 * When storing a tied object (be it a tied scalar, array or hash), we lay out
1739 * a special mark, followed by the underlying tied object. For instance, when
1740 * dealing with a tied hash, we store SX_TIED_HASH <hash object>, where
1741 * <hash object> stands for the serialization of the tied hash.
1743 static int store_tied(cxt, sv)
1749 int svt = SvTYPE(sv);
1752 TRACEME(("store_tied (0x%lx)", (unsigned long) sv));
1755 * We have a small run-time penalty here because we chose to factorise
1756 * all tieds objects into the same routine, and not have a store_tied_hash,
1757 * a store_tied_array, etc...
1759 * Don't use a switch() statement, as most compilers don't optimize that
1760 * well for 2/3 values. An if() else if() cascade is just fine. We put
1761 * tied hashes first, as they are the most likely beasts.
1764 if (svt == SVt_PVHV) {
1765 TRACEME(("tied hash"));
1766 PUTMARK(SX_TIED_HASH); /* Introduces tied hash */
1767 } else if (svt == SVt_PVAV) {
1768 TRACEME(("tied array"));
1769 PUTMARK(SX_TIED_ARRAY); /* Introduces tied array */
1771 TRACEME(("tied scalar"));
1772 PUTMARK(SX_TIED_SCALAR); /* Introduces tied scalar */
1776 if (!(mg = mg_find(sv, mtype)))
1777 CROAK(("No magic '%c' found while storing tied %s", mtype,
1778 (svt == SVt_PVHV) ? "hash" :
1779 (svt == SVt_PVAV) ? "array" : "scalar"));
1782 * The mg->mg_obj found by mg_find() above actually points to the
1783 * underlying tied Perl object implementation. For instance, if the
1784 * original SV was that of a tied array, then mg->mg_obj is an AV.
1786 * Note that we store the Perl object as-is. We don't call its FETCH
1787 * method along the way. At retrieval time, we won't call its STORE
1788 * method either, but the tieing magic will be re-installed. In itself,
1789 * that ensures that the tieing semantics are preserved since futher
1790 * accesses on the retrieved object will indeed call the magic methods...
1793 if (ret = store(cxt, mg->mg_obj))
1796 TRACEME(("ok (tied)"));
1804 * Stores a reference to an item within a tied structure:
1806 * . \$h{key}, stores both the (tied %h) object and 'key'.
1807 * . \$a[idx], stores both the (tied @a) object and 'idx'.
1809 * Layout is therefore either:
1810 * SX_TIED_KEY <object> <key>
1811 * SX_TIED_IDX <object> <index>
1813 static int store_tied_item(cxt, sv)
1820 TRACEME(("store_tied_item (0x%lx)", (unsigned long) sv));
1822 if (!(mg = mg_find(sv, 'p')))
1823 CROAK(("No magic 'p' found while storing reference to tied item"));
1826 * We discriminate between \$h{key} and \$a[idx] via mg_ptr.
1830 TRACEME(("store_tied_item: storing a ref to a tied hash item"));
1831 PUTMARK(SX_TIED_KEY);
1832 TRACEME(("store_tied_item: storing OBJ 0x%lx",
1833 (unsigned long) mg->mg_obj));
1835 if (ret = store(cxt, mg->mg_obj))
1838 TRACEME(("store_tied_item: storing PTR 0x%lx",
1839 (unsigned long) mg->mg_ptr));
1841 if (ret = store(cxt, (SV *) mg->mg_ptr))
1844 I32 idx = mg->mg_len;
1846 TRACEME(("store_tied_item: storing a ref to a tied array item "));
1847 PUTMARK(SX_TIED_IDX);
1848 TRACEME(("store_tied_item: storing OBJ 0x%lx",
1849 (unsigned long) mg->mg_obj));
1851 if (ret = store(cxt, mg->mg_obj))
1854 TRACEME(("store_tied_item: storing IDX %d", idx));
1859 TRACEME(("ok (tied item)"));
1865 * store_hook -- dispatched manually, not via sv_store[]
1867 * The blessed SV is serialized by a hook.
1871 * SX_HOOK <flags> <len> <classname> <len2> <str> [<len3> <object-IDs>]
1873 * where <flags> indicates how long <len>, <len2> and <len3> are, whether
1874 * the trailing part [] is present, the type of object (scalar, array or hash).
1875 * There is also a bit which says how the classname is stored between:
1880 * and when the <index> form is used (classname already seen), the "large
1881 * classname" bit in <flags> indicates how large the <index> is.
1883 * The serialized string returned by the hook is of length <len2> and comes
1884 * next. It is an opaque string for us.
1886 * Those <len3> object IDs which are listed last represent the extra references
1887 * not directly serialized by the hook, but which are linked to the object.
1889 * When recursion is mandated to resolve object-IDs not yet seen, we have
1890 * instead, with <header> being flags with bits set to indicate the object type
1891 * and that recursion was indeed needed:
1893 * SX_HOOK <header> <object> <header> <object> <flags>
1895 * that same header being repeated between serialized objects obtained through
1896 * recursion, until we reach flags indicating no recursion, at which point
1897 * we know we've resynchronized with a single layout, after <flags>.
1899 static int store_hook(cxt, sv, type, pkg, hook)
1911 int count; /* really len3 + 1 */
1912 unsigned char flags;
1915 int recursed = 0; /* counts recursion */
1916 int obj_type; /* object type, on 2 bits */
1919 int clone = cxt->optype & ST_CLONE;
1921 TRACEME(("store_hook, class \"%s\", tagged #%d", HvNAME(pkg), cxt->tagnum));
1924 * Determine object type on 2 bits.
1929 obj_type = SHT_SCALAR;
1932 obj_type = SHT_ARRAY;
1935 obj_type = SHT_HASH;
1938 CROAK(("Unexpected object type (%d) in store_hook()", type));
1940 flags = SHF_NEED_RECURSE | obj_type;
1942 class = HvNAME(pkg);
1943 len = strlen(class);
1946 * To call the hook, we need to fake a call like:
1948 * $object->STORABLE_freeze($cloning);
1950 * but we don't have the $object here. For instance, if $object is
1951 * a blessed array, what we have in `sv' is the array, and we can't
1952 * call a method on those.
1954 * Therefore, we need to create a temporary reference to the object and
1955 * make the call on that reference.
1958 TRACEME(("about to call STORABLE_freeze on class %s", class));
1960 ref = newRV_noinc(sv); /* Temporary reference */
1961 av = array_call(ref, hook, clone); /* @a = $object->STORABLE_freeze($c) */
1963 SvREFCNT_dec(ref); /* Reclaim temporary reference */
1965 count = AvFILLp(av) + 1;
1966 TRACEME(("store_hook, array holds %d items", count));
1969 * If they return an empty list, it means they wish to ignore the
1970 * hook for this class (and not just this instance -- that's for them
1971 * to handle if they so wish).
1973 * Simply disable the cached entry for the hook (it won't be recomputed
1974 * since it's present in the cache) and recurse to store_blessed().
1979 * They must not change their mind in the middle of a serialization.
1982 if (hv_fetch(cxt->hclass, class, len, FALSE))
1983 CROAK(("Too late to ignore hooks for %s class \"%s\"",
1984 (cxt->optype & ST_CLONE) ? "cloning" : "storing", class));
1986 pkg_hide(cxt->hook, pkg, "STORABLE_freeze");
1988 ASSERT(!pkg_can(cxt->hook, pkg, "STORABLE_freeze"), ("hook invisible"));
1989 TRACEME(("Ignoring STORABLE_freeze in class \"%s\"", class));
1991 return store_blessed(cxt, sv, type, pkg);
1995 * Get frozen string.
1999 pv = SvPV(ary[0], len2);
2002 * Allocate a class ID if not already done.
2005 if (!known_class(cxt, class, len, &classnum)) {
2006 TRACEME(("first time we see class %s, ID = %d", class, classnum));
2007 classnum = -1; /* Mark: we must store classname */
2009 TRACEME(("already seen class %s, ID = %d", class, classnum));
2013 * If they returned more than one item, we need to serialize some
2014 * extra references if not already done.
2016 * Loop over the array, starting at postion #1, and for each item,
2017 * ensure it is a reference, serialize it if not already done, and
2018 * replace the entry with the tag ID of the corresponding serialized
2021 * We CHEAT by not calling av_fetch() and read directly within the
2025 for (i = 1; i < count; i++) {
2030 CROAK(("Item #%d from hook in %s is not a reference", i, class));
2031 xsv = SvRV(xsv); /* Follow ref to know what to look for */
2034 * Look in hseen and see if we have a tag already.
2035 * Serialize entry if not done already, and get its tag.
2038 if (svh = hv_fetch(cxt->hseen, (char *) &xsv, sizeof(xsv), FALSE))
2039 goto sv_seen; /* Avoid moving code too far to the right */
2041 TRACEME(("listed object %d at 0x%lx is unknown",
2042 i-1, (unsigned long) xsv));
2045 * We need to recurse to store that object and get it to be known
2046 * so that we can resolve the list of object-IDs at retrieve time.
2048 * The first time we do this, we need to emit the proper header
2049 * indicating that we recursed, and what the type of object is (the
2050 * object we're storing via a user-hook). Indeed, during retrieval,
2051 * we'll have to create the object before recursing to retrieve the
2052 * others, in case those would point back at that object.
2055 /* [SX_HOOK] <flags> <object>*/
2060 if (ret = store(cxt, xsv)) /* Given by hook for us to store */
2063 svh = hv_fetch(cxt->hseen, (char *) &xsv, sizeof(xsv), FALSE);
2065 CROAK(("Could not serialize item #%d from hook in %s", i, class));
2068 * Replace entry with its tag (not a real SV, so no refcnt increment)
2074 TRACEME(("listed object %d at 0x%lx is tag #%d",
2075 i-1, (unsigned long) xsv, (I32) *svh));
2079 * Compute leading flags.
2083 if (((classnum == -1) ? len : classnum) > LG_SCALAR)
2084 flags |= SHF_LARGE_CLASSLEN;
2086 flags |= SHF_IDX_CLASSNAME;
2087 if (len2 > LG_SCALAR)
2088 flags |= SHF_LARGE_STRLEN;
2090 flags |= SHF_HAS_LIST;
2091 if (count > (LG_SCALAR + 1))
2092 flags |= SHF_LARGE_LISTLEN;
2095 * We're ready to emit either serialized form:
2097 * SX_HOOK <flags> <len> <classname> <len2> <str> [<len3> <object-IDs>]
2098 * SX_HOOK <flags> <index> <len2> <str> [<len3> <object-IDs>]
2100 * If we recursed, the SX_HOOK has already been emitted.
2103 TRACEME(("SX_HOOK (recursed=%d) flags=0x%x class=%d len=%d len2=%d len3=%d",
2104 recursed, flags, classnum, len, len2, count-1));
2106 /* SX_HOOK <flags> */
2111 /* <len> <classname> or <index> */
2112 if (flags & SHF_IDX_CLASSNAME) {
2113 if (flags & SHF_LARGE_CLASSLEN)
2116 unsigned char cnum = (unsigned char) classnum;
2120 if (flags & SHF_LARGE_CLASSLEN)
2123 unsigned char clen = (unsigned char) len;
2126 WRITE(class, len); /* Final \0 is omitted */
2129 /* <len2> <frozen-str> */
2130 if (flags & SHF_LARGE_STRLEN)
2133 unsigned char clen = (unsigned char) len2;
2137 WRITE(pv, len2); /* Final \0 is omitted */
2139 /* [<len3> <object-IDs>] */
2140 if (flags & SHF_HAS_LIST) {
2141 int len3 = count - 1;
2142 if (flags & SHF_LARGE_LISTLEN)
2145 unsigned char clen = (unsigned char) len3;
2150 * NOTA BENE, for 64-bit machines: the ary[i] below does not yield a
2151 * real pointer, rather a tag number, well under the 32-bit limit.
2154 for (i = 1; i < count; i++) {
2155 I32 tagval = htonl(LOW_32BITS(ary[i]));
2156 WRITE(&tagval, sizeof(I32));
2157 TRACEME(("object %d, tag #%d", i-1, ntohl(tagval)));
2162 * Free the array. We need extra care for indices after 0, since they
2163 * don't hold real SVs but integers cast.
2167 AvFILLp(av) = 0; /* Cheat, nothing after 0 interests us */
2175 * store_blessed -- dispatched manually, not via sv_store[]
2177 * Check whether there is a STORABLE_xxx hook defined in the class or in one
2178 * of its ancestors. If there is, then redispatch to store_hook();
2180 * Otherwise, the blessed SV is stored using the following layout:
2182 * SX_BLESS <flag> <len> <classname> <object>
2184 * where <flag> indicates whether <len> is stored on 0 or 4 bytes, depending
2185 * on the high-order bit in flag: if 1, then length follows on 4 bytes.
2186 * Otherwise, the low order bits give the length, thereby giving a compact
2187 * representation for class names less than 127 chars long.
2189 * Each <classname> seen is remembered and indexed, so that the next time
2190 * an object in the blessed in the same <classname> is stored, the following
2193 * SX_IX_BLESS <flag> <index> <object>
2195 * where <index> is the classname index, stored on 0 or 4 bytes depending
2196 * on the high-order bit in flag (same encoding as above for <len>).
2198 static int store_blessed(cxt, sv, type, pkg)
2209 TRACEME(("store_blessed, type %d, class \"%s\"", type, HvNAME(pkg)));
2212 * Look for a hook for this blessed SV and redirect to store_hook()
2216 hook = pkg_can(cxt->hook, pkg, "STORABLE_freeze");
2218 return store_hook(cxt, sv, type, pkg, hook);
2221 * This is a blessed SV without any serialization hook.
2224 class = HvNAME(pkg);
2225 len = strlen(class);
2227 TRACEME(("blessed 0x%lx in %s, no hook: tagged #%d",
2228 (unsigned long) sv, class, cxt->tagnum));
2231 * Determine whether it is the first time we see that class name (in which
2232 * case it will be stored in the SX_BLESS form), or whether we already
2233 * saw that class name before (in which case the SX_IX_BLESS form will be
2237 if (known_class(cxt, class, len, &classnum)) {
2238 TRACEME(("already seen class %s, ID = %d", class, classnum));
2239 PUTMARK(SX_IX_BLESS);
2240 if (classnum <= LG_BLESS) {
2241 unsigned char cnum = (unsigned char) classnum;
2244 unsigned char flag = (unsigned char) 0x80;
2249 TRACEME(("first time we see class %s, ID = %d", class, classnum));
2251 if (len <= LG_BLESS) {
2252 unsigned char clen = (unsigned char) len;
2255 unsigned char flag = (unsigned char) 0x80;
2257 WLEN(len); /* Don't BER-encode, this should be rare */
2259 WRITE(class, len); /* Final \0 is omitted */
2263 * Now emit the <object> part.
2266 return SV_STORE(type)(cxt, sv);
2272 * We don't know how to store the item we reached, so return an error condition.
2273 * (it's probably a GLOB, some CODE reference, etc...)
2275 * If they defined the `forgive_me' variable at the Perl level to some
2276 * true value, then don't croak, just warn, and store a placeholder string
2279 static int store_other(cxt, sv)
2284 static char buf[80];
2286 TRACEME(("store_other"));
2289 * Fetch the value from perl only once per store() operation.
2293 cxt->forgive_me == 0 ||
2294 (cxt->forgive_me < 0 && !(cxt->forgive_me =
2295 SvTRUE(perl_get_sv("Storable::forgive_me", TRUE)) ? 1 : 0))
2297 CROAK(("Can't store %s items", sv_reftype(sv, FALSE)));
2299 warn("Can't store item %s(0x%lx)",
2300 sv_reftype(sv, FALSE), (unsigned long) sv);
2303 * Store placeholder string as a scalar instead...
2306 (void) sprintf(buf, "You lost %s(0x%lx)\0", sv_reftype(sv, FALSE),
2307 (unsigned long) sv);
2310 STORE_SCALAR(buf, len);
2311 TRACEME(("ok (dummy \"%s\", length = %d)", buf, len));
2317 *** Store driving routines
2323 * WARNING: partially duplicates Perl's sv_reftype for speed.
2325 * Returns the type of the SV, identified by an integer. That integer
2326 * may then be used to index the dynamic routine dispatch table.
2328 static int sv_type(sv)
2331 switch (SvTYPE(sv)) {
2336 * No need to check for ROK, that can't be set here since there
2337 * is no field capable of hodling the xrv_rv reference.
2345 * Starting from SVt_PV, it is possible to have the ROK flag
2346 * set, the pointer to the other SV being either stored in
2347 * the xrv_rv (in the case of a pure SVt_RV), or as the
2348 * xpv_pv field of an SVt_PV and its heirs.
2350 * However, those SV cannot be magical or they would be an
2351 * SVt_PVMG at least.
2353 return SvROK(sv) ? svis_REF : svis_SCALAR;
2355 case SVt_PVLV: /* Workaround for perl5.004_04 "LVALUE" bug */
2356 if (SvRMAGICAL(sv) && (mg_find(sv, 'p')))
2357 return svis_TIED_ITEM;
2360 if (SvRMAGICAL(sv) && (mg_find(sv, 'q')))
2362 return SvROK(sv) ? svis_REF : svis_SCALAR;
2364 if (SvRMAGICAL(sv) && (mg_find(sv, 'P')))
2368 if (SvRMAGICAL(sv) && (mg_find(sv, 'P')))
2381 * Recursively store objects pointed to by the sv to the specified file.
2383 * Layout is <content> or SX_OBJECT <tagnum> if we reach an already stored
2384 * object (one for which storage has started -- it may not be over if we have
2385 * a self-referenced structure). This data set forms a stored <object>.
2387 static int store(cxt, sv)
2395 HV *hseen = cxt->hseen;
2397 TRACEME(("store (0x%lx)", (unsigned long) sv));
2400 * If object has already been stored, do not duplicate data.
2401 * Simply emit the SX_OBJECT marker followed by its tag data.
2402 * The tag is always written in network order.
2404 * NOTA BENE, for 64-bit machines: the "*svh" below does not yield a
2405 * real pointer, rather a tag number (watch the insertion code below).
2406 * That means it pobably safe to assume it is well under the 32-bit limit,
2407 * and makes the truncation safe.
2408 * -- RAM, 14/09/1999
2411 svh = hv_fetch(hseen, (char *) &sv, sizeof(sv), FALSE);
2413 I32 tagval = htonl(LOW_32BITS(*svh));
2415 TRACEME(("object 0x%lx seen as #%d",
2416 (unsigned long) sv, ntohl(tagval)));
2419 WRITE(&tagval, sizeof(I32));
2424 * Allocate a new tag and associate it with the address of the sv being
2425 * stored, before recursing...
2427 * In order to avoid creating new SvIVs to hold the tagnum we just
2428 * cast the tagnum to a SV pointer and store that in the hash. This
2429 * means that we must clean up the hash manually afterwards, but gives
2430 * us a 15% throughput increase.
2432 * The (IV) cast below is for 64-bit machines, to avoid warnings from
2433 * the compiler. Please, let me know if it does not work.
2434 * -- RAM, 14/09/1999
2438 if (!hv_store(hseen,
2439 (char *) &sv, sizeof(sv), (SV*)(IV) cxt->tagnum, 0))
2443 * Store `sv' and everything beneath it, using appropriate routine.
2444 * Abort immediately if we get a non-zero status back.
2449 TRACEME(("storing 0x%lx tag #%d, type %d...",
2450 (unsigned long) sv, cxt->tagnum, type));
2453 HV *pkg = SvSTASH(sv);
2454 ret = store_blessed(cxt, sv, type, pkg);
2456 ret = SV_STORE(type)(cxt, sv);
2458 TRACEME(("%s (stored 0x%lx, refcnt=%d, %s)",
2459 ret ? "FAILED" : "ok", (unsigned long) sv,
2460 SvREFCNT(sv), sv_reftype(sv, FALSE)));
2468 * Write magic number and system information into the file.
2469 * Layout is <magic> <network> [<len> <byteorder> <sizeof int> <sizeof long>
2470 * <sizeof ptr>] where <len> is the length of the byteorder hexa string.
2471 * All size and lenghts are written as single characters here.
2473 * Note that no byte ordering info is emitted when <network> is true, since
2474 * integers will be emitted in network order in that case.
2476 static int magic_write(cxt)
2479 char buf[256]; /* Enough room for 256 hexa digits */
2481 int use_network_order = cxt->netorder;
2483 TRACEME(("magic_write on fd=%d", cxt->fio ? fileno(cxt->fio) : -1));
2486 WRITE(magicstr, strlen(magicstr)); /* Don't write final \0 */
2489 * Starting with 0.6, the "use_network_order" byte flag is also used to
2490 * indicate the version number of the binary image, encoded in the upper
2491 * bits. The bit 0 is always used to indicate network order.
2495 ((use_network_order ? 0x1 : 0x0) | (STORABLE_BIN_MAJOR << 1));
2499 * Starting with 0.7, a full byte is dedicated to the minor version of
2500 * the binary format, which is incremented only when new markers are
2501 * introduced, for instance, but when backward compatibility is preserved.
2504 PUTMARK((unsigned char) STORABLE_BIN_MINOR);
2506 if (use_network_order)
2507 return 0; /* Don't bother with byte ordering */
2509 sprintf(buf, "%lx", (unsigned long) BYTEORDER);
2510 c = (unsigned char) strlen(buf);
2512 WRITE(buf, (unsigned int) c); /* Don't write final \0 */
2513 PUTMARK((unsigned char) sizeof(int));
2514 PUTMARK((unsigned char) sizeof(long));
2515 PUTMARK((unsigned char) sizeof(char *));
2517 TRACEME(("ok (magic_write byteorder = 0x%lx [%d], I%d L%d P%d)",
2518 (unsigned long) BYTEORDER, (int) c,
2519 sizeof(int), sizeof(long), sizeof(char *)));
2527 * Common code for store operations.
2529 * When memory store is requested (f = NULL) and a non null SV* is given in
2530 * `res', it is filled with a new SV created out of the memory buffer.
2532 * It is required to provide a non-null `res' when the operation type is not
2533 * dclone() and store() is performed to memory.
2535 static int do_store(f, sv, optype, network_order, res)
2545 ASSERT(!(f == 0 && !(optype & ST_CLONE)) || res,
2546 ("must supply result SV pointer for real recursion to memory"));
2548 TRACEME(("do_store (optype=%d, netorder=%d)",
2549 optype, network_order));
2554 * Workaround for CROAK leak: if they enter with a "dirty" context,
2555 * free up memory for them now.
2562 * Now that STORABLE_xxx hooks exist, it is possible that they try to
2563 * re-enter store() via the hooks. We need to stack contexts.
2567 cxt = allocate_context(cxt);
2571 ASSERT(cxt->entry == 1, ("starting new recursion"));
2572 ASSERT(!cxt->dirty, ("clean context"));
2575 * Ensure sv is actually a reference. From perl, we called something
2577 * pstore(FILE, \@array);
2578 * so we must get the scalar value behing that reference.
2582 CROAK(("Not a reference"));
2583 sv = SvRV(sv); /* So follow it to know what to store */
2586 * If we're going to store to memory, reset the buffer.
2593 * Prepare context and emit headers.
2596 init_store_context(cxt, f, optype, network_order);
2598 if (-1 == magic_write(cxt)) /* Emit magic and ILP info */
2599 return 0; /* Error */
2602 * Recursively store object...
2605 ASSERT(is_storing(), ("within store operation"));
2607 status = store(cxt, sv); /* Just do it! */
2610 * If they asked for a memory store and they provided an SV pointer,
2611 * make an SV string out of the buffer and fill their pointer.
2613 * When asking for ST_REAL, it's MANDATORY for the caller to provide
2614 * an SV, since context cleanup might free the buffer if we did recurse.
2615 * (unless caller is dclone(), which is aware of that).
2618 if (!cxt->fio && res)
2624 * The "root" context is never freed, since it is meant to be always
2625 * handy for the common case where no recursion occurs at all (i.e.
2626 * we enter store() outside of any Storable code and leave it, period).
2627 * We know it's the "root" context because there's nothing stacked
2632 * When deep cloning, we don't free the context: doing so would force
2633 * us to copy the data in the memory buffer. Sicne we know we're
2634 * about to enter do_retrieve...
2637 clean_store_context(cxt);
2638 if (cxt->prev && !(cxt->optype & ST_CLONE))
2641 TRACEME(("do_store returns %d", status));
2649 * Store the transitive data closure of given object to disk.
2650 * Returns 0 on error, a true value otherwise.
2656 TRACEME(("pstore"));
2657 return do_store(f, sv, 0, FALSE, Nullsv);
2664 * Same as pstore(), but network order is used for integers and doubles are
2665 * emitted as strings.
2667 int net_pstore(f, sv)
2671 TRACEME(("net_pstore"));
2672 return do_store(f, sv, 0, TRUE, Nullsv);
2682 * Build a new SV out of the content of the internal memory buffer.
2684 static SV *mbuf2sv()
2688 return newSVpv(mbase, MBUF_SIZE());
2694 * Store the transitive data closure of given object to memory.
2695 * Returns undef on error, a scalar value containing the data otherwise.
2703 TRACEME(("mstore"));
2705 if (!do_store(0, sv, 0, FALSE, &out))
2706 return &PL_sv_undef;
2714 * Same as mstore(), but network order is used for integers and doubles are
2715 * emitted as strings.
2723 TRACEME(("net_mstore"));
2725 if (!do_store(0, sv, 0, TRUE, &out))
2726 return &PL_sv_undef;
2732 *** Specific retrieve callbacks.
2738 * Return an error via croak, since it is not possible that we get here
2739 * under normal conditions, when facing a file produced via pstore().
2741 static SV *retrieve_other(cxt)
2745 cxt->ver_major != STORABLE_BIN_MAJOR &&
2746 cxt->ver_minor != STORABLE_BIN_MINOR
2748 CROAK(("Corrupted storable %s (binary v%d.%d), current is v%d.%d",
2749 cxt->fio ? "file" : "string",
2750 cxt->ver_major, cxt->ver_minor,
2751 STORABLE_BIN_MAJOR, STORABLE_BIN_MINOR));
2753 CROAK(("Corrupted storable %s (binary v%d.%d)",
2754 cxt->fio ? "file" : "string",
2755 cxt->ver_major, cxt->ver_minor));
2758 return (SV *) 0; /* Just in case */
2762 * retrieve_idx_blessed
2764 * Layout is SX_IX_BLESS <index> <object> with SX_IX_BLESS already read.
2765 * <index> can be coded on either 1 or 5 bytes.
2767 static SV *retrieve_idx_blessed(cxt)
2775 TRACEME(("retrieve_idx_blessed (#%d)", cxt->tagnum));
2777 GETMARK(idx); /* Index coded on a single char? */
2782 * Fetch classname in `aclass'
2785 sva = av_fetch(cxt->aclass, idx, FALSE);
2787 CROAK(("Class name #%d should have been seen already", idx));
2789 class = SvPVX(*sva); /* We know it's a PV, by construction */
2791 TRACEME(("class ID %d => %s", idx, class));
2794 * Retrieve object and bless it.
2807 * Layout is SX_BLESS <len> <classname> <object> with SX_BLESS already read.
2808 * <len> can be coded on either 1 or 5 bytes.
2810 static SV *retrieve_blessed(cxt)
2815 char buf[LG_BLESS + 1]; /* Avoid malloc() if possible */
2818 TRACEME(("retrieve_blessed (#%d)", cxt->tagnum));
2821 * Decode class name length and read that name.
2823 * Short classnames have two advantages: their length is stored on one
2824 * single byte, and the string can be read on the stack.
2827 GETMARK(len); /* Length coded on a single char? */
2830 TRACEME(("** allocating %d bytes for class name", len+1));
2831 New(10003, class, len+1, char);
2834 class[len] = '\0'; /* Mark string end */
2837 * It's a new classname, otherwise it would have been an SX_IX_BLESS.
2840 if (!av_store(cxt->aclass, cxt->classnum++, newSVpvn(class, len)))
2844 * Retrieve object and bless it.
2860 * Layout: SX_HOOK <flags> <len> <classname> <len2> <str> [<len3> <object-IDs>]
2861 * with leading mark already read, as usual.
2863 * When recursion was involved during serialization of the object, there
2864 * is an unknown amount of serialized objects after the SX_HOOK mark. Until
2865 * we reach a <flags> marker with the recursion bit cleared.
2867 static SV *retrieve_hook(cxt)
2871 char buf[LG_BLESS + 1]; /* Avoid malloc() if possible */
2883 int clone = cxt->optype & ST_CLONE;
2885 TRACEME(("retrieve_hook (#%d)", cxt->tagnum));
2888 * Read flags, which tell us about the type, and whether we need to recurse.
2894 * Create the (empty) object, and mark it as seen.
2896 * This must be done now, because tags are incremented, and during
2897 * serialization, the object tag was affected before recursion could
2901 obj_type = flags & SHF_TYPE_MASK;
2907 sv = (SV *) newAV();
2910 sv = (SV *) newHV();
2913 return retrieve_other(cxt); /* Let it croak */
2918 * Whilst flags tell us to recurse, do so.
2920 * We don't need to remember the addresses returned by retrieval, because
2921 * all the references will be obtained through indirection via the object
2922 * tags in the object-ID list.
2925 while (flags & SHF_NEED_RECURSE) {
2926 TRACEME(("retrieve_hook recursing..."));
2930 TRACEME(("retrieve_hook back with rv=0x%lx", (unsigned long) rv));
2934 if (flags & SHF_IDX_CLASSNAME) {
2939 * Fetch index from `aclass'
2942 if (flags & SHF_LARGE_CLASSLEN)
2947 sva = av_fetch(cxt->aclass, idx, FALSE);
2949 CROAK(("Class name #%d should have been seen already", idx));
2951 class = SvPVX(*sva); /* We know it's a PV, by construction */
2952 TRACEME(("class ID %d => %s", idx, class));
2956 * Decode class name length and read that name.
2958 * NOTA BENE: even if the length is stored on one byte, we don't read
2959 * on the stack. Just like retrieve_blessed(), we limit the name to
2960 * LG_BLESS bytes. This is an arbitrary decision.
2963 if (flags & SHF_LARGE_CLASSLEN)
2968 if (len > LG_BLESS) {
2969 TRACEME(("** allocating %d bytes for class name", len+1));
2970 New(10003, class, len+1, char);
2974 class[len] = '\0'; /* Mark string end */
2977 * Record new classname.
2980 if (!av_store(cxt->aclass, cxt->classnum++, newSVpvn(class, len)))
2984 TRACEME(("class name: %s", class));
2987 * Decode user-frozen string length and read it in a SV.
2989 * For efficiency reasons, we read data directly into the SV buffer.
2990 * To understand that code, read retrieve_scalar()
2993 if (flags & SHF_LARGE_STRLEN)
2998 frozen = NEWSV(10002, len2);
3000 SAFEREAD(SvPVX(frozen), len2, frozen);
3001 SvCUR_set(frozen, len2);
3002 *SvEND(frozen) = '\0';
3004 (void) SvPOK_only(frozen); /* Validates string pointer */
3007 TRACEME(("frozen string: %d bytes", len2));
3010 * Decode object-ID list length, if present.
3013 if (flags & SHF_HAS_LIST) {
3014 if (flags & SHF_LARGE_LISTLEN)
3020 av_extend(av, len3 + 1); /* Leave room for [0] */
3021 AvFILLp(av) = len3; /* About to be filled anyway */
3025 TRACEME(("has %d object IDs to link", len3));
3028 * Read object-ID list into array.
3029 * Because we pre-extended it, we can cheat and fill it manually.
3031 * We read object tags and we can convert them into SV* on the fly
3032 * because we know all the references listed in there (as tags)
3033 * have been already serialized, hence we have a valid correspondance
3034 * between each of those tags and the recreated SV.
3038 SV **ary = AvARRAY(av);
3040 for (i = 1; i <= len3; i++) { /* We leave [0] alone */
3045 READ(&tag, sizeof(I32));
3047 svh = av_fetch(cxt->aseen, tag, FALSE);
3049 CROAK(("Object #%d should have been retrieved already", tag));
3051 ary[i] = SvREFCNT_inc(xsv);
3056 * Bless the object and look up the STORABLE_thaw hook.
3060 hook = pkg_can(cxt->hook, SvSTASH(sv), "STORABLE_thaw");
3062 CROAK(("No STORABLE_thaw defined for objects of class %s", class));
3065 * If we don't have an `av' yet, prepare one.
3066 * Then insert the frozen string as item [0].
3074 AvARRAY(av)[0] = SvREFCNT_inc(frozen);
3079 * $object->STORABLE_thaw($cloning, $frozen, @refs);
3081 * where $object is our blessed (empty) object, $cloning is a boolean
3082 * telling whether we're running a deep clone, $frozen is the frozen
3083 * string the user gave us in his serializing hook, and @refs, which may
3084 * be empty, is the list of extra references he returned along for us
3087 * In effect, the hook is an alternate creation routine for the class,
3088 * the object itself being already created by the runtime.
3091 TRACEME(("calling STORABLE_thaw on %s at 0x%lx (%d args)",
3092 class, (unsigned long) sv, AvFILLp(av) + 1));
3095 (void) scalar_call(rv, hook, clone, av, G_SCALAR|G_DISCARD);
3102 SvREFCNT_dec(frozen);
3105 if (!(flags & SHF_IDX_CLASSNAME) && class != buf)
3114 * Retrieve reference to some other scalar.
3115 * Layout is SX_REF <object>, with SX_REF already read.
3117 static SV *retrieve_ref(cxt)
3123 TRACEME(("retrieve_ref (#%d)", cxt->tagnum));
3126 * We need to create the SV that holds the reference to the yet-to-retrieve
3127 * object now, so that we may record the address in the seen table.
3128 * Otherwise, if the object to retrieve references us, we won't be able
3129 * to resolve the SX_OBJECT we'll see at that point! Hence we cannot
3130 * do the retrieve first and use rv = newRV(sv) since it will be too late
3131 * for SEEN() recording.
3134 rv = NEWSV(10002, 0);
3135 SEEN(rv); /* Will return if rv is null */
3136 sv = retrieve(cxt); /* Retrieve <object> */
3138 return (SV *) 0; /* Failed */
3141 * WARNING: breaks RV encapsulation.
3143 * Now for the tricky part. We have to upgrade our existing SV, so that
3144 * it is now an RV on sv... Again, we cheat by duplicating the code
3145 * held in newSVrv(), since we already got our SV from retrieve().
3149 * SvRV(rv) = SvREFCNT_inc(sv);
3151 * here because the reference count we got from retrieve() above is
3152 * already correct: if the object was retrieved from the file, then
3153 * its reference count is one. Otherwise, if it was retrieved via
3154 * an SX_OBJECT indication, a ref count increment was done.
3157 sv_upgrade(rv, SVt_RV);
3158 SvRV(rv) = sv; /* $rv = \$sv */
3161 TRACEME(("ok (retrieve_ref at 0x%lx)", (unsigned long) rv));
3167 * retrieve_overloaded
3169 * Retrieve reference to some other scalar with overloading.
3170 * Layout is SX_OVERLOAD <object>, with SX_OVERLOAD already read.
3172 static SV *retrieve_overloaded(cxt)
3179 TRACEME(("retrieve_overloaded (#%d)", cxt->tagnum));
3182 * Same code as retrieve_ref(), duplicated to avoid extra call.
3185 rv = NEWSV(10002, 0);
3186 SEEN(rv); /* Will return if rv is null */
3187 sv = retrieve(cxt); /* Retrieve <object> */
3189 return (SV *) 0; /* Failed */
3192 * WARNING: breaks RV encapsulation.
3195 sv_upgrade(rv, SVt_RV);
3196 SvRV(rv) = sv; /* $rv = \$sv */
3200 * Restore overloading magic.
3203 stash = (HV *) SvSTASH (sv);
3204 if (!stash || !Gv_AMG(stash))
3205 CROAK(("Cannot restore overloading on %s(0x%lx)", sv_reftype(sv, FALSE),
3206 (unsigned long) sv));
3210 TRACEME(("ok (retrieve_overloaded at 0x%lx)", (unsigned long) rv));
3216 * retrieve_tied_array
3218 * Retrieve tied array
3219 * Layout is SX_TIED_ARRAY <object>, with SX_TIED_ARRAY already read.
3221 static SV *retrieve_tied_array(cxt)
3227 TRACEME(("retrieve_tied_array (#%d)", cxt->tagnum));
3229 tv = NEWSV(10002, 0);
3230 SEEN(tv); /* Will return if tv is null */
3231 sv = retrieve(cxt); /* Retrieve <object> */
3233 return (SV *) 0; /* Failed */
3235 sv_upgrade(tv, SVt_PVAV);
3236 AvREAL_off((AV *)tv);
3237 sv_magic(tv, sv, 'P', Nullch, 0);
3238 SvREFCNT_dec(sv); /* Undo refcnt inc from sv_magic() */
3240 TRACEME(("ok (retrieve_tied_array at 0x%lx)", (unsigned long) tv));
3246 * retrieve_tied_hash
3248 * Retrieve tied hash
3249 * Layout is SX_TIED_HASH <object>, with SX_TIED_HASH already read.
3251 static SV *retrieve_tied_hash(cxt)
3257 TRACEME(("retrieve_tied_hash (#%d)", cxt->tagnum));
3259 tv = NEWSV(10002, 0);
3260 SEEN(tv); /* Will return if tv is null */
3261 sv = retrieve(cxt); /* Retrieve <object> */
3263 return (SV *) 0; /* Failed */
3265 sv_upgrade(tv, SVt_PVHV);
3266 sv_magic(tv, sv, 'P', Nullch, 0);
3267 SvREFCNT_dec(sv); /* Undo refcnt inc from sv_magic() */
3269 TRACEME(("ok (retrieve_tied_hash at 0x%lx)", (unsigned long) tv));
3275 * retrieve_tied_scalar
3277 * Retrieve tied scalar
3278 * Layout is SX_TIED_SCALAR <object>, with SX_TIED_SCALAR already read.
3280 static SV *retrieve_tied_scalar(cxt)
3286 TRACEME(("retrieve_tied_scalar (#%d)", cxt->tagnum));
3288 tv = NEWSV(10002, 0);
3289 SEEN(tv); /* Will return if rv is null */
3290 sv = retrieve(cxt); /* Retrieve <object> */
3292 return (SV *) 0; /* Failed */
3294 sv_upgrade(tv, SVt_PVMG);
3295 sv_magic(tv, sv, 'q', Nullch, 0);
3296 SvREFCNT_dec(sv); /* Undo refcnt inc from sv_magic() */
3298 TRACEME(("ok (retrieve_tied_scalar at 0x%lx)", (unsigned long) tv));
3306 * Retrieve reference to value in a tied hash.
3307 * Layout is SX_TIED_KEY <object> <key>, with SX_TIED_KEY already read.
3309 static SV *retrieve_tied_key(cxt)
3316 TRACEME(("retrieve_tied_key (#%d)", cxt->tagnum));
3318 tv = NEWSV(10002, 0);
3319 SEEN(tv); /* Will return if tv is null */
3320 sv = retrieve(cxt); /* Retrieve <object> */
3322 return (SV *) 0; /* Failed */
3324 key = retrieve(cxt); /* Retrieve <key> */
3326 return (SV *) 0; /* Failed */
3328 sv_upgrade(tv, SVt_PVMG);
3329 sv_magic(tv, sv, 'p', (char *)key, HEf_SVKEY);
3330 SvREFCNT_dec(key); /* Undo refcnt inc from sv_magic() */
3331 SvREFCNT_dec(sv); /* Undo refcnt inc from sv_magic() */
3339 * Retrieve reference to value in a tied array.
3340 * Layout is SX_TIED_IDX <object> <idx>, with SX_TIED_IDX already read.
3342 static SV *retrieve_tied_idx(cxt)
3349 TRACEME(("retrieve_tied_idx (#%d)", cxt->tagnum));
3351 tv = NEWSV(10002, 0);
3352 SEEN(tv); /* Will return if tv is null */
3353 sv = retrieve(cxt); /* Retrieve <object> */
3355 return (SV *) 0; /* Failed */
3357 RLEN(idx); /* Retrieve <idx> */
3359 sv_upgrade(tv, SVt_PVMG);
3360 sv_magic(tv, sv, 'p', Nullch, idx);
3361 SvREFCNT_dec(sv); /* Undo refcnt inc from sv_magic() */
3370 * Retrieve defined long (string) scalar.
3372 * Layout is SX_LSCALAR <length> <data>, with SX_LSCALAR already read.
3373 * The scalar is "long" in that <length> is larger than LG_SCALAR so it
3374 * was not stored on a single byte.
3376 static SV *retrieve_lscalar(cxt)
3383 TRACEME(("retrieve_lscalar (#%d), len = %d", cxt->tagnum, len));
3386 * Allocate an empty scalar of the suitable length.
3389 sv = NEWSV(10002, len);
3390 SEEN(sv); /* Associate this new scalar with tag "tagnum" */
3393 * WARNING: duplicates parts of sv_setpv and breaks SV data encapsulation.
3395 * Now, for efficiency reasons, read data directly inside the SV buffer,
3396 * and perform the SV final settings directly by duplicating the final
3397 * work done by sv_setpv. Since we're going to allocate lots of scalars
3398 * this way, it's worth the hassle and risk.
3401 SAFEREAD(SvPVX(sv), len, sv);
3402 SvCUR_set(sv, len); /* Record C string length */
3403 *SvEND(sv) = '\0'; /* Ensure it's null terminated anyway */
3404 (void) SvPOK_only(sv); /* Validate string pointer */
3405 SvTAINT(sv); /* External data cannot be trusted */
3407 TRACEME(("large scalar len %d '%s'", len, SvPVX(sv)));
3408 TRACEME(("ok (retrieve_lscalar at 0x%lx)", (unsigned long) sv));
3416 * Retrieve defined short (string) scalar.
3418 * Layout is SX_SCALAR <length> <data>, with SX_SCALAR already read.
3419 * The scalar is "short" so <length> is single byte. If it is 0, there
3420 * is no <data> section.
3422 static SV *retrieve_scalar(cxt)
3429 TRACEME(("retrieve_scalar (#%d), len = %d", cxt->tagnum, len));
3432 * Allocate an empty scalar of the suitable length.
3435 sv = NEWSV(10002, len);
3436 SEEN(sv); /* Associate this new scalar with tag "tagnum" */
3439 * WARNING: duplicates parts of sv_setpv and breaks SV data encapsulation.
3444 * newSV did not upgrade to SVt_PV so the scalar is undefined.
3445 * To make it defined with an empty length, upgrade it now...
3447 sv_upgrade(sv, SVt_PV);
3449 *SvEND(sv) = '\0'; /* Ensure it's null terminated anyway */
3450 TRACEME(("ok (retrieve_scalar empty at 0x%lx)", (unsigned long) sv));
3453 * Now, for efficiency reasons, read data directly inside the SV buffer,
3454 * and perform the SV final settings directly by duplicating the final
3455 * work done by sv_setpv. Since we're going to allocate lots of scalars
3456 * this way, it's worth the hassle and risk.
3458 SAFEREAD(SvPVX(sv), len, sv);
3459 SvCUR_set(sv, len); /* Record C string length */
3460 *SvEND(sv) = '\0'; /* Ensure it's null terminated anyway */
3461 TRACEME(("small scalar len %d '%s'", len, SvPVX(sv)));
3464 (void) SvPOK_only(sv); /* Validate string pointer */
3465 SvTAINT(sv); /* External data cannot be trusted */
3467 TRACEME(("ok (retrieve_scalar at 0x%lx)", (unsigned long) sv));
3474 * Retrieve defined integer.
3475 * Layout is SX_INTEGER <data>, whith SX_INTEGER already read.
3477 static SV *retrieve_integer(cxt)
3483 TRACEME(("retrieve_integer (#%d)", cxt->tagnum));
3485 READ(&iv, sizeof(iv));
3487 SEEN(sv); /* Associate this new scalar with tag "tagnum" */
3489 TRACEME(("integer %d", iv));
3490 TRACEME(("ok (retrieve_integer at 0x%lx)", (unsigned long) sv));
3498 * Retrieve defined integer in network order.
3499 * Layout is SX_NETINT <data>, whith SX_NETINT already read.
3501 static SV *retrieve_netint(cxt)
3507 TRACEME(("retrieve_netint (#%d)", cxt->tagnum));
3509 READ(&iv, sizeof(iv));
3511 sv = newSViv((int) ntohl(iv));
3512 TRACEME(("network integer %d", (int) ntohl(iv)));
3515 TRACEME(("network integer (as-is) %d", iv));
3517 SEEN(sv); /* Associate this new scalar with tag "tagnum" */
3519 TRACEME(("ok (retrieve_netint at 0x%lx)", (unsigned long) sv));
3527 * Retrieve defined double.
3528 * Layout is SX_DOUBLE <data>, whith SX_DOUBLE already read.
3530 static SV *retrieve_double(cxt)
3536 TRACEME(("retrieve_double (#%d)", cxt->tagnum));
3538 READ(&nv, sizeof(nv));
3540 SEEN(sv); /* Associate this new scalar with tag "tagnum" */
3542 TRACEME(("double %lf", nv));
3543 TRACEME(("ok (retrieve_double at 0x%lx)", (unsigned long) sv));
3551 * Retrieve defined byte (small integer within the [-128, +127] range).
3552 * Layout is SX_BYTE <data>, whith SX_BYTE already read.
3554 static SV *retrieve_byte(cxt)
3560 TRACEME(("retrieve_byte (#%d)", cxt->tagnum));
3563 TRACEME(("small integer read as %d", (unsigned char) siv));
3564 sv = newSViv((unsigned char) siv - 128);
3565 SEEN(sv); /* Associate this new scalar with tag "tagnum" */
3567 TRACEME(("byte %d", (unsigned char) siv - 128));
3568 TRACEME(("ok (retrieve_byte at 0x%lx)", (unsigned long) sv));
3576 * Return the undefined value.
3578 static SV *retrieve_undef(cxt)
3583 TRACEME(("retrieve_undef"));
3594 * Return the immortal undefined value.
3596 static SV *retrieve_sv_undef(cxt)
3599 SV *sv = &PL_sv_undef;
3601 TRACEME(("retrieve_sv_undef"));
3610 * Return the immortal yes value.
3612 static SV *retrieve_sv_yes(cxt)
3615 SV *sv = &PL_sv_yes;
3617 TRACEME(("retrieve_sv_yes"));
3626 * Return the immortal no value.
3628 static SV *retrieve_sv_no(cxt)
3633 TRACEME(("retrieve_sv_no"));
3642 * Retrieve a whole array.
3643 * Layout is SX_ARRAY <size> followed by each item, in increading index order.
3644 * Each item is stored as <object>.
3646 * When we come here, SX_ARRAY has been read already.
3648 static SV *retrieve_array(cxt)
3656 TRACEME(("retrieve_array (#%d)", cxt->tagnum));
3659 * Read length, and allocate array, then pre-extend it.
3663 TRACEME(("size = %d", len));
3665 SEEN(av); /* Will return if array not allocated nicely */
3669 return (SV *) av; /* No data follow if array is empty */
3672 * Now get each item in turn...
3675 for (i = 0; i < len; i++) {
3676 TRACEME(("(#%d) item", i));
3677 sv = retrieve(cxt); /* Retrieve item */
3680 if (av_store(av, i, sv) == 0)
3684 TRACEME(("ok (retrieve_array at 0x%lx)", (unsigned long) av));
3692 * Retrieve a whole hash table.
3693 * Layout is SX_HASH <size> followed by each key/value pair, in random order.
3694 * Keys are stored as <length> <data>, the <data> section being omitted
3696 * Values are stored as <object>.
3698 * When we come here, SX_HASH has been read already.
3700 static SV *retrieve_hash(cxt)
3708 static SV *sv_h_undef = (SV *) 0; /* hv_store() bug */
3710 TRACEME(("retrieve_hash (#%d)", cxt->tagnum));
3713 * Read length, allocate table.
3717 TRACEME(("size = %d", len));
3719 SEEN(hv); /* Will return if table not allocated properly */
3721 return (SV *) hv; /* No data follow if table empty */
3724 * Now get each key/value pair in turn...
3727 for (i = 0; i < len; i++) {
3732 TRACEME(("(#%d) value", i));
3739 * Since we're reading into kbuf, we must ensure we're not
3740 * recursing between the read and the hv_store() where it's used.
3741 * Hence the key comes after the value.
3744 RLEN(size); /* Get key size */
3745 KBUFCHK(size); /* Grow hash key read pool if needed */
3748 kbuf[size] = '\0'; /* Mark string end, just in case */
3749 TRACEME(("(#%d) key '%s'", i, kbuf));
3752 * Enter key/value pair into hash table.
3755 if (hv_store(hv, kbuf, (U32) size, sv, 0) == 0)
3759 TRACEME(("ok (retrieve_hash at 0x%lx)", (unsigned long) hv));
3765 * old_retrieve_array
3767 * Retrieve a whole array in pre-0.6 binary format.
3769 * Layout is SX_ARRAY <size> followed by each item, in increading index order.
3770 * Each item is stored as SX_ITEM <object> or SX_IT_UNDEF for "holes".
3772 * When we come here, SX_ARRAY has been read already.
3774 static SV *old_retrieve_array(cxt)
3783 TRACEME(("old_retrieve_array (#%d)", cxt->tagnum));
3786 * Read length, and allocate array, then pre-extend it.
3790 TRACEME(("size = %d", len));
3792 SEEN(av); /* Will return if array not allocated nicely */
3796 return (SV *) av; /* No data follow if array is empty */
3799 * Now get each item in turn...
3802 for (i = 0; i < len; i++) {
3804 if (c == SX_IT_UNDEF) {
3805 TRACEME(("(#%d) undef item", i));
3806 continue; /* av_extend() already filled us with undef */
3809 (void) retrieve_other(0); /* Will croak out */
3810 TRACEME(("(#%d) item", i));
3811 sv = retrieve(cxt); /* Retrieve item */
3814 if (av_store(av, i, sv) == 0)
3818 TRACEME(("ok (old_retrieve_array at 0x%lx)", (unsigned long) av));
3826 * Retrieve a whole hash table in pre-0.6 binary format.
3828 * Layout is SX_HASH <size> followed by each key/value pair, in random order.
3829 * Keys are stored as SX_KEY <length> <data>, the <data> section being omitted
3831 * Values are stored as SX_VALUE <object> or SX_VL_UNDEF for "holes".
3833 * When we come here, SX_HASH has been read already.
3835 static SV *old_retrieve_hash(cxt)
3844 static SV *sv_h_undef = (SV *) 0; /* hv_store() bug */
3846 TRACEME(("old_retrieve_hash (#%d)", cxt->tagnum));
3849 * Read length, allocate table.
3853 TRACEME(("size = %d", len));
3855 SEEN(hv); /* Will return if table not allocated properly */
3857 return (SV *) hv; /* No data follow if table empty */
3860 * Now get each key/value pair in turn...
3863 for (i = 0; i < len; i++) {
3869 if (c == SX_VL_UNDEF) {
3870 TRACEME(("(#%d) undef value", i));
3872 * Due to a bug in hv_store(), it's not possible to pass
3873 * &PL_sv_undef to hv_store() as a value, otherwise the
3874 * associated key will not be creatable any more. -- RAM, 14/01/97
3877 sv_h_undef = newSVsv(&PL_sv_undef);
3878 sv = SvREFCNT_inc(sv_h_undef);
3879 } else if (c == SX_VALUE) {
3880 TRACEME(("(#%d) value", i));
3885 (void) retrieve_other(0); /* Will croak out */
3889 * Since we're reading into kbuf, we must ensure we're not
3890 * recursing between the read and the hv_store() where it's used.
3891 * Hence the key comes after the value.
3896 (void) retrieve_other(0); /* Will croak out */
3897 RLEN(size); /* Get key size */
3898 KBUFCHK(size); /* Grow hash key read pool if needed */
3901 kbuf[size] = '\0'; /* Mark string end, just in case */
3902 TRACEME(("(#%d) key '%s'", i, kbuf));
3905 * Enter key/value pair into hash table.
3908 if (hv_store(hv, kbuf, (U32) size, sv, 0) == 0)
3912 TRACEME(("ok (retrieve_hash at 0x%lx)", (unsigned long) hv));
3918 *** Retrieval engine.
3924 * Make sure the stored data we're trying to retrieve has been produced
3925 * on an ILP compatible system with the same byteorder. It croaks out in
3926 * case an error is detected. [ILP = integer-long-pointer sizes]
3927 * Returns null if error is detected, &PL_sv_undef otherwise.
3929 * Note that there's no byte ordering info emitted when network order was
3930 * used at store time.
3932 static SV *magic_check(cxt)
3936 char byteorder[256];
3938 int use_network_order;
3940 int version_minor = 0;
3942 TRACEME(("magic_check"));
3945 * The "magic number" is only for files, not when freezing in memory.
3949 STRLEN len = sizeof(magicstr) - 1;
3952 READ(buf, len); /* Not null-terminated */
3953 buf[len] = '\0'; /* Is now */
3955 if (0 == strcmp(buf, magicstr))
3959 * Try to read more bytes to check for the old magic number, which
3963 old_len = sizeof(old_magicstr) - 1;
3964 READ(&buf[len], old_len - len);
3965 buf[old_len] = '\0'; /* Is now null-terminated */
3967 if (strcmp(buf, old_magicstr))
3968 CROAK(("File is not a perl storable"));
3973 * Starting with 0.6, the "use_network_order" byte flag is also used to
3974 * indicate the version number of the binary, and therefore governs the
3975 * setting of sv_retrieve_vtbl. See magic_write().
3978 GETMARK(use_network_order);
3979 version_major = use_network_order >> 1;
3980 cxt->retrieve_vtbl = version_major ? sv_retrieve : sv_old_retrieve;
3982 TRACEME(("magic_check: netorder = 0x%x", use_network_order));
3986 * Starting with 0.7 (binary major 2), a full byte is dedicated to the
3987 * minor version of the protocol. See magic_write().
3990 if (version_major > 1)
3991 GETMARK(version_minor);
3993 cxt->ver_major = version_major;
3994 cxt->ver_minor = version_minor;
3996 TRACEME(("binary image version is %d.%d", version_major, version_minor));
3999 * Inter-operability sanity check: we can't retrieve something stored
4000 * using a format more recent than ours, because we have no way to
4001 * know what has changed, and letting retrieval go would mean a probable
4002 * failure reporting a "corrupted" storable file.
4006 version_major > STORABLE_BIN_MAJOR ||
4007 (version_major == STORABLE_BIN_MAJOR &&
4008 version_minor > STORABLE_BIN_MINOR)
4010 CROAK(("Storable binary image v%d.%d more recent than I am (v%d.%d)",
4011 version_major, version_minor,
4012 STORABLE_BIN_MAJOR, STORABLE_BIN_MINOR));
4015 * If they stored using network order, there's no byte ordering
4016 * information to check.
4019 if (cxt->netorder = (use_network_order & 0x1))
4020 return &PL_sv_undef; /* No byte ordering info */
4022 sprintf(byteorder, "%lx", (unsigned long) BYTEORDER);
4024 READ(buf, c); /* Not null-terminated */
4025 buf[c] = '\0'; /* Is now */
4027 if (strcmp(buf, byteorder))
4028 CROAK(("Byte order is not compatible"));
4030 GETMARK(c); /* sizeof(int) */
4031 if ((int) c != sizeof(int))
4032 CROAK(("Integer size is not compatible"));
4034 GETMARK(c); /* sizeof(long) */
4035 if ((int) c != sizeof(long))
4036 CROAK(("Long integer size is not compatible"));
4038 GETMARK(c); /* sizeof(char *) */
4039 if ((int) c != sizeof(char *))
4040 CROAK(("Pointer integer size is not compatible"));
4042 return &PL_sv_undef; /* OK */
4048 * Recursively retrieve objects from the specified file and return their
4049 * root SV (which may be an AV or an HV for what we care).
4050 * Returns null if there is a problem.
4052 static SV *retrieve(cxt)
4059 TRACEME(("retrieve"));
4062 * Grab address tag which identifies the object if we are retrieving
4063 * an older format. Since the new binary format counts objects and no
4064 * longer explicitely tags them, we must keep track of the correspondance
4067 * The following section will disappear one day when the old format is
4068 * no longer supported, hence the final "goto" in the "if" block.
4071 if (cxt->hseen) { /* Retrieving old binary */
4073 if (cxt->netorder) {
4075 READ(&nettag, sizeof(I32)); /* Ordered sequence of I32 */
4076 tag = (stag_t) nettag;
4078 READ(&tag, sizeof(stag_t)); /* Original address of the SV */
4081 if (type == SX_OBJECT) {
4083 svh = hv_fetch(cxt->hseen, (char *) &tag, sizeof(tag), FALSE);
4085 CROAK(("Old tag 0x%x should have been mapped already", tag));
4086 tagn = SvIV(*svh); /* Mapped tag number computed earlier below */
4089 * The following code is common with the SX_OBJECT case below.
4092 svh = av_fetch(cxt->aseen, tagn, FALSE);
4094 CROAK(("Object #%d should have been retrieved already", tagn));
4096 TRACEME(("has retrieved #%d at 0x%lx", tagn, (unsigned long) sv));
4097 SvREFCNT_inc(sv); /* One more reference to this same sv */
4098 return sv; /* The SV pointer where object was retrieved */
4102 * Map new object, but don't increase tagnum. This will be done
4103 * by each of the retrieve_* functions when they call SEEN().
4105 * The mapping associates the "tag" initially present with a unique
4106 * tag number. See test for SX_OBJECT above to see how this is perused.
4109 if (!hv_store(cxt->hseen, (char *) &tag, sizeof(tag),
4110 newSViv(cxt->tagnum), 0))
4117 * Regular post-0.6 binary format.
4123 TRACEME(("retrieve type = %d", type));
4126 * Are we dealing with an object we should have already retrieved?
4129 if (type == SX_OBJECT) {
4131 READ(&tag, sizeof(I32));
4133 svh = av_fetch(cxt->aseen, tag, FALSE);
4135 CROAK(("Object #%d should have been retrieved already", tag));
4137 TRACEME(("had retrieved #%d at 0x%lx", tag, (unsigned long) sv));
4138 SvREFCNT_inc(sv); /* One more reference to this same sv */
4139 return sv; /* The SV pointer where object was retrieved */
4142 first_time: /* Will disappear when support for old format is dropped */
4145 * Okay, first time through for this one.
4148 sv = RETRIEVE(cxt, type)(cxt);
4150 return (SV *) 0; /* Failed */
4153 * Old binary formats (pre-0.7).
4155 * Final notifications, ended by SX_STORED may now follow.
4156 * Currently, the only pertinent notification to apply on the
4157 * freshly retrieved object is either:
4158 * SX_CLASS <char-len> <classname> for short classnames.
4159 * SX_LG_CLASS <int-len> <classname> for larger one (rare!).
4160 * Class name is then read into the key buffer pool used by
4161 * hash table key retrieval.
4164 if (cxt->ver_major < 2) {
4165 while ((type = GETCHAR()) != SX_STORED) {
4169 GETMARK(len); /* Length coded on a single char */
4171 case SX_LG_CLASS: /* Length coded on a regular integer */
4176 return (SV *) 0; /* Failed */
4178 KBUFCHK(len); /* Grow buffer as necessary */
4181 kbuf[len] = '\0'; /* Mark string end */
4186 TRACEME(("ok (retrieved 0x%lx, refcnt=%d, %s)", (unsigned long) sv,
4187 SvREFCNT(sv) - 1, sv_reftype(sv, FALSE)));
4195 * Retrieve data held in file and return the root object.
4196 * Common routine for pretrieve and mretrieve.
4198 static SV *do_retrieve(f, in, optype)
4205 struct extendable msave; /* Where potentially valid mbuf is saved */
4207 TRACEME(("do_retrieve (optype = 0x%x)", optype));
4209 optype |= ST_RETRIEVE;
4212 * Sanity assertions for retrieve dispatch tables.
4215 ASSERT(sizeof(sv_old_retrieve) == sizeof(sv_retrieve),
4216 ("old and new retrieve dispatch table have same size"));
4217 ASSERT(sv_old_retrieve[SX_ERROR] == retrieve_other,
4218 ("SX_ERROR entry correctly initialized in old dispatch table"));
4219 ASSERT(sv_retrieve[SX_ERROR] == retrieve_other,
4220 ("SX_ERROR entry correctly initialized in new dispatch table"));
4223 * Workaround for CROAK leak: if they enter with a "dirty" context,
4224 * free up memory for them now.
4231 * Now that STORABLE_xxx hooks exist, it is possible that they try to
4232 * re-enter retrieve() via the hooks.
4236 cxt = allocate_context(cxt);
4240 ASSERT(cxt->entry == 1, ("starting new recursion"));
4241 ASSERT(!cxt->dirty, ("clean context"));
4246 * Data is loaded into the memory buffer when f is NULL, unless `in' is
4247 * also NULL, in which case we're expecting the data to already lie
4248 * in the buffer (dclone case).
4251 KBUFINIT(); /* Allocate hash key reading pool once */
4254 StructCopy(&cxt->membuf, &msave, struct extendable);
4260 * Magic number verifications.
4262 * This needs to be done before calling init_retrieve_context()
4263 * since the format indication in the file are necessary to conduct
4264 * some of the initializations.
4267 cxt->fio = f; /* Where I/O are performed */
4269 if (!magic_check(cxt))
4270 CROAK(("Magic number checking on storable %s failed",
4271 cxt->fio ? "file" : "string"));
4273 TRACEME(("data stored in %s format",
4274 cxt->netorder ? "net order" : "native"));
4276 init_retrieve_context(cxt, optype);
4278 ASSERT(is_retrieving(), ("within retrieve operation"));
4280 sv = retrieve(cxt); /* Recursively retrieve object, get root SV */
4287 StructCopy(&msave, &cxt->membuf, struct extendable);
4290 * The "root" context is never freed.
4293 clean_retrieve_context(cxt);
4294 if (cxt->prev) /* This context was stacked */
4295 free_context(cxt); /* It was not the "root" context */
4298 * Prepare returned value.
4302 TRACEME(("retrieve ERROR"));
4303 return &PL_sv_undef; /* Something went wrong, return undef */
4306 TRACEME(("retrieve got %s(0x%lx)",
4307 sv_reftype(sv, FALSE), (unsigned long) sv));
4310 * Backward compatibility with Storable-0.5@9 (which we know we
4311 * are retrieving if hseen is non-null): don't create an extra RV
4312 * for objects since we special-cased it at store time.
4314 * Build a reference to the SV returned by pretrieve even if it is
4315 * already one and not a scalar, for consistency reasons.
4317 * NB: although context might have been cleaned, the value of `cxt->hseen'
4318 * remains intact, and can be used as a flag.
4321 if (cxt->hseen) { /* Was not handling overloading by then */
4323 if (sv_type(sv) == svis_REF && (rv = SvRV(sv)) && SvOBJECT(rv))
4328 * If reference is overloaded, restore behaviour.
4330 * NB: minor glitch here: normally, overloaded refs are stored specially
4331 * so that we can croak when behaviour cannot be re-installed, and also
4332 * avoid testing for overloading magic at each reference retrieval.
4334 * Unfortunately, the root reference is implicitely stored, so we must
4335 * check for possible overloading now. Furthermore, if we don't restore
4336 * overloading, we cannot croak as if the original ref was, because we
4337 * have no way to determine whether it was an overloaded ref or not in
4340 * It's a pity that overloading magic is attached to the rv, and not to
4341 * the underlying sv as blessing is.
4345 HV *stash = (HV *) SvSTASH (sv);
4346 SV *rv = newRV_noinc(sv);
4347 if (stash && Gv_AMG(stash)) {
4349 TRACEME(("restored overloading on root reference"));
4354 return newRV_noinc(sv);
4360 * Retrieve data held in file and return the root object, undef on error.
4365 TRACEME(("pretrieve"));
4366 return do_retrieve(f, Nullsv, 0);
4372 * Retrieve data held in scalar and return the root object, undef on error.
4377 TRACEME(("mretrieve"));
4378 return do_retrieve(0, sv, 0);
4388 * Deep clone: returns a fresh copy of the original referenced SV tree.
4390 * This is achieved by storing the object in memory and restoring from
4391 * there. Not that efficient, but it should be faster than doing it from
4399 stcxt_t *real_context;
4402 TRACEME(("dclone"));
4405 * Workaround for CROAK leak: if they enter with a "dirty" context,
4406 * free up memory for them now.
4413 * do_store() optimizes for dclone by not freeing its context, should
4414 * we need to allocate one because we're deep cloning from a hook.
4417 if (!do_store(0, sv, ST_CLONE, FALSE, Nullsv))
4418 return &PL_sv_undef; /* Error during store */
4421 * Because of the above optimization, we have to refresh the context,
4422 * since a new one could have been allocated and stacked by do_store().
4425 { dSTCXT; real_context = cxt; } /* Sub-block needed for macro */
4426 cxt = real_context; /* And we need this temporary... */
4429 * Now, `cxt' may refer to a new context.
4432 ASSERT(!cxt->dirty, ("clean context"));
4433 ASSERT(!cxt->entry, ("entry will not cause new context allocation"));
4436 TRACEME(("dclone stored %d bytes", size));
4439 out = do_retrieve(0, Nullsv, ST_CLONE); /* Will free non-root context */
4441 TRACEME(("dclone returns 0x%lx", (unsigned long) out));
4451 * The Perl IO GV object distinguishes between input and output for sockets
4452 * but not for plain files. To allow Storable to transparently work on
4453 * plain files and sockets transparently, we have to ask xsubpp to fetch the
4454 * right object for us. Hence the OutputStream and InputStream declarations.
4456 * Before perl 5.004_05, those entries in the standard typemap are not
4457 * defined in perl include files, so we do that here.
4460 #ifndef OutputStream
4461 #define OutputStream PerlIO *
4462 #define InputStream PerlIO *
4463 #endif /* !OutputStream */
4465 MODULE = Storable PACKAGE = Storable
4503 last_op_in_netorder()