2 * Store and retrieve mechanism.
6 * $Id: Storable.xs,v 1.0 2000/09/01 19:40:41 ram Exp $
8 * Copyright (c) 1995-2000, Raphael Manfredi
10 * You may redistribute only under the same terms as Perl 5, as specified
11 * in the README file that comes with the distribution.
13 * $Log: Storable.xs,v $
14 * Revision 1.0 2000/09/01 19:40:41 ram
15 * Baseline for first official release.
21 #include <patchlevel.h> /* Perl's one, needed since 5.6 */
25 #define DEBUGME /* Debug mode, turns assertions on as well */
26 #define DASSERT /* Assertion mode */
30 * Pre PerlIO time when none of USE_PERLIO and PERLIO_IS_STDIO is defined
31 * Provide them with the necessary defines so they can build with pre-5.004.
34 #ifndef PERLIO_IS_STDIO
36 #define PerlIO_getc(x) getc(x)
37 #define PerlIO_putc(f,x) putc(x,f)
38 #define PerlIO_read(x,y,z) fread(y,1,z,x)
39 #define PerlIO_write(x,y,z) fwrite(y,1,z,x)
40 #define PerlIO_stdoutf printf
41 #endif /* PERLIO_IS_STDIO */
42 #endif /* USE_PERLIO */
45 * Earlier versions of perl might be used, we can't assume they have the latest!
48 #ifndef PERL_VERSION /* For perls < 5.6 */
49 #define PERL_VERSION PATCHLEVEL
51 #define newRV_noinc(sv) ((Sv = newRV(sv)), --SvREFCNT(SvRV(Sv)), Sv)
53 #if (PATCHLEVEL <= 4) /* Older perls (<= 5.004) lack PL_ namespace */
54 #define PL_sv_yes sv_yes
55 #define PL_sv_no sv_no
56 #define PL_sv_undef sv_undef
57 #if (SUBVERSION <= 4) /* 5.004_04 has been reported to lack newSVpvn */
58 #define newSVpvn newSVpv
60 #endif /* PATCHLEVEL <= 4 */
61 #ifndef HvSHAREKEYS_off
62 #define HvSHAREKEYS_off(hv) /* Ignore */
64 #ifndef AvFILLp /* Older perls (<=5.003) lack AvFILLp */
65 #define AvFILLp AvFILL
67 typedef double NV; /* Older perls lack the NV type */
68 #define IVdf "ld" /* Various printf formats for Perl types */
72 #define INT2PTR(t,v) (t)(IV)(v)
73 #define PTR2UV(v) (unsigned long)(v)
74 #endif /* PERL_VERSION -- perls < 5.6 */
76 #ifndef NVef /* The following were not part of perl 5.6 */
77 #if defined(USE_LONG_DOUBLE) && \
78 defined(HAS_LONG_DOUBLE) && defined(PERL_PRIfldbl)
79 #define NVef PERL_PRIeldbl
80 #define NVff PERL_PRIfldbl
81 #define NVgf PERL_PRIgldbl
93 #define TRACEME(x) do { PerlIO_stdoutf x; PerlIO_stdoutf("\n"); } while (0)
99 #define ASSERT(x,y) do { \
101 PerlIO_stdoutf("ASSERT FAILED (\"%s\", line %d): ", \
102 __FILE__, __LINE__); \
103 PerlIO_stdoutf y; PerlIO_stdoutf("\n"); \
114 #define C(x) ((char) (x)) /* For markers with dynamic retrieval handling */
116 #define SX_OBJECT C(0) /* Already stored object */
117 #define SX_LSCALAR C(1) /* Scalar (large binary) follows (length, data) */
118 #define SX_ARRAY C(2) /* Array forthcominng (size, item list) */
119 #define SX_HASH C(3) /* Hash forthcoming (size, key/value pair list) */
120 #define SX_REF C(4) /* Reference to object forthcoming */
121 #define SX_UNDEF C(5) /* Undefined scalar */
122 #define SX_INTEGER C(6) /* Integer forthcoming */
123 #define SX_DOUBLE C(7) /* Double forthcoming */
124 #define SX_BYTE C(8) /* (signed) byte forthcoming */
125 #define SX_NETINT C(9) /* Integer in network order forthcoming */
126 #define SX_SCALAR C(10) /* Scalar (binary, small) follows (length, data) */
127 #define SX_TIED_ARRAY C(11) /* Tied array forthcoming */
128 #define SX_TIED_HASH C(12) /* Tied hash forthcoming */
129 #define SX_TIED_SCALAR C(13) /* Tied scalar forthcoming */
130 #define SX_SV_UNDEF C(14) /* Perl's immortal PL_sv_undef */
131 #define SX_SV_YES C(15) /* Perl's immortal PL_sv_yes */
132 #define SX_SV_NO C(16) /* Perl's immortal PL_sv_no */
133 #define SX_BLESS C(17) /* Object is blessed */
134 #define SX_IX_BLESS C(18) /* Object is blessed, classname given by index */
135 #define SX_HOOK C(19) /* Stored via hook, user-defined */
136 #define SX_OVERLOAD C(20) /* Overloaded reference */
137 #define SX_TIED_KEY C(21) /* Tied magic key forthcoming */
138 #define SX_TIED_IDX C(22) /* Tied magic index forthcoming */
139 #define SX_UTF8STR C(23) /* UTF-8 string forthcoming (small) */
140 #define SX_LUTF8STR C(24) /* UTF-8 string forthcoming (large) */
141 #define SX_ERROR C(25) /* Error */
144 * Those are only used to retrieve "old" pre-0.6 binary images.
146 #define SX_ITEM 'i' /* An array item introducer */
147 #define SX_IT_UNDEF 'I' /* Undefined array item */
148 #define SX_KEY 'k' /* An hash key introducer */
149 #define SX_VALUE 'v' /* An hash value introducer */
150 #define SX_VL_UNDEF 'V' /* Undefined hash value */
153 * Those are only used to retrieve "old" pre-0.7 binary images
156 #define SX_CLASS 'b' /* Object is blessed, class name length <255 */
157 #define SX_LG_CLASS 'B' /* Object is blessed, class name length >255 */
158 #define SX_STORED 'X' /* End of object */
161 * Limits between short/long length representation.
164 #define LG_SCALAR 255 /* Large scalar length limit */
165 #define LG_BLESS 127 /* Large classname bless limit */
171 #define ST_STORE 0x1 /* Store operation */
172 #define ST_RETRIEVE 0x2 /* Retrieval operation */
173 #define ST_CLONE 0x4 /* Deep cloning operation */
176 * The following structure is used for hash table key retrieval. Since, when
177 * retrieving objects, we'll be facing blessed hash references, it's best
178 * to pre-allocate that buffer once and resize it as the need arises, never
179 * freeing it (keys will be saved away someplace else anyway, so even large
180 * keys are not enough a motivation to reclaim that space).
182 * This structure is also used for memory store/retrieve operations which
183 * happen in a fixed place before being malloc'ed elsewhere if persistency
184 * is required. Hence the aptr pointer.
187 char *arena; /* Will hold hash key strings, resized as needed */
188 STRLEN asiz; /* Size of aforementionned buffer */
189 char *aptr; /* Arena pointer, for in-place read/write ops */
190 char *aend; /* First invalid address */
195 * An hash table records the objects which have already been stored.
196 * Those are referred to as SX_OBJECT in the file, and their "tag" (i.e.
197 * an arbitrary sequence number) is used to identify them.
200 * An array table records the objects which have already been retrieved,
201 * as seen by the tag determind by counting the objects themselves. The
202 * reference to that retrieved object is kept in the table, and is returned
203 * when an SX_OBJECT is found bearing that same tag.
205 * The same processing is used to record "classname" for blessed objects:
206 * indexing by a hash at store time, and via an array at retrieve time.
209 typedef unsigned long stag_t; /* Used by pre-0.6 binary format */
212 * The following "thread-safe" related defines were contributed by
213 * Murray Nesbitt <murray@activestate.com> and integrated by RAM, who
214 * only renamed things a little bit to ensure consistency with surrounding
215 * code. -- RAM, 14/09/1999
217 * The original patch suffered from the fact that the stcxt_t structure
218 * was global. Murray tried to minimize the impact on the code as much as
221 * Starting with 0.7, Storable can be re-entrant, via the STORABLE_xxx hooks
222 * on objects. Therefore, the notion of context needs to be generalized,
226 #define MY_VERSION "Storable(" XS_VERSION ")"
229 * Fields s_tainted and s_dirty are prefixed with s_ because Perl's include
230 * files remap tainted and dirty when threading is enabled. That's bad for
231 * perl to remap such common words. -- RAM, 29/09/00
234 typedef struct stcxt {
235 int entry; /* flags recursion */
236 int optype; /* type of traversal operation */
237 HV *hseen; /* which objects have been seen, store time */
238 AV *aseen; /* which objects have been seen, retrieve time */
239 HV *hclass; /* which classnames have been seen, store time */
240 AV *aclass; /* which classnames have been seen, retrieve time */
241 HV *hook; /* cache for hook methods per class name */
242 I32 tagnum; /* incremented at store time for each seen object */
243 I32 classnum; /* incremented at store time for each seen classname */
244 int netorder; /* true if network order used */
245 int s_tainted; /* true if input source is tainted, at retrieve time */
246 int forgive_me; /* whether to be forgiving... */
247 int canonical; /* whether to store hashes sorted by key */
248 int s_dirty; /* context is dirty due to CROAK() -- can be cleaned */
249 struct extendable keybuf; /* for hash key retrieval */
250 struct extendable membuf; /* for memory store/retrieve operations */
251 PerlIO *fio; /* where I/O are performed, NULL for memory */
252 int ver_major; /* major of version for retrieved object */
253 int ver_minor; /* minor of version for retrieved object */
254 SV *(**retrieve_vtbl)(); /* retrieve dispatch table */
255 struct stcxt *prev; /* contexts chained backwards in real recursion */
258 #if defined(MULTIPLICITY) || defined(PERL_OBJECT) || defined(PERL_CAPI)
260 #if (PATCHLEVEL <= 4) && (SUBVERSION < 68)
262 SV *perinterp_sv = perl_get_sv(MY_VERSION, FALSE)
263 #else /* >= perl5.004_68 */
265 SV *perinterp_sv = *hv_fetch(PL_modglobal, \
266 MY_VERSION, sizeof(MY_VERSION)-1, TRUE)
267 #endif /* < perl5.004_68 */
269 #define dSTCXT_PTR(T,name) \
270 T name = (perinterp_sv && SvIOK(perinterp_sv) \
271 ? INT2PTR(T, SvIVX(perinterp_sv)) : (T) 0)
274 dSTCXT_PTR(stcxt_t *, cxt)
278 Newz(0, cxt, 1, stcxt_t); \
279 sv_setiv(perinterp_sv, PTR2IV(cxt))
281 #define SET_STCXT(x) do { \
283 sv_setiv(perinterp_sv, PTR2IV(x)); \
286 #else /* !MULTIPLICITY && !PERL_OBJECT && !PERL_CAPI */
288 static stcxt_t Context;
289 static stcxt_t *Context_ptr = &Context;
290 #define dSTCXT stcxt_t *cxt = Context_ptr
291 #define INIT_STCXT dSTCXT
292 #define SET_STCXT(x) Context_ptr = x
294 #endif /* MULTIPLICITY || PERL_OBJECT || PERL_CAPI */
298 * Croaking implies a memory leak, since we don't use setjmp/longjmp
299 * to catch the exit and free memory used during store or retrieve
300 * operations. This is not too difficult to fix, but I need to understand
301 * how Perl does it, and croaking is exceptional anyway, so I lack the
302 * motivation to do it.
304 * The current workaround is to mark the context as dirty when croaking,
305 * so that data structures can be freed whenever we renter Storable code
306 * (but only *then*: it's a workaround, not a fix).
308 * This is also imperfect, because we don't really know how far they trapped
309 * the croak(), and when we were recursing, we won't be able to clean anything
310 * but the topmost context stacked.
313 #define CROAK(x) do { cxt->s_dirty = 1; croak x; } while (0)
316 * End of "thread-safe" related definitions.
322 * Keep only the low 32 bits of a pointer (used for tags, which are not
327 #define LOW_32BITS(x) ((I32) (x))
329 #define LOW_32BITS(x) ((I32) ((unsigned long) (x) & 0xffffffffUL))
335 * Hack for Crays, where sizeof(I32) == 8, and which are big-endians.
336 * Used in the WLEN and RLEN macros.
340 #define oI(x) ((I32 *) ((char *) (x) + 4))
341 #define oS(x) ((x) - 4)
342 #define oC(x) (x = 0)
351 * key buffer handling
353 #define kbuf (cxt->keybuf).arena
354 #define ksiz (cxt->keybuf).asiz
355 #define KBUFINIT() do { \
357 TRACEME(("** allocating kbuf of 128 bytes")); \
358 New(10003, kbuf, 128, char); \
362 #define KBUFCHK(x) do { \
364 TRACEME(("** extending kbuf to %d bytes", x+1)); \
365 Renew(kbuf, x+1, char); \
371 * memory buffer handling
373 #define mbase (cxt->membuf).arena
374 #define msiz (cxt->membuf).asiz
375 #define mptr (cxt->membuf).aptr
376 #define mend (cxt->membuf).aend
378 #define MGROW (1 << 13)
379 #define MMASK (MGROW - 1)
381 #define round_mgrow(x) \
382 ((unsigned long) (((unsigned long) (x) + MMASK) & ~MMASK))
383 #define trunc_int(x) \
384 ((unsigned long) ((unsigned long) (x) & ~(sizeof(int)-1)))
385 #define int_aligned(x) \
386 ((unsigned long) (x) == trunc_int(x))
388 #define MBUF_INIT(x) do { \
390 TRACEME(("** allocating mbase of %d bytes", MGROW)); \
391 New(10003, mbase, MGROW, char); \
398 mend = mbase + msiz; \
401 #define MBUF_TRUNC(x) mptr = mbase + x
402 #define MBUF_SIZE() (mptr - mbase)
405 * Use SvPOKp(), because SvPOK() fails on tainted scalars.
406 * See store_scalar() for other usage of this workaround.
408 #define MBUF_LOAD(v) do { \
410 CROAK(("Not a scalar string")); \
411 mptr = mbase = SvPV(v, msiz); \
412 mend = mbase + msiz; \
415 #define MBUF_XTEND(x) do { \
416 int nsz = (int) round_mgrow((x)+msiz); \
417 int offset = mptr - mbase; \
418 TRACEME(("** extending mbase to %d bytes", nsz)); \
419 Renew(mbase, nsz, char); \
421 mptr = mbase + offset; \
422 mend = mbase + nsz; \
425 #define MBUF_CHK(x) do { \
426 if ((mptr + (x)) > mend) \
430 #define MBUF_GETC(x) do { \
432 x = (int) (unsigned char) *mptr++; \
438 #define MBUF_GETINT(x) do { \
440 if ((mptr + 4) <= mend) { \
441 memcpy(oI(&x), mptr, 4); \
447 #define MBUF_GETINT(x) do { \
448 if ((mptr + sizeof(int)) <= mend) { \
449 if (int_aligned(mptr)) \
452 memcpy(&x, mptr, sizeof(int)); \
453 mptr += sizeof(int); \
459 #define MBUF_READ(x,s) do { \
460 if ((mptr + (s)) <= mend) { \
461 memcpy(x, mptr, s); \
467 #define MBUF_SAFEREAD(x,s,z) do { \
468 if ((mptr + (s)) <= mend) { \
469 memcpy(x, mptr, s); \
477 #define MBUF_PUTC(c) do { \
479 *mptr++ = (char) c; \
482 *mptr++ = (char) c; \
487 #define MBUF_PUTINT(i) do { \
489 memcpy(mptr, oI(&i), 4); \
493 #define MBUF_PUTINT(i) do { \
494 MBUF_CHK(sizeof(int)); \
495 if (int_aligned(mptr)) \
498 memcpy(mptr, &i, sizeof(int)); \
499 mptr += sizeof(int); \
503 #define MBUF_WRITE(x,s) do { \
505 memcpy(mptr, x, s); \
510 * Possible return values for sv_type().
514 #define svis_SCALAR 1
518 #define svis_TIED_ITEM 5
525 #define SHF_TYPE_MASK 0x03
526 #define SHF_LARGE_CLASSLEN 0x04
527 #define SHF_LARGE_STRLEN 0x08
528 #define SHF_LARGE_LISTLEN 0x10
529 #define SHF_IDX_CLASSNAME 0x20
530 #define SHF_NEED_RECURSE 0x40
531 #define SHF_HAS_LIST 0x80
534 * Types for SX_HOOK (2 bits).
542 * Before 0.6, the magic string was "perl-store" (binary version number 0).
544 * Since 0.6 introduced many binary incompatibilities, the magic string has
545 * been changed to "pst0" to allow an old image to be properly retrieved by
546 * a newer Storable, but ensure a newer image cannot be retrieved with an
549 * At 0.7, objects are given the ability to serialize themselves, and the
550 * set of markers is extended, backward compatibility is not jeopardized,
551 * so the binary version number could have remained unchanged. To correctly
552 * spot errors if a file making use of 0.7-specific extensions is given to
553 * 0.6 for retrieval, the binary version was moved to "2". And I'm introducing
554 * a "minor" version, to better track this kind of evolution from now on.
557 static char old_magicstr[] = "perl-store"; /* Magic number before 0.6 */
558 static char magicstr[] = "pst0"; /* Used as a magic number */
560 #define STORABLE_BIN_MAJOR 2 /* Binary major "version" */
561 #define STORABLE_BIN_MINOR 3 /* Binary minor "version" */
564 * Useful store shortcuts...
567 #define PUTMARK(x) do { \
570 else if (PerlIO_putc(cxt->fio, x) == EOF) \
574 #define WRITE_I32(x) do { \
575 ASSERT(sizeof(x) == sizeof(I32), ("writing an I32")); \
578 else if (PerlIO_write(cxt->fio, oI(&x), oS(sizeof(x))) != oS(sizeof(x))) \
583 #define WLEN(x) do { \
584 if (cxt->netorder) { \
585 int y = (int) htonl(x); \
588 else if (PerlIO_write(cxt->fio,oI(&y),oS(sizeof(y))) != oS(sizeof(y))) \
593 else if (PerlIO_write(cxt->fio,oI(&x),oS(sizeof(x))) != oS(sizeof(x))) \
598 #define WLEN(x) WRITE_I32(x)
601 #define WRITE(x,y) do { \
604 else if (PerlIO_write(cxt->fio, x, y) != y) \
608 #define STORE_PV_LEN(pv, len, small, large) do { \
609 if (len <= LG_SCALAR) { \
610 unsigned char clen = (unsigned char) len; \
622 #define STORE_SCALAR(pv, len) STORE_PV_LEN(pv, len, SX_SCALAR, SX_LSCALAR)
625 * Conditional UTF8 support.
626 * On non-UTF8 perls, UTF8 strings are returned as normal strings.
630 #define STORE_UTF8STR(pv, len) STORE_PV_LEN(pv, len, SX_UTF8STR, SX_LUTF8STR)
633 #define STORE_UTF8STR(pv, len) CROAK(("panic: storing UTF8 in non-UTF8 perl"))
634 #define SvUTF8_on(sv) CROAK(("Cannot retrieve UTF8 data in non-UTF8 perl"))
638 * Store undef in arrays and hashes without recursing through store().
640 #define STORE_UNDEF() do { \
646 * Useful retrieve shortcuts...
650 (cxt->fio ? PerlIO_getc(cxt->fio) : (mptr >= mend ? EOF : (int) *mptr++))
652 #define GETMARK(x) do { \
655 else if ((x = PerlIO_getc(cxt->fio)) == EOF) \
659 #define READ_I32(x) do { \
660 ASSERT(sizeof(x) == sizeof(I32), ("reading an I32")); \
664 else if (PerlIO_read(cxt->fio, oI(&x), oS(sizeof(x))) != oS(sizeof(x))) \
669 #define RLEN(x) do { \
673 else if (PerlIO_read(cxt->fio, oI(&x), oS(sizeof(x))) != oS(sizeof(x))) \
676 x = (int) ntohl(x); \
679 #define RLEN(x) READ_I32(x)
682 #define READ(x,y) do { \
685 else if (PerlIO_read(cxt->fio, x, y) != y) \
689 #define SAFEREAD(x,y,z) do { \
691 MBUF_SAFEREAD(x,y,z); \
692 else if (PerlIO_read(cxt->fio, x, y) != y) { \
699 * This macro is used at retrieve time, to remember where object 'y', bearing a
700 * given tag 'tagnum', has been retrieved. Next time we see an SX_OBJECT marker,
701 * we'll therefore know where it has been retrieved and will be able to
702 * share the same reference, as in the original stored memory image.
704 #define SEEN(y) do { \
707 if (av_store(cxt->aseen, cxt->tagnum++, SvREFCNT_inc(y)) == 0) \
709 TRACEME(("aseen(#%d) = 0x%"UVxf" (refcnt=%d)", cxt->tagnum-1, \
710 PTR2UV(y), SvREFCNT(y)-1)); \
714 * Bless `s' in `p', via a temporary reference, required by sv_bless().
716 #define BLESS(s,p) do { \
719 TRACEME(("blessing 0x%"UVxf" in %s", PTR2UV(s), (p))); \
720 stash = gv_stashpv((p), TRUE); \
721 ref = newRV_noinc(s); \
722 (void) sv_bless(ref, stash); \
728 static SV *retrieve();
731 * Dynamic dispatching table for SV store.
734 static int store_ref(stcxt_t *cxt, SV *sv);
735 static int store_scalar(stcxt_t *cxt, SV *sv);
736 static int store_array(stcxt_t *cxt, AV *av);
737 static int store_hash(stcxt_t *cxt, HV *hv);
738 static int store_tied(stcxt_t *cxt, SV *sv);
739 static int store_tied_item(stcxt_t *cxt, SV *sv);
740 static int store_other(stcxt_t *cxt, SV *sv);
741 static int store_blessed(stcxt_t *cxt, SV *sv, int type, HV *pkg);
743 static int (*sv_store[])() = {
744 store_ref, /* svis_REF */
745 store_scalar, /* svis_SCALAR */
746 store_array, /* svis_ARRAY */
747 store_hash, /* svis_HASH */
748 store_tied, /* svis_TIED */
749 store_tied_item, /* svis_TIED_ITEM */
750 store_other, /* svis_OTHER */
753 #define SV_STORE(x) (*sv_store[x])
756 * Dynamic dispatching tables for SV retrieval.
759 static SV *retrieve_lscalar(stcxt_t *cxt);
760 static SV *retrieve_lutf8str(stcxt_t *cxt);
761 static SV *old_retrieve_array(stcxt_t *cxt);
762 static SV *old_retrieve_hash(stcxt_t *cxt);
763 static SV *retrieve_ref(stcxt_t *cxt);
764 static SV *retrieve_undef(stcxt_t *cxt);
765 static SV *retrieve_integer(stcxt_t *cxt);
766 static SV *retrieve_double(stcxt_t *cxt);
767 static SV *retrieve_byte(stcxt_t *cxt);
768 static SV *retrieve_netint(stcxt_t *cxt);
769 static SV *retrieve_scalar(stcxt_t *cxt);
770 static SV *retrieve_utf8str(stcxt_t *cxt);
771 static SV *retrieve_tied_array(stcxt_t *cxt);
772 static SV *retrieve_tied_hash(stcxt_t *cxt);
773 static SV *retrieve_tied_scalar(stcxt_t *cxt);
774 static SV *retrieve_other(stcxt_t *cxt);
776 static SV *(*sv_old_retrieve[])() = {
777 0, /* SX_OBJECT -- entry unused dynamically */
778 retrieve_lscalar, /* SX_LSCALAR */
779 old_retrieve_array, /* SX_ARRAY -- for pre-0.6 binaries */
780 old_retrieve_hash, /* SX_HASH -- for pre-0.6 binaries */
781 retrieve_ref, /* SX_REF */
782 retrieve_undef, /* SX_UNDEF */
783 retrieve_integer, /* SX_INTEGER */
784 retrieve_double, /* SX_DOUBLE */
785 retrieve_byte, /* SX_BYTE */
786 retrieve_netint, /* SX_NETINT */
787 retrieve_scalar, /* SX_SCALAR */
788 retrieve_tied_array, /* SX_ARRAY */
789 retrieve_tied_hash, /* SX_HASH */
790 retrieve_tied_scalar, /* SX_SCALAR */
791 retrieve_other, /* SX_SV_UNDEF not supported */
792 retrieve_other, /* SX_SV_YES not supported */
793 retrieve_other, /* SX_SV_NO not supported */
794 retrieve_other, /* SX_BLESS not supported */
795 retrieve_other, /* SX_IX_BLESS not supported */
796 retrieve_other, /* SX_HOOK not supported */
797 retrieve_other, /* SX_OVERLOADED not supported */
798 retrieve_other, /* SX_TIED_KEY not supported */
799 retrieve_other, /* SX_TIED_IDX not supported */
800 retrieve_other, /* SX_UTF8STR not supported */
801 retrieve_other, /* SX_LUTF8STR not supported */
802 retrieve_other, /* SX_ERROR */
805 static SV *retrieve_array(stcxt_t *cxt);
806 static SV *retrieve_hash(stcxt_t *cxt);
807 static SV *retrieve_sv_undef(stcxt_t *cxt);
808 static SV *retrieve_sv_yes(stcxt_t *cxt);
809 static SV *retrieve_sv_no(stcxt_t *cxt);
810 static SV *retrieve_blessed(stcxt_t *cxt);
811 static SV *retrieve_idx_blessed(stcxt_t *cxt);
812 static SV *retrieve_hook(stcxt_t *cxt);
813 static SV *retrieve_overloaded(stcxt_t *cxt);
814 static SV *retrieve_tied_key(stcxt_t *cxt);
815 static SV *retrieve_tied_idx(stcxt_t *cxt);
817 static SV *(*sv_retrieve[])() = {
818 0, /* SX_OBJECT -- entry unused dynamically */
819 retrieve_lscalar, /* SX_LSCALAR */
820 retrieve_array, /* SX_ARRAY */
821 retrieve_hash, /* SX_HASH */
822 retrieve_ref, /* SX_REF */
823 retrieve_undef, /* SX_UNDEF */
824 retrieve_integer, /* SX_INTEGER */
825 retrieve_double, /* SX_DOUBLE */
826 retrieve_byte, /* SX_BYTE */
827 retrieve_netint, /* SX_NETINT */
828 retrieve_scalar, /* SX_SCALAR */
829 retrieve_tied_array, /* SX_ARRAY */
830 retrieve_tied_hash, /* SX_HASH */
831 retrieve_tied_scalar, /* SX_SCALAR */
832 retrieve_sv_undef, /* SX_SV_UNDEF */
833 retrieve_sv_yes, /* SX_SV_YES */
834 retrieve_sv_no, /* SX_SV_NO */
835 retrieve_blessed, /* SX_BLESS */
836 retrieve_idx_blessed, /* SX_IX_BLESS */
837 retrieve_hook, /* SX_HOOK */
838 retrieve_overloaded, /* SX_OVERLOAD */
839 retrieve_tied_key, /* SX_TIED_KEY */
840 retrieve_tied_idx, /* SX_TIED_IDX */
841 retrieve_utf8str, /* SX_UTF8STR */
842 retrieve_lutf8str, /* SX_LUTF8STR */
843 retrieve_other, /* SX_ERROR */
846 #define RETRIEVE(c,x) (*(c)->retrieve_vtbl[(x) >= SX_ERROR ? SX_ERROR : (x)])
848 static SV *mbuf2sv(void);
851 *** Context management.
857 * Called once per "thread" (interpreter) to initialize some global context.
859 static void init_perinterp(void)
863 cxt->netorder = 0; /* true if network order used */
864 cxt->forgive_me = -1; /* whether to be forgiving... */
870 * Initialize a new store context for real recursion.
872 static void init_store_context(
878 TRACEME(("init_store_context"));
880 cxt->netorder = network_order;
881 cxt->forgive_me = -1; /* Fetched from perl if needed */
882 cxt->canonical = -1; /* Idem */
883 cxt->tagnum = -1; /* Reset tag numbers */
884 cxt->classnum = -1; /* Reset class numbers */
885 cxt->fio = f; /* Where I/O are performed */
886 cxt->optype = optype; /* A store, or a deep clone */
887 cxt->entry = 1; /* No recursion yet */
890 * The `hseen' table is used to keep track of each SV stored and their
891 * associated tag numbers is special. It is "abused" because the
892 * values stored are not real SV, just integers cast to (SV *),
893 * which explains the freeing below.
895 * It is also one possible bottlneck to achieve good storing speed,
896 * so the "shared keys" optimization is turned off (unlikely to be
897 * of any use here), and the hash table is "pre-extended". Together,
898 * those optimizations increase the throughput by 12%.
901 cxt->hseen = newHV(); /* Table where seen objects are stored */
902 HvSHAREKEYS_off(cxt->hseen);
905 * The following does not work well with perl5.004_04, and causes
906 * a core dump later on, in a completely unrelated spot, which
907 * makes me think there is a memory corruption going on.
909 * Calling hv_ksplit(hseen, HBUCKETS) instead of manually hacking
910 * it below does not make any difference. It seems to work fine
911 * with perl5.004_68 but given the probable nature of the bug,
912 * that does not prove anything.
914 * It's a shame because increasing the amount of buckets raises
915 * store() throughput by 5%, but until I figure this out, I can't
916 * allow for this to go into production.
918 * It is reported fixed in 5.005, hence the #if.
920 #if PERL_VERSION >= 5
921 #define HBUCKETS 4096 /* Buckets for %hseen */
922 HvMAX(cxt->hseen) = HBUCKETS - 1; /* keys %hseen = $HBUCKETS; */
926 * The `hclass' hash uses the same settings as `hseen' above, but it is
927 * used to assign sequential tags (numbers) to class names for blessed
930 * We turn the shared key optimization on.
933 cxt->hclass = newHV(); /* Where seen classnames are stored */
935 #if PERL_VERSION >= 5
936 HvMAX(cxt->hclass) = HBUCKETS - 1; /* keys %hclass = $HBUCKETS; */
940 * The `hook' hash table is used to keep track of the references on
941 * the STORABLE_freeze hook routines, when found in some class name.
943 * It is assumed that the inheritance tree will not be changed during
944 * storing, and that no new method will be dynamically created by the
948 cxt->hook = newHV(); /* Table where hooks are cached */
952 * clean_store_context
954 * Clean store context by
956 static void clean_store_context(stcxt_t *cxt)
960 TRACEME(("clean_store_context"));
962 ASSERT(cxt->optype & ST_STORE, ("was performing a store()"));
965 * Insert real values into hashes where we stored faked pointers.
968 hv_iterinit(cxt->hseen);
969 while (he = hv_iternext(cxt->hseen))
970 HeVAL(he) = &PL_sv_undef;
972 hv_iterinit(cxt->hclass);
973 while (he = hv_iternext(cxt->hclass))
974 HeVAL(he) = &PL_sv_undef;
977 * And now dispose of them...
980 hv_undef(cxt->hseen);
981 sv_free((SV *) cxt->hseen);
983 hv_undef(cxt->hclass);
984 sv_free((SV *) cxt->hclass);
987 sv_free((SV *) cxt->hook);
994 * init_retrieve_context
996 * Initialize a new retrieve context for real recursion.
998 static void init_retrieve_context(stcxt_t *cxt, int optype, int is_tainted)
1000 TRACEME(("init_retrieve_context"));
1003 * The hook hash table is used to keep track of the references on
1004 * the STORABLE_thaw hook routines, when found in some class name.
1006 * It is assumed that the inheritance tree will not be changed during
1007 * storing, and that no new method will be dynamically created by the
1011 cxt->hook = newHV(); /* Caches STORABLE_thaw */
1014 * If retrieving an old binary version, the cxt->retrieve_vtbl variable
1015 * was set to sv_old_retrieve. We'll need a hash table to keep track of
1016 * the correspondance between the tags and the tag number used by the
1017 * new retrieve routines.
1020 cxt->hseen = (cxt->retrieve_vtbl == sv_old_retrieve) ? newHV() : 0;
1022 cxt->aseen = newAV(); /* Where retrieved objects are kept */
1023 cxt->aclass = newAV(); /* Where seen classnames are kept */
1024 cxt->tagnum = 0; /* Have to count objects... */
1025 cxt->classnum = 0; /* ...and class names as well */
1026 cxt->optype = optype;
1027 cxt->s_tainted = is_tainted;
1028 cxt->entry = 1; /* No recursion yet */
1032 * clean_retrieve_context
1034 * Clean retrieve context by
1036 static void clean_retrieve_context(stcxt_t *cxt)
1038 TRACEME(("clean_retrieve_context"));
1040 ASSERT(cxt->optype & ST_RETRIEVE, ("was performing a retrieve()"));
1042 av_undef(cxt->aseen);
1043 sv_free((SV *) cxt->aseen);
1045 av_undef(cxt->aclass);
1046 sv_free((SV *) cxt->aclass);
1048 hv_undef(cxt->hook);
1049 sv_free((SV *) cxt->hook);
1052 sv_free((SV *) cxt->hseen); /* optional HV, for backward compat. */
1061 * A workaround for the CROAK bug: cleanup the last context.
1063 static void clean_context(cxt)
1066 TRACEME(("clean_context"));
1068 ASSERT(cxt->s_dirty, ("dirty context"));
1070 if (cxt->optype & ST_RETRIEVE)
1071 clean_retrieve_context(cxt);
1073 clean_store_context(cxt);
1079 * Allocate a new context and push it on top of the parent one.
1080 * This new context is made globally visible via SET_STCXT().
1082 static stcxt_t *allocate_context(parent_cxt)
1083 stcxt_t *parent_cxt;
1087 TRACEME(("allocate_context"));
1089 ASSERT(!parent_cxt->s_dirty, ("parent context clean"));
1091 Newz(0, cxt, 1, stcxt_t);
1092 cxt->prev = parent_cxt;
1101 * Free current context, which cannot be the "root" one.
1102 * Make the context underneath globally visible via SET_STCXT().
1104 static void free_context(cxt)
1107 stcxt_t *prev = cxt->prev;
1109 TRACEME(("free_context"));
1111 ASSERT(!cxt->s_dirty, ("clean context"));
1112 ASSERT(prev, ("not freeing root context"));
1130 * Tells whether we're in the middle of a store operation.
1132 int is_storing(void)
1136 return cxt->entry && (cxt->optype & ST_STORE);
1142 * Tells whether we're in the middle of a retrieve operation.
1144 int is_retrieving(void)
1148 return cxt->entry && (cxt->optype & ST_RETRIEVE);
1152 * last_op_in_netorder
1154 * Returns whether last operation was made using network order.
1156 * This is typically out-of-band information that might prove useful
1157 * to people wishing to convert native to network order data when used.
1159 int last_op_in_netorder(void)
1163 return cxt->netorder;
1167 *** Hook lookup and calling routines.
1173 * A wrapper on gv_fetchmethod_autoload() which caches results.
1175 * Returns the routine reference as an SV*, or null if neither the package
1176 * nor its ancestors know about the method.
1178 static SV *pkg_fetchmeth(
1188 * The following code is the same as the one performed by UNIVERSAL::can
1192 gv = gv_fetchmethod_autoload(pkg, method, FALSE);
1193 if (gv && isGV(gv)) {
1194 sv = newRV((SV*) GvCV(gv));
1195 TRACEME(("%s->%s: 0x%"UVxf, HvNAME(pkg), method, PTR2UV(sv)));
1197 sv = newSVsv(&PL_sv_undef);
1198 TRACEME(("%s->%s: not found", HvNAME(pkg), method));
1202 * Cache the result, ignoring failure: if we can't store the value,
1203 * it just won't be cached.
1206 (void) hv_store(cache, HvNAME(pkg), strlen(HvNAME(pkg)), sv, 0);
1208 return SvOK(sv) ? sv : (SV *) 0;
1214 * Force cached value to be undef: hook ignored even if present.
1216 static void pkg_hide(
1221 (void) hv_store(cache,
1222 HvNAME(pkg), strlen(HvNAME(pkg)), newSVsv(&PL_sv_undef), 0);
1228 * Our own "UNIVERSAL::can", which caches results.
1230 * Returns the routine reference as an SV*, or null if the object does not
1231 * know about the method.
1241 TRACEME(("pkg_can for %s->%s", HvNAME(pkg), method));
1244 * Look into the cache to see whether we already have determined
1245 * where the routine was, if any.
1247 * NOTA BENE: we don't use `method' at all in our lookup, since we know
1248 * that only one hook (i.e. always the same) is cached in a given cache.
1251 svh = hv_fetch(cache, HvNAME(pkg), strlen(HvNAME(pkg)), FALSE);
1255 TRACEME(("cached %s->%s: not found", HvNAME(pkg), method));
1258 TRACEME(("cached %s->%s: 0x%"UVxf,
1259 HvNAME(pkg), method, PTR2UV(sv)));
1264 TRACEME(("not cached yet"));
1265 return pkg_fetchmeth(cache, pkg, method); /* Fetch and cache */
1271 * Call routine as obj->hook(av) in scalar context.
1272 * Propagates the single returned value if not called in void context.
1274 static SV *scalar_call(
1285 TRACEME(("scalar_call (cloning=%d)", cloning));
1292 XPUSHs(sv_2mortal(newSViv(cloning))); /* Cloning flag */
1294 SV **ary = AvARRAY(av);
1295 int cnt = AvFILLp(av) + 1;
1297 XPUSHs(ary[0]); /* Frozen string */
1298 for (i = 1; i < cnt; i++) {
1299 TRACEME(("pushing arg #%d (0x%"UVxf")...",
1300 i, PTR2UV(ary[i])));
1301 XPUSHs(sv_2mortal(newRV(ary[i])));
1306 TRACEME(("calling..."));
1307 count = perl_call_sv(hook, flags); /* Go back to Perl code */
1308 TRACEME(("count = %d", count));
1314 SvREFCNT_inc(sv); /* We're returning it, must stay alive! */
1327 * Call routine obj->hook(cloning) in list context.
1328 * Returns the list of returned values in an array.
1330 static AV *array_call(
1340 TRACEME(("array_call (cloning=%d)", cloning));
1346 XPUSHs(obj); /* Target object */
1347 XPUSHs(sv_2mortal(newSViv(cloning))); /* Cloning flag */
1350 count = perl_call_sv(hook, G_ARRAY); /* Go back to Perl code */
1355 for (i = count - 1; i >= 0; i--) {
1357 av_store(av, i, SvREFCNT_inc(sv));
1370 * Lookup the class name in the `hclass' table and either assign it a new ID
1371 * or return the existing one, by filling in `classnum'.
1373 * Return true if the class was known, false if the ID was just generated.
1375 static int known_class(
1377 char *name, /* Class name */
1378 int len, /* Name length */
1382 HV *hclass = cxt->hclass;
1384 TRACEME(("known_class (%s)", name));
1387 * Recall that we don't store pointers in this hash table, but tags.
1388 * Therefore, we need LOW_32BITS() to extract the relevant parts.
1391 svh = hv_fetch(hclass, name, len, FALSE);
1393 *classnum = LOW_32BITS(*svh);
1398 * Unknown classname, we need to record it.
1402 if (!hv_store(hclass, name, len, INT2PTR(SV*, cxt->classnum), 0))
1403 CROAK(("Unable to record new classname"));
1405 *classnum = cxt->classnum;
1410 *** Sepcific store routines.
1416 * Store a reference.
1417 * Layout is SX_REF <object> or SX_OVERLOAD <object>.
1419 static int store_ref(stcxt_t *cxt, SV *sv)
1421 TRACEME(("store_ref (0x%"UVxf")", PTR2UV(sv)));
1424 * Follow reference, and check if target is overloaded.
1430 HV *stash = (HV *) SvSTASH(sv);
1431 if (stash && Gv_AMG(stash)) {
1432 TRACEME(("ref (0x%"UVxf") is overloaded", PTR2UV(sv)));
1433 PUTMARK(SX_OVERLOAD);
1439 return store(cxt, sv);
1447 * Layout is SX_LSCALAR <length> <data>, SX_SCALAR <lenght> <data> or SX_UNDEF.
1448 * The <data> section is omitted if <length> is 0.
1450 * If integer or double, the layout is SX_INTEGER <data> or SX_DOUBLE <data>.
1451 * Small integers (within [-127, +127]) are stored as SX_BYTE <byte>.
1453 static int store_scalar(stcxt_t *cxt, SV *sv)
1458 U32 flags = SvFLAGS(sv); /* "cc -O" may put it in register */
1460 TRACEME(("store_scalar (0x%"UVxf")", PTR2UV(sv)));
1463 * For efficiency, break the SV encapsulation by peaking at the flags
1464 * directly without using the Perl macros to avoid dereferencing
1465 * sv->sv_flags each time we wish to check the flags.
1468 if (!(flags & SVf_OK)) { /* !SvOK(sv) */
1469 if (sv == &PL_sv_undef) {
1470 TRACEME(("immortal undef"));
1471 PUTMARK(SX_SV_UNDEF);
1473 TRACEME(("undef at 0x%"UVxf, PTR2UV(sv)));
1480 * Always store the string representation of a scalar if it exists.
1481 * Gisle Aas provided me with this test case, better than a long speach:
1483 * perl -MDevel::Peek -le '$a="abc"; $a+0; Dump($a)'
1484 * SV = PVNV(0x80c8520)
1486 * FLAGS = (NOK,POK,pNOK,pPOK)
1489 * PV = 0x80c83d0 "abc"\0
1493 * Write SX_SCALAR, length, followed by the actual data.
1495 * Otherwise, write an SX_BYTE, SX_INTEGER or an SX_DOUBLE as
1496 * appropriate, followed by the actual (binary) data. A double
1497 * is written as a string if network order, for portability.
1499 * NOTE: instead of using SvNOK(sv), we test for SvNOKp(sv).
1500 * The reason is that when the scalar value is tainted, the SvNOK(sv)
1503 * The test for a read-only scalar with both POK and NOK set is meant
1504 * to quickly detect &PL_sv_yes and &PL_sv_no without having to pay the
1505 * address comparison for each scalar we store.
1508 #define SV_MAYBE_IMMORTAL (SVf_READONLY|SVf_POK|SVf_NOK)
1510 if ((flags & SV_MAYBE_IMMORTAL) == SV_MAYBE_IMMORTAL) {
1511 if (sv == &PL_sv_yes) {
1512 TRACEME(("immortal yes"));
1514 } else if (sv == &PL_sv_no) {
1515 TRACEME(("immortal no"));
1518 pv = SvPV(sv, len); /* We know it's SvPOK */
1519 goto string; /* Share code below */
1521 } else if (flags & SVp_POK) { /* SvPOKp(sv) => string */
1522 I32 wlen; /* For 64-bit machines */
1526 * Will come here from below with pv and len set if double & netorder,
1527 * or from above if it was readonly, POK and NOK but neither &PL_sv_yes
1532 wlen = (I32) len; /* WLEN via STORE_SCALAR expects I32 */
1534 STORE_UTF8STR(pv, wlen);
1536 STORE_SCALAR(pv, wlen);
1537 TRACEME(("ok (scalar 0x%"UVxf" '%s', length = %"IVdf")",
1538 PTR2UV(sv), SvPVX(sv), (IV)len));
1540 } else if (flags & SVp_NOK) { /* SvNOKp(sv) => double */
1544 * Watch for number being an integer in disguise.
1546 if (nv == (NV) (iv = I_V(nv))) {
1547 TRACEME(("double %"NVff" is actually integer %"IVdf, nv, iv));
1548 goto integer; /* Share code below */
1551 if (cxt->netorder) {
1552 TRACEME(("double %"NVff" stored as string", nv));
1554 goto string; /* Share code above */
1558 WRITE(&nv, sizeof(nv));
1560 TRACEME(("ok (double 0x%"UVxf", value = %"NVff")", PTR2UV(sv), nv));
1562 } else if (flags & SVp_IOK) { /* SvIOKp(sv) => integer */
1566 * Will come here from above with iv set if double is an integer.
1571 * Optimize small integers into a single byte, otherwise store as
1572 * a real integer (converted into network order if they asked).
1575 if (iv >= -128 && iv <= 127) {
1576 unsigned char siv = (unsigned char) (iv + 128); /* [0,255] */
1579 TRACEME(("small integer stored as %d", siv));
1580 } else if (cxt->netorder) {
1583 niv = (I32) htonl(iv);
1584 TRACEME(("using network order"));
1587 TRACEME(("as-is for network order"));
1592 PUTMARK(SX_INTEGER);
1593 WRITE(&iv, sizeof(iv));
1596 TRACEME(("ok (integer 0x%"UVxf", value = %"IVdf")", PTR2UV(sv), iv));
1599 CROAK(("Can't determine type of %s(0x%"UVxf")",
1600 sv_reftype(sv, FALSE),
1603 return 0; /* Ok, no recursion on scalars */
1611 * Layout is SX_ARRAY <size> followed by each item, in increading index order.
1612 * Each item is stored as <object>.
1614 static int store_array(stcxt_t *cxt, AV *av)
1617 I32 len = av_len(av) + 1;
1621 TRACEME(("store_array (0x%"UVxf")", PTR2UV(av)));
1624 * Signal array by emitting SX_ARRAY, followed by the array length.
1629 TRACEME(("size = %d", len));
1632 * Now store each item recursively.
1635 for (i = 0; i < len; i++) {
1636 sav = av_fetch(av, i, 0);
1638 TRACEME(("(#%d) undef item", i));
1642 TRACEME(("(#%d) item", i));
1643 if (ret = store(cxt, *sav))
1647 TRACEME(("ok (array)"));
1656 * Borrowed from perl source file pp_ctl.c, where it is used by pp_sort.
1659 sortcmp(const void *a, const void *b)
1661 return sv_cmp(*(SV * const *) a, *(SV * const *) b);
1668 * Store an hash table.
1670 * Layout is SX_HASH <size> followed by each key/value pair, in random order.
1671 * Values are stored as <object>.
1672 * Keys are stored as <length> <data>, the <data> section being omitted
1675 static int store_hash(stcxt_t *cxt, HV *hv)
1677 I32 len = HvKEYS(hv);
1683 TRACEME(("store_hash (0x%"UVxf")", PTR2UV(hv)));
1686 * Signal hash by emitting SX_HASH, followed by the table length.
1691 TRACEME(("size = %d", len));
1694 * Save possible iteration state via each() on that table.
1697 riter = HvRITER(hv);
1698 eiter = HvEITER(hv);
1702 * Now store each item recursively.
1704 * If canonical is defined to some true value then store each
1705 * key/value pair in sorted order otherwise the order is random.
1706 * Canonical order is irrelevant when a deep clone operation is performed.
1708 * Fetch the value from perl only once per store() operation, and only
1713 !(cxt->optype & ST_CLONE) && (cxt->canonical == 1 ||
1714 (cxt->canonical < 0 && (cxt->canonical =
1715 SvTRUE(perl_get_sv("Storable::canonical", TRUE)) ? 1 : 0)))
1718 * Storing in order, sorted by key.
1719 * Run through the hash, building up an array of keys in a
1720 * mortal array, sort the array and then run through the
1726 TRACEME(("using canonical order"));
1728 for (i = 0; i < len; i++) {
1729 HE *he = hv_iternext(hv);
1730 SV *key = hv_iterkeysv(he);
1731 av_store(av, AvFILLp(av)+1, key); /* av_push(), really */
1734 qsort((char *) AvARRAY(av), len, sizeof(SV *), sortcmp);
1736 for (i = 0; i < len; i++) {
1739 SV *key = av_shift(av);
1740 HE *he = hv_fetch_ent(hv, key, 0, 0);
1741 SV *val = HeVAL(he);
1743 return 1; /* Internal error, not I/O error */
1746 * Store value first.
1749 TRACEME(("(#%d) value 0x%"UVxf, i, PTR2UV(val)));
1751 if (ret = store(cxt, val))
1756 * Keys are written after values to make sure retrieval
1757 * can be optimal in terms of memory usage, where keys are
1758 * read into a fixed unique buffer called kbuf.
1759 * See retrieve_hash() for details.
1762 keyval = hv_iterkey(he, &keylen);
1763 TRACEME(("(#%d) key '%s'", i, keyval));
1766 WRITE(keyval, keylen);
1770 * Free up the temporary array
1779 * Storing in "random" order (in the order the keys are stored
1780 * within the the hash). This is the default and will be faster!
1783 for (i = 0; i < len; i++) {
1786 SV *val = hv_iternextsv(hv, &key, &len);
1789 return 1; /* Internal error, not I/O error */
1792 * Store value first.
1795 TRACEME(("(#%d) value 0x%"UVxf, i, PTR2UV(val)));
1797 if (ret = store(cxt, val))
1802 * Keys are written after values to make sure retrieval
1803 * can be optimal in terms of memory usage, where keys are
1804 * read into a fixed unique buffer called kbuf.
1805 * See retrieve_hash() for details.
1808 TRACEME(("(#%d) key '%s'", i, key));
1815 TRACEME(("ok (hash 0x%"UVxf")", PTR2UV(hv)));
1818 HvRITER(hv) = riter; /* Restore hash iterator state */
1819 HvEITER(hv) = eiter;
1827 * When storing a tied object (be it a tied scalar, array or hash), we lay out
1828 * a special mark, followed by the underlying tied object. For instance, when
1829 * dealing with a tied hash, we store SX_TIED_HASH <hash object>, where
1830 * <hash object> stands for the serialization of the tied hash.
1832 static int store_tied(stcxt_t *cxt, SV *sv)
1836 int svt = SvTYPE(sv);
1839 TRACEME(("store_tied (0x%"UVxf")", PTR2UV(sv)));
1842 * We have a small run-time penalty here because we chose to factorise
1843 * all tieds objects into the same routine, and not have a store_tied_hash,
1844 * a store_tied_array, etc...
1846 * Don't use a switch() statement, as most compilers don't optimize that
1847 * well for 2/3 values. An if() else if() cascade is just fine. We put
1848 * tied hashes first, as they are the most likely beasts.
1851 if (svt == SVt_PVHV) {
1852 TRACEME(("tied hash"));
1853 PUTMARK(SX_TIED_HASH); /* Introduces tied hash */
1854 } else if (svt == SVt_PVAV) {
1855 TRACEME(("tied array"));
1856 PUTMARK(SX_TIED_ARRAY); /* Introduces tied array */
1858 TRACEME(("tied scalar"));
1859 PUTMARK(SX_TIED_SCALAR); /* Introduces tied scalar */
1863 if (!(mg = mg_find(sv, mtype)))
1864 CROAK(("No magic '%c' found while storing tied %s", mtype,
1865 (svt == SVt_PVHV) ? "hash" :
1866 (svt == SVt_PVAV) ? "array" : "scalar"));
1869 * The mg->mg_obj found by mg_find() above actually points to the
1870 * underlying tied Perl object implementation. For instance, if the
1871 * original SV was that of a tied array, then mg->mg_obj is an AV.
1873 * Note that we store the Perl object as-is. We don't call its FETCH
1874 * method along the way. At retrieval time, we won't call its STORE
1875 * method either, but the tieing magic will be re-installed. In itself,
1876 * that ensures that the tieing semantics are preserved since futher
1877 * accesses on the retrieved object will indeed call the magic methods...
1880 if (ret = store(cxt, mg->mg_obj))
1883 TRACEME(("ok (tied)"));
1891 * Stores a reference to an item within a tied structure:
1893 * . \$h{key}, stores both the (tied %h) object and 'key'.
1894 * . \$a[idx], stores both the (tied @a) object and 'idx'.
1896 * Layout is therefore either:
1897 * SX_TIED_KEY <object> <key>
1898 * SX_TIED_IDX <object> <index>
1900 static int store_tied_item(stcxt_t *cxt, SV *sv)
1905 TRACEME(("store_tied_item (0x%"UVxf")", PTR2UV(sv)));
1907 if (!(mg = mg_find(sv, 'p')))
1908 CROAK(("No magic 'p' found while storing reference to tied item"));
1911 * We discriminate between \$h{key} and \$a[idx] via mg_ptr.
1915 TRACEME(("store_tied_item: storing a ref to a tied hash item"));
1916 PUTMARK(SX_TIED_KEY);
1917 TRACEME(("store_tied_item: storing OBJ 0x%"UVxf, PTR2UV(mg->mg_obj)));
1919 if (ret = store(cxt, mg->mg_obj))
1922 TRACEME(("store_tied_item: storing PTR 0x%"UVxf, PTR2UV(mg->mg_ptr)));
1924 if (ret = store(cxt, (SV *) mg->mg_ptr))
1927 I32 idx = mg->mg_len;
1929 TRACEME(("store_tied_item: storing a ref to a tied array item "));
1930 PUTMARK(SX_TIED_IDX);
1931 TRACEME(("store_tied_item: storing OBJ 0x%"UVxf, PTR2UV(mg->mg_obj)));
1933 if (ret = store(cxt, mg->mg_obj))
1936 TRACEME(("store_tied_item: storing IDX %d", idx));
1941 TRACEME(("ok (tied item)"));
1947 * store_hook -- dispatched manually, not via sv_store[]
1949 * The blessed SV is serialized by a hook.
1953 * SX_HOOK <flags> <len> <classname> <len2> <str> [<len3> <object-IDs>]
1955 * where <flags> indicates how long <len>, <len2> and <len3> are, whether
1956 * the trailing part [] is present, the type of object (scalar, array or hash).
1957 * There is also a bit which says how the classname is stored between:
1962 * and when the <index> form is used (classname already seen), the "large
1963 * classname" bit in <flags> indicates how large the <index> is.
1965 * The serialized string returned by the hook is of length <len2> and comes
1966 * next. It is an opaque string for us.
1968 * Those <len3> object IDs which are listed last represent the extra references
1969 * not directly serialized by the hook, but which are linked to the object.
1971 * When recursion is mandated to resolve object-IDs not yet seen, we have
1972 * instead, with <header> being flags with bits set to indicate the object type
1973 * and that recursion was indeed needed:
1975 * SX_HOOK <header> <object> <header> <object> <flags>
1977 * that same header being repeated between serialized objects obtained through
1978 * recursion, until we reach flags indicating no recursion, at which point
1979 * we know we've resynchronized with a single layout, after <flags>.
1981 static int store_hook(
1994 int count; /* really len3 + 1 */
1995 unsigned char flags;
1998 int recursed = 0; /* counts recursion */
1999 int obj_type; /* object type, on 2 bits */
2002 int clone = cxt->optype & ST_CLONE;
2004 TRACEME(("store_hook, class \"%s\", tagged #%d", HvNAME(pkg), cxt->tagnum));
2007 * Determine object type on 2 bits.
2012 obj_type = SHT_SCALAR;
2015 obj_type = SHT_ARRAY;
2018 obj_type = SHT_HASH;
2021 CROAK(("Unexpected object type (%d) in store_hook()", type));
2023 flags = SHF_NEED_RECURSE | obj_type;
2025 class = HvNAME(pkg);
2026 len = strlen(class);
2029 * To call the hook, we need to fake a call like:
2031 * $object->STORABLE_freeze($cloning);
2033 * but we don't have the $object here. For instance, if $object is
2034 * a blessed array, what we have in `sv' is the array, and we can't
2035 * call a method on those.
2037 * Therefore, we need to create a temporary reference to the object and
2038 * make the call on that reference.
2041 TRACEME(("about to call STORABLE_freeze on class %s", class));
2043 ref = newRV_noinc(sv); /* Temporary reference */
2044 av = array_call(ref, hook, clone); /* @a = $object->STORABLE_freeze($c) */
2046 SvREFCNT_dec(ref); /* Reclaim temporary reference */
2048 count = AvFILLp(av) + 1;
2049 TRACEME(("store_hook, array holds %d items", count));
2052 * If they return an empty list, it means they wish to ignore the
2053 * hook for this class (and not just this instance -- that's for them
2054 * to handle if they so wish).
2056 * Simply disable the cached entry for the hook (it won't be recomputed
2057 * since it's present in the cache) and recurse to store_blessed().
2062 * They must not change their mind in the middle of a serialization.
2065 if (hv_fetch(cxt->hclass, class, len, FALSE))
2066 CROAK(("Too late to ignore hooks for %s class \"%s\"",
2067 (cxt->optype & ST_CLONE) ? "cloning" : "storing", class));
2069 pkg_hide(cxt->hook, pkg, "STORABLE_freeze");
2071 ASSERT(!pkg_can(cxt->hook, pkg, "STORABLE_freeze"), ("hook invisible"));
2072 TRACEME(("ignoring STORABLE_freeze in class \"%s\"", class));
2074 return store_blessed(cxt, sv, type, pkg);
2078 * Get frozen string.
2082 pv = SvPV(ary[0], len2);
2085 * If they returned more than one item, we need to serialize some
2086 * extra references if not already done.
2088 * Loop over the array, starting at postion #1, and for each item,
2089 * ensure it is a reference, serialize it if not already done, and
2090 * replace the entry with the tag ID of the corresponding serialized
2093 * We CHEAT by not calling av_fetch() and read directly within the
2097 for (i = 1; i < count; i++) {
2102 CROAK(("Item #%d from hook in %s is not a reference", i, class));
2103 xsv = SvRV(xsv); /* Follow ref to know what to look for */
2106 * Look in hseen and see if we have a tag already.
2107 * Serialize entry if not done already, and get its tag.
2110 if (svh = hv_fetch(cxt->hseen, (char *) &xsv, sizeof(xsv), FALSE))
2111 goto sv_seen; /* Avoid moving code too far to the right */
2113 TRACEME(("listed object %d at 0x%"UVxf" is unknown", i-1, PTR2UV(xsv)));
2116 * We need to recurse to store that object and get it to be known
2117 * so that we can resolve the list of object-IDs at retrieve time.
2119 * The first time we do this, we need to emit the proper header
2120 * indicating that we recursed, and what the type of object is (the
2121 * object we're storing via a user-hook). Indeed, during retrieval,
2122 * we'll have to create the object before recursing to retrieve the
2123 * others, in case those would point back at that object.
2126 /* [SX_HOOK] <flags> <object>*/
2131 if (ret = store(cxt, xsv)) /* Given by hook for us to store */
2134 svh = hv_fetch(cxt->hseen, (char *) &xsv, sizeof(xsv), FALSE);
2136 CROAK(("Could not serialize item #%d from hook in %s", i, class));
2139 * Replace entry with its tag (not a real SV, so no refcnt increment)
2145 TRACEME(("listed object %d at 0x%"UVxf" is tag #%"UVuf,
2146 i-1, PTR2UV(xsv), PTR2UV(*svh)));
2150 * Allocate a class ID if not already done.
2152 * This needs to be done after the recursion above, since at retrieval
2153 * time, we'll see the inner objects first. Many thanks to
2154 * Salvador Ortiz Garcia <sog@msg.com.mx> who spot that bug and
2155 * proposed the right fix. -- RAM, 15/09/2000
2158 if (!known_class(cxt, class, len, &classnum)) {
2159 TRACEME(("first time we see class %s, ID = %d", class, classnum));
2160 classnum = -1; /* Mark: we must store classname */
2162 TRACEME(("already seen class %s, ID = %d", class, classnum));
2166 * Compute leading flags.
2170 if (((classnum == -1) ? len : classnum) > LG_SCALAR)
2171 flags |= SHF_LARGE_CLASSLEN;
2173 flags |= SHF_IDX_CLASSNAME;
2174 if (len2 > LG_SCALAR)
2175 flags |= SHF_LARGE_STRLEN;
2177 flags |= SHF_HAS_LIST;
2178 if (count > (LG_SCALAR + 1))
2179 flags |= SHF_LARGE_LISTLEN;
2182 * We're ready to emit either serialized form:
2184 * SX_HOOK <flags> <len> <classname> <len2> <str> [<len3> <object-IDs>]
2185 * SX_HOOK <flags> <index> <len2> <str> [<len3> <object-IDs>]
2187 * If we recursed, the SX_HOOK has already been emitted.
2190 TRACEME(("SX_HOOK (recursed=%d) flags=0x%x "
2191 "class=%"IVdf" len=%"IVdf" len2=%"IVdf" len3=%d",
2192 recursed, flags, (IV)classnum, (IV)len, (IV)len2, count-1));
2194 /* SX_HOOK <flags> */
2199 /* <len> <classname> or <index> */
2200 if (flags & SHF_IDX_CLASSNAME) {
2201 if (flags & SHF_LARGE_CLASSLEN)
2204 unsigned char cnum = (unsigned char) classnum;
2208 if (flags & SHF_LARGE_CLASSLEN)
2211 unsigned char clen = (unsigned char) len;
2214 WRITE(class, len); /* Final \0 is omitted */
2217 /* <len2> <frozen-str> */
2218 if (flags & SHF_LARGE_STRLEN) {
2219 I32 wlen2 = len2; /* STRLEN might be 8 bytes */
2220 WLEN(wlen2); /* Must write an I32 for 64-bit machines */
2222 unsigned char clen = (unsigned char) len2;
2226 WRITE(pv, len2); /* Final \0 is omitted */
2228 /* [<len3> <object-IDs>] */
2229 if (flags & SHF_HAS_LIST) {
2230 int len3 = count - 1;
2231 if (flags & SHF_LARGE_LISTLEN)
2234 unsigned char clen = (unsigned char) len3;
2239 * NOTA BENE, for 64-bit machines: the ary[i] below does not yield a
2240 * real pointer, rather a tag number, well under the 32-bit limit.
2243 for (i = 1; i < count; i++) {
2244 I32 tagval = htonl(LOW_32BITS(ary[i]));
2246 TRACEME(("object %d, tag #%d", i-1, ntohl(tagval)));
2251 * Free the array. We need extra care for indices after 0, since they
2252 * don't hold real SVs but integers cast.
2256 AvFILLp(av) = 0; /* Cheat, nothing after 0 interests us */
2264 * store_blessed -- dispatched manually, not via sv_store[]
2266 * Check whether there is a STORABLE_xxx hook defined in the class or in one
2267 * of its ancestors. If there is, then redispatch to store_hook();
2269 * Otherwise, the blessed SV is stored using the following layout:
2271 * SX_BLESS <flag> <len> <classname> <object>
2273 * where <flag> indicates whether <len> is stored on 0 or 4 bytes, depending
2274 * on the high-order bit in flag: if 1, then length follows on 4 bytes.
2275 * Otherwise, the low order bits give the length, thereby giving a compact
2276 * representation for class names less than 127 chars long.
2278 * Each <classname> seen is remembered and indexed, so that the next time
2279 * an object in the blessed in the same <classname> is stored, the following
2282 * SX_IX_BLESS <flag> <index> <object>
2284 * where <index> is the classname index, stored on 0 or 4 bytes depending
2285 * on the high-order bit in flag (same encoding as above for <len>).
2287 static int store_blessed(
2298 TRACEME(("store_blessed, type %d, class \"%s\"", type, HvNAME(pkg)));
2301 * Look for a hook for this blessed SV and redirect to store_hook()
2305 hook = pkg_can(cxt->hook, pkg, "STORABLE_freeze");
2307 return store_hook(cxt, sv, type, pkg, hook);
2310 * This is a blessed SV without any serialization hook.
2313 class = HvNAME(pkg);
2314 len = strlen(class);
2316 TRACEME(("blessed 0x%"UVxf" in %s, no hook: tagged #%d",
2317 PTR2UV(sv), class, cxt->tagnum));
2320 * Determine whether it is the first time we see that class name (in which
2321 * case it will be stored in the SX_BLESS form), or whether we already
2322 * saw that class name before (in which case the SX_IX_BLESS form will be
2326 if (known_class(cxt, class, len, &classnum)) {
2327 TRACEME(("already seen class %s, ID = %d", class, classnum));
2328 PUTMARK(SX_IX_BLESS);
2329 if (classnum <= LG_BLESS) {
2330 unsigned char cnum = (unsigned char) classnum;
2333 unsigned char flag = (unsigned char) 0x80;
2338 TRACEME(("first time we see class %s, ID = %d", class, classnum));
2340 if (len <= LG_BLESS) {
2341 unsigned char clen = (unsigned char) len;
2344 unsigned char flag = (unsigned char) 0x80;
2346 WLEN(len); /* Don't BER-encode, this should be rare */
2348 WRITE(class, len); /* Final \0 is omitted */
2352 * Now emit the <object> part.
2355 return SV_STORE(type)(cxt, sv);
2361 * We don't know how to store the item we reached, so return an error condition.
2362 * (it's probably a GLOB, some CODE reference, etc...)
2364 * If they defined the `forgive_me' variable at the Perl level to some
2365 * true value, then don't croak, just warn, and store a placeholder string
2368 static int store_other(stcxt_t *cxt, SV *sv)
2371 static char buf[80];
2373 TRACEME(("store_other"));
2376 * Fetch the value from perl only once per store() operation.
2380 cxt->forgive_me == 0 ||
2381 (cxt->forgive_me < 0 && !(cxt->forgive_me =
2382 SvTRUE(perl_get_sv("Storable::forgive_me", TRUE)) ? 1 : 0))
2384 CROAK(("Can't store %s items", sv_reftype(sv, FALSE)));
2386 warn("Can't store item %s(0x%"UVxf")",
2387 sv_reftype(sv, FALSE), PTR2UV(sv));
2390 * Store placeholder string as a scalar instead...
2393 (void) sprintf(buf, "You lost %s(0x%"UVxf")\0", sv_reftype(sv, FALSE),
2397 STORE_SCALAR(buf, len);
2398 TRACEME(("ok (dummy \"%s\", length = %"IVdf")", buf, len));
2404 *** Store driving routines
2410 * WARNING: partially duplicates Perl's sv_reftype for speed.
2412 * Returns the type of the SV, identified by an integer. That integer
2413 * may then be used to index the dynamic routine dispatch table.
2415 static int sv_type(SV *sv)
2417 switch (SvTYPE(sv)) {
2422 * No need to check for ROK, that can't be set here since there
2423 * is no field capable of hodling the xrv_rv reference.
2431 * Starting from SVt_PV, it is possible to have the ROK flag
2432 * set, the pointer to the other SV being either stored in
2433 * the xrv_rv (in the case of a pure SVt_RV), or as the
2434 * xpv_pv field of an SVt_PV and its heirs.
2436 * However, those SV cannot be magical or they would be an
2437 * SVt_PVMG at least.
2439 return SvROK(sv) ? svis_REF : svis_SCALAR;
2441 case SVt_PVLV: /* Workaround for perl5.004_04 "LVALUE" bug */
2442 if (SvRMAGICAL(sv) && (mg_find(sv, 'p')))
2443 return svis_TIED_ITEM;
2446 if (SvRMAGICAL(sv) && (mg_find(sv, 'q')))
2448 return SvROK(sv) ? svis_REF : svis_SCALAR;
2450 if (SvRMAGICAL(sv) && (mg_find(sv, 'P')))
2454 if (SvRMAGICAL(sv) && (mg_find(sv, 'P')))
2467 * Recursively store objects pointed to by the sv to the specified file.
2469 * Layout is <content> or SX_OBJECT <tagnum> if we reach an already stored
2470 * object (one for which storage has started -- it may not be over if we have
2471 * a self-referenced structure). This data set forms a stored <object>.
2473 static int store(stcxt_t *cxt, SV *sv)
2479 HV *hseen = cxt->hseen;
2481 TRACEME(("store (0x%"UVxf")", PTR2UV(sv)));
2484 * If object has already been stored, do not duplicate data.
2485 * Simply emit the SX_OBJECT marker followed by its tag data.
2486 * The tag is always written in network order.
2488 * NOTA BENE, for 64-bit machines: the "*svh" below does not yield a
2489 * real pointer, rather a tag number (watch the insertion code below).
2490 * That means it pobably safe to assume it is well under the 32-bit limit,
2491 * and makes the truncation safe.
2492 * -- RAM, 14/09/1999
2495 svh = hv_fetch(hseen, (char *) &sv, sizeof(sv), FALSE);
2497 I32 tagval = htonl(LOW_32BITS(*svh));
2499 TRACEME(("object 0x%"UVxf" seen as #%d", PTR2UV(sv), ntohl(tagval)));
2507 * Allocate a new tag and associate it with the address of the sv being
2508 * stored, before recursing...
2510 * In order to avoid creating new SvIVs to hold the tagnum we just
2511 * cast the tagnum to a SV pointer and store that in the hash. This
2512 * means that we must clean up the hash manually afterwards, but gives
2513 * us a 15% throughput increase.
2518 if (!hv_store(hseen,
2519 (char *) &sv, sizeof(sv), INT2PTR(SV*, cxt->tagnum), 0))
2523 * Store `sv' and everything beneath it, using appropriate routine.
2524 * Abort immediately if we get a non-zero status back.
2529 TRACEME(("storing 0x%"UVxf" tag #%d, type %d...",
2530 PTR2UV(sv), cxt->tagnum, type));
2533 HV *pkg = SvSTASH(sv);
2534 ret = store_blessed(cxt, sv, type, pkg);
2536 ret = SV_STORE(type)(cxt, sv);
2538 TRACEME(("%s (stored 0x%"UVxf", refcnt=%d, %s)",
2539 ret ? "FAILED" : "ok", PTR2UV(sv),
2540 SvREFCNT(sv), sv_reftype(sv, FALSE)));
2548 * Write magic number and system information into the file.
2549 * Layout is <magic> <network> [<len> <byteorder> <sizeof int> <sizeof long>
2550 * <sizeof ptr>] where <len> is the length of the byteorder hexa string.
2551 * All size and lenghts are written as single characters here.
2553 * Note that no byte ordering info is emitted when <network> is true, since
2554 * integers will be emitted in network order in that case.
2556 static int magic_write(stcxt_t *cxt)
2558 char buf[256]; /* Enough room for 256 hexa digits */
2560 int use_network_order = cxt->netorder;
2562 TRACEME(("magic_write on fd=%d", cxt->fio ? fileno(cxt->fio) : -1));
2565 WRITE(magicstr, strlen(magicstr)); /* Don't write final \0 */
2568 * Starting with 0.6, the "use_network_order" byte flag is also used to
2569 * indicate the version number of the binary image, encoded in the upper
2570 * bits. The bit 0 is always used to indicate network order.
2574 ((use_network_order ? 0x1 : 0x0) | (STORABLE_BIN_MAJOR << 1));
2578 * Starting with 0.7, a full byte is dedicated to the minor version of
2579 * the binary format, which is incremented only when new markers are
2580 * introduced, for instance, but when backward compatibility is preserved.
2583 PUTMARK((unsigned char) STORABLE_BIN_MINOR);
2585 if (use_network_order)
2586 return 0; /* Don't bother with byte ordering */
2588 sprintf(buf, "%lx", (unsigned long) BYTEORDER);
2589 c = (unsigned char) strlen(buf);
2591 WRITE(buf, (unsigned int) c); /* Don't write final \0 */
2592 PUTMARK((unsigned char) sizeof(int));
2593 PUTMARK((unsigned char) sizeof(long));
2594 PUTMARK((unsigned char) sizeof(char *));
2595 PUTMARK((unsigned char) sizeof(NV));
2597 TRACEME(("ok (magic_write byteorder = 0x%lx [%d], I%d L%d P%d D%d)",
2598 (unsigned long) BYTEORDER, (int) c,
2599 (int) sizeof(int), (int) sizeof(long),
2600 (int) sizeof(char *), (int) sizeof(NV)));
2608 * Common code for store operations.
2610 * When memory store is requested (f = NULL) and a non null SV* is given in
2611 * `res', it is filled with a new SV created out of the memory buffer.
2613 * It is required to provide a non-null `res' when the operation type is not
2614 * dclone() and store() is performed to memory.
2616 static int do_store(
2626 ASSERT(!(f == 0 && !(optype & ST_CLONE)) || res,
2627 ("must supply result SV pointer for real recursion to memory"));
2629 TRACEME(("do_store (optype=%d, netorder=%d)",
2630 optype, network_order));
2635 * Workaround for CROAK leak: if they enter with a "dirty" context,
2636 * free up memory for them now.
2643 * Now that STORABLE_xxx hooks exist, it is possible that they try to
2644 * re-enter store() via the hooks. We need to stack contexts.
2648 cxt = allocate_context(cxt);
2652 ASSERT(cxt->entry == 1, ("starting new recursion"));
2653 ASSERT(!cxt->s_dirty, ("clean context"));
2656 * Ensure sv is actually a reference. From perl, we called something
2658 * pstore(FILE, \@array);
2659 * so we must get the scalar value behing that reference.
2663 CROAK(("Not a reference"));
2664 sv = SvRV(sv); /* So follow it to know what to store */
2667 * If we're going to store to memory, reset the buffer.
2674 * Prepare context and emit headers.
2677 init_store_context(cxt, f, optype, network_order);
2679 if (-1 == magic_write(cxt)) /* Emit magic and ILP info */
2680 return 0; /* Error */
2683 * Recursively store object...
2686 ASSERT(is_storing(), ("within store operation"));
2688 status = store(cxt, sv); /* Just do it! */
2691 * If they asked for a memory store and they provided an SV pointer,
2692 * make an SV string out of the buffer and fill their pointer.
2694 * When asking for ST_REAL, it's MANDATORY for the caller to provide
2695 * an SV, since context cleanup might free the buffer if we did recurse.
2696 * (unless caller is dclone(), which is aware of that).
2699 if (!cxt->fio && res)
2705 * The "root" context is never freed, since it is meant to be always
2706 * handy for the common case where no recursion occurs at all (i.e.
2707 * we enter store() outside of any Storable code and leave it, period).
2708 * We know it's the "root" context because there's nothing stacked
2713 * When deep cloning, we don't free the context: doing so would force
2714 * us to copy the data in the memory buffer. Sicne we know we're
2715 * about to enter do_retrieve...
2718 clean_store_context(cxt);
2719 if (cxt->prev && !(cxt->optype & ST_CLONE))
2722 TRACEME(("do_store returns %d", status));
2730 * Store the transitive data closure of given object to disk.
2731 * Returns 0 on error, a true value otherwise.
2733 int pstore(PerlIO *f, SV *sv)
2735 TRACEME(("pstore"));
2736 return do_store(f, sv, 0, FALSE, (SV**) 0);
2743 * Same as pstore(), but network order is used for integers and doubles are
2744 * emitted as strings.
2746 int net_pstore(PerlIO *f, SV *sv)
2748 TRACEME(("net_pstore"));
2749 return do_store(f, sv, 0, TRUE, (SV**) 0);
2759 * Build a new SV out of the content of the internal memory buffer.
2761 static SV *mbuf2sv(void)
2765 return newSVpv(mbase, MBUF_SIZE());
2771 * Store the transitive data closure of given object to memory.
2772 * Returns undef on error, a scalar value containing the data otherwise.
2779 TRACEME(("mstore"));
2781 if (!do_store((PerlIO*) 0, sv, 0, FALSE, &out))
2782 return &PL_sv_undef;
2790 * Same as mstore(), but network order is used for integers and doubles are
2791 * emitted as strings.
2793 SV *net_mstore(SV *sv)
2798 TRACEME(("net_mstore"));
2800 if (!do_store((PerlIO*) 0, sv, 0, TRUE, &out))
2801 return &PL_sv_undef;
2807 *** Specific retrieve callbacks.
2813 * Return an error via croak, since it is not possible that we get here
2814 * under normal conditions, when facing a file produced via pstore().
2816 static SV *retrieve_other(stcxt_t *cxt)
2819 cxt->ver_major != STORABLE_BIN_MAJOR &&
2820 cxt->ver_minor != STORABLE_BIN_MINOR
2822 CROAK(("Corrupted storable %s (binary v%d.%d), current is v%d.%d",
2823 cxt->fio ? "file" : "string",
2824 cxt->ver_major, cxt->ver_minor,
2825 STORABLE_BIN_MAJOR, STORABLE_BIN_MINOR));
2827 CROAK(("Corrupted storable %s (binary v%d.%d)",
2828 cxt->fio ? "file" : "string",
2829 cxt->ver_major, cxt->ver_minor));
2832 return (SV *) 0; /* Just in case */
2836 * retrieve_idx_blessed
2838 * Layout is SX_IX_BLESS <index> <object> with SX_IX_BLESS already read.
2839 * <index> can be coded on either 1 or 5 bytes.
2841 static SV *retrieve_idx_blessed(stcxt_t *cxt)
2848 TRACEME(("retrieve_idx_blessed (#%d)", cxt->tagnum));
2850 GETMARK(idx); /* Index coded on a single char? */
2855 * Fetch classname in `aclass'
2858 sva = av_fetch(cxt->aclass, idx, FALSE);
2860 CROAK(("Class name #%d should have been seen already", (int)idx));
2862 class = SvPVX(*sva); /* We know it's a PV, by construction */
2864 TRACEME(("class ID %d => %s", idx, class));
2867 * Retrieve object and bless it.
2880 * Layout is SX_BLESS <len> <classname> <object> with SX_BLESS already read.
2881 * <len> can be coded on either 1 or 5 bytes.
2883 static SV *retrieve_blessed(stcxt_t *cxt)
2887 char buf[LG_BLESS + 1]; /* Avoid malloc() if possible */
2890 TRACEME(("retrieve_blessed (#%d)", cxt->tagnum));
2893 * Decode class name length and read that name.
2895 * Short classnames have two advantages: their length is stored on one
2896 * single byte, and the string can be read on the stack.
2899 GETMARK(len); /* Length coded on a single char? */
2902 TRACEME(("** allocating %d bytes for class name", len+1));
2903 New(10003, class, len+1, char);
2906 class[len] = '\0'; /* Mark string end */
2909 * It's a new classname, otherwise it would have been an SX_IX_BLESS.
2912 if (!av_store(cxt->aclass, cxt->classnum++, newSVpvn(class, len)))
2916 * Retrieve object and bless it.
2932 * Layout: SX_HOOK <flags> <len> <classname> <len2> <str> [<len3> <object-IDs>]
2933 * with leading mark already read, as usual.
2935 * When recursion was involved during serialization of the object, there
2936 * is an unknown amount of serialized objects after the SX_HOOK mark. Until
2937 * we reach a <flags> marker with the recursion bit cleared.
2939 static SV *retrieve_hook(stcxt_t *cxt)
2942 char buf[LG_BLESS + 1]; /* Avoid malloc() if possible */
2954 int clone = cxt->optype & ST_CLONE;
2956 TRACEME(("retrieve_hook (#%d)", cxt->tagnum));
2959 * Read flags, which tell us about the type, and whether we need to recurse.
2965 * Create the (empty) object, and mark it as seen.
2967 * This must be done now, because tags are incremented, and during
2968 * serialization, the object tag was affected before recursion could
2972 obj_type = flags & SHF_TYPE_MASK;
2978 sv = (SV *) newAV();
2981 sv = (SV *) newHV();
2984 return retrieve_other(cxt); /* Let it croak */
2989 * Whilst flags tell us to recurse, do so.
2991 * We don't need to remember the addresses returned by retrieval, because
2992 * all the references will be obtained through indirection via the object
2993 * tags in the object-ID list.
2996 while (flags & SHF_NEED_RECURSE) {
2997 TRACEME(("retrieve_hook recursing..."));
3001 TRACEME(("retrieve_hook back with rv=0x%"UVxf,
3006 if (flags & SHF_IDX_CLASSNAME) {
3011 * Fetch index from `aclass'
3014 if (flags & SHF_LARGE_CLASSLEN)
3019 sva = av_fetch(cxt->aclass, idx, FALSE);
3021 CROAK(("Class name #%d should have been seen already", (int)idx));
3023 class = SvPVX(*sva); /* We know it's a PV, by construction */
3024 TRACEME(("class ID %d => %s", idx, class));
3028 * Decode class name length and read that name.
3030 * NOTA BENE: even if the length is stored on one byte, we don't read
3031 * on the stack. Just like retrieve_blessed(), we limit the name to
3032 * LG_BLESS bytes. This is an arbitrary decision.
3035 if (flags & SHF_LARGE_CLASSLEN)
3040 if (len > LG_BLESS) {
3041 TRACEME(("** allocating %d bytes for class name", len+1));
3042 New(10003, class, len+1, char);
3046 class[len] = '\0'; /* Mark string end */
3049 * Record new classname.
3052 if (!av_store(cxt->aclass, cxt->classnum++, newSVpvn(class, len)))
3056 TRACEME(("class name: %s", class));
3059 * Decode user-frozen string length and read it in a SV.
3061 * For efficiency reasons, we read data directly into the SV buffer.
3062 * To understand that code, read retrieve_scalar()
3065 if (flags & SHF_LARGE_STRLEN)
3070 frozen = NEWSV(10002, len2);
3072 SAFEREAD(SvPVX(frozen), len2, frozen);
3073 SvCUR_set(frozen, len2);
3074 *SvEND(frozen) = '\0';
3076 (void) SvPOK_only(frozen); /* Validates string pointer */
3077 if (cxt->s_tainted) /* Is input source tainted? */
3080 TRACEME(("frozen string: %d bytes", len2));
3083 * Decode object-ID list length, if present.
3086 if (flags & SHF_HAS_LIST) {
3087 if (flags & SHF_LARGE_LISTLEN)
3093 av_extend(av, len3 + 1); /* Leave room for [0] */
3094 AvFILLp(av) = len3; /* About to be filled anyway */
3098 TRACEME(("has %d object IDs to link", len3));
3101 * Read object-ID list into array.
3102 * Because we pre-extended it, we can cheat and fill it manually.
3104 * We read object tags and we can convert them into SV* on the fly
3105 * because we know all the references listed in there (as tags)
3106 * have been already serialized, hence we have a valid correspondance
3107 * between each of those tags and the recreated SV.
3111 SV **ary = AvARRAY(av);
3113 for (i = 1; i <= len3; i++) { /* We leave [0] alone */
3120 svh = av_fetch(cxt->aseen, tag, FALSE);
3122 CROAK(("Object #%d should have been retrieved already", (int)tag));
3124 ary[i] = SvREFCNT_inc(xsv);
3129 * Bless the object and look up the STORABLE_thaw hook.
3133 hook = pkg_can(cxt->hook, SvSTASH(sv), "STORABLE_thaw");
3135 CROAK(("No STORABLE_thaw defined for objects of class %s", class));
3138 * If we don't have an `av' yet, prepare one.
3139 * Then insert the frozen string as item [0].
3147 AvARRAY(av)[0] = SvREFCNT_inc(frozen);
3152 * $object->STORABLE_thaw($cloning, $frozen, @refs);
3154 * where $object is our blessed (empty) object, $cloning is a boolean
3155 * telling whether we're running a deep clone, $frozen is the frozen
3156 * string the user gave us in his serializing hook, and @refs, which may
3157 * be empty, is the list of extra references he returned along for us
3160 * In effect, the hook is an alternate creation routine for the class,
3161 * the object itself being already created by the runtime.
3164 TRACEME(("calling STORABLE_thaw on %s at 0x%"UVxf" (%"IVdf" args)",
3165 class, PTR2UV(sv), AvFILLp(av) + 1));
3168 (void) scalar_call(rv, hook, clone, av, G_SCALAR|G_DISCARD);
3175 SvREFCNT_dec(frozen);
3178 if (!(flags & SHF_IDX_CLASSNAME) && class != buf)
3187 * Retrieve reference to some other scalar.
3188 * Layout is SX_REF <object>, with SX_REF already read.
3190 static SV *retrieve_ref(stcxt_t *cxt)
3195 TRACEME(("retrieve_ref (#%d)", cxt->tagnum));
3198 * We need to create the SV that holds the reference to the yet-to-retrieve
3199 * object now, so that we may record the address in the seen table.
3200 * Otherwise, if the object to retrieve references us, we won't be able
3201 * to resolve the SX_OBJECT we'll see at that point! Hence we cannot
3202 * do the retrieve first and use rv = newRV(sv) since it will be too late
3203 * for SEEN() recording.
3206 rv = NEWSV(10002, 0);
3207 SEEN(rv); /* Will return if rv is null */
3208 sv = retrieve(cxt); /* Retrieve <object> */
3210 return (SV *) 0; /* Failed */
3213 * WARNING: breaks RV encapsulation.
3215 * Now for the tricky part. We have to upgrade our existing SV, so that
3216 * it is now an RV on sv... Again, we cheat by duplicating the code
3217 * held in newSVrv(), since we already got our SV from retrieve().
3221 * SvRV(rv) = SvREFCNT_inc(sv);
3223 * here because the reference count we got from retrieve() above is
3224 * already correct: if the object was retrieved from the file, then
3225 * its reference count is one. Otherwise, if it was retrieved via
3226 * an SX_OBJECT indication, a ref count increment was done.
3229 sv_upgrade(rv, SVt_RV);
3230 SvRV(rv) = sv; /* $rv = \$sv */
3233 TRACEME(("ok (retrieve_ref at 0x%"UVxf")", PTR2UV(rv)));
3239 * retrieve_overloaded
3241 * Retrieve reference to some other scalar with overloading.
3242 * Layout is SX_OVERLOAD <object>, with SX_OVERLOAD already read.
3244 static SV *retrieve_overloaded(stcxt_t *cxt)
3250 TRACEME(("retrieve_overloaded (#%d)", cxt->tagnum));
3253 * Same code as retrieve_ref(), duplicated to avoid extra call.
3256 rv = NEWSV(10002, 0);
3257 SEEN(rv); /* Will return if rv is null */
3258 sv = retrieve(cxt); /* Retrieve <object> */
3260 return (SV *) 0; /* Failed */
3263 * WARNING: breaks RV encapsulation.
3266 sv_upgrade(rv, SVt_RV);
3267 SvRV(rv) = sv; /* $rv = \$sv */
3271 * Restore overloading magic.
3274 stash = (HV *) SvSTASH (sv);
3275 if (!stash || !Gv_AMG(stash))
3276 CROAK(("Cannot restore overloading on %s(0x%"UVxf")",
3277 sv_reftype(sv, FALSE),
3282 TRACEME(("ok (retrieve_overloaded at 0x%"UVxf")", PTR2UV(rv)));
3288 * retrieve_tied_array
3290 * Retrieve tied array
3291 * Layout is SX_TIED_ARRAY <object>, with SX_TIED_ARRAY already read.
3293 static SV *retrieve_tied_array(stcxt_t *cxt)
3298 TRACEME(("retrieve_tied_array (#%d)", cxt->tagnum));
3300 tv = NEWSV(10002, 0);
3301 SEEN(tv); /* Will return if tv is null */
3302 sv = retrieve(cxt); /* Retrieve <object> */
3304 return (SV *) 0; /* Failed */
3306 sv_upgrade(tv, SVt_PVAV);
3307 AvREAL_off((AV *)tv);
3308 sv_magic(tv, sv, 'P', Nullch, 0);
3309 SvREFCNT_dec(sv); /* Undo refcnt inc from sv_magic() */
3311 TRACEME(("ok (retrieve_tied_array at 0x%"UVxf")", PTR2UV(tv)));
3317 * retrieve_tied_hash
3319 * Retrieve tied hash
3320 * Layout is SX_TIED_HASH <object>, with SX_TIED_HASH already read.
3322 static SV *retrieve_tied_hash(stcxt_t *cxt)
3327 TRACEME(("retrieve_tied_hash (#%d)", cxt->tagnum));
3329 tv = NEWSV(10002, 0);
3330 SEEN(tv); /* Will return if tv is null */
3331 sv = retrieve(cxt); /* Retrieve <object> */
3333 return (SV *) 0; /* Failed */
3335 sv_upgrade(tv, SVt_PVHV);
3336 sv_magic(tv, sv, 'P', Nullch, 0);
3337 SvREFCNT_dec(sv); /* Undo refcnt inc from sv_magic() */
3339 TRACEME(("ok (retrieve_tied_hash at 0x%"UVxf")", PTR2UV(tv)));
3345 * retrieve_tied_scalar
3347 * Retrieve tied scalar
3348 * Layout is SX_TIED_SCALAR <object>, with SX_TIED_SCALAR already read.
3350 static SV *retrieve_tied_scalar(cxt)
3356 TRACEME(("retrieve_tied_scalar (#%d)", cxt->tagnum));
3358 tv = NEWSV(10002, 0);
3359 SEEN(tv); /* Will return if rv is null */
3360 sv = retrieve(cxt); /* Retrieve <object> */
3362 return (SV *) 0; /* Failed */
3364 sv_upgrade(tv, SVt_PVMG);
3365 sv_magic(tv, sv, 'q', Nullch, 0);
3366 SvREFCNT_dec(sv); /* Undo refcnt inc from sv_magic() */
3368 TRACEME(("ok (retrieve_tied_scalar at 0x%"UVxf")", PTR2UV(tv)));
3376 * Retrieve reference to value in a tied hash.
3377 * Layout is SX_TIED_KEY <object> <key>, with SX_TIED_KEY already read.
3379 static SV *retrieve_tied_key(stcxt_t *cxt)
3385 TRACEME(("retrieve_tied_key (#%d)", cxt->tagnum));
3387 tv = NEWSV(10002, 0);
3388 SEEN(tv); /* Will return if tv is null */
3389 sv = retrieve(cxt); /* Retrieve <object> */
3391 return (SV *) 0; /* Failed */
3393 key = retrieve(cxt); /* Retrieve <key> */
3395 return (SV *) 0; /* Failed */
3397 sv_upgrade(tv, SVt_PVMG);
3398 sv_magic(tv, sv, 'p', (char *)key, HEf_SVKEY);
3399 SvREFCNT_dec(key); /* Undo refcnt inc from sv_magic() */
3400 SvREFCNT_dec(sv); /* Undo refcnt inc from sv_magic() */
3408 * Retrieve reference to value in a tied array.
3409 * Layout is SX_TIED_IDX <object> <idx>, with SX_TIED_IDX already read.
3411 static SV *retrieve_tied_idx(stcxt_t *cxt)
3417 TRACEME(("retrieve_tied_idx (#%d)", cxt->tagnum));
3419 tv = NEWSV(10002, 0);
3420 SEEN(tv); /* Will return if tv is null */
3421 sv = retrieve(cxt); /* Retrieve <object> */
3423 return (SV *) 0; /* Failed */
3425 RLEN(idx); /* Retrieve <idx> */
3427 sv_upgrade(tv, SVt_PVMG);
3428 sv_magic(tv, sv, 'p', Nullch, idx);
3429 SvREFCNT_dec(sv); /* Undo refcnt inc from sv_magic() */
3438 * Retrieve defined long (string) scalar.
3440 * Layout is SX_LSCALAR <length> <data>, with SX_LSCALAR already read.
3441 * The scalar is "long" in that <length> is larger than LG_SCALAR so it
3442 * was not stored on a single byte.
3444 static SV *retrieve_lscalar(stcxt_t *cxt)
3450 TRACEME(("retrieve_lscalar (#%d), len = %"IVdf, cxt->tagnum, len));
3453 * Allocate an empty scalar of the suitable length.
3456 sv = NEWSV(10002, len);
3457 SEEN(sv); /* Associate this new scalar with tag "tagnum" */
3460 * WARNING: duplicates parts of sv_setpv and breaks SV data encapsulation.
3462 * Now, for efficiency reasons, read data directly inside the SV buffer,
3463 * and perform the SV final settings directly by duplicating the final
3464 * work done by sv_setpv. Since we're going to allocate lots of scalars
3465 * this way, it's worth the hassle and risk.
3468 SAFEREAD(SvPVX(sv), len, sv);
3469 SvCUR_set(sv, len); /* Record C string length */
3470 *SvEND(sv) = '\0'; /* Ensure it's null terminated anyway */
3471 (void) SvPOK_only(sv); /* Validate string pointer */
3472 if (cxt->s_tainted) /* Is input source tainted? */
3473 SvTAINT(sv); /* External data cannot be trusted */
3475 TRACEME(("large scalar len %"IVdf" '%s'", len, SvPVX(sv)));
3476 TRACEME(("ok (retrieve_lscalar at 0x%"UVxf")", PTR2UV(sv)));
3484 * Retrieve defined short (string) scalar.
3486 * Layout is SX_SCALAR <length> <data>, with SX_SCALAR already read.
3487 * The scalar is "short" so <length> is single byte. If it is 0, there
3488 * is no <data> section.
3490 static SV *retrieve_scalar(stcxt_t *cxt)
3496 TRACEME(("retrieve_scalar (#%d), len = %d", cxt->tagnum, len));
3499 * Allocate an empty scalar of the suitable length.
3502 sv = NEWSV(10002, len);
3503 SEEN(sv); /* Associate this new scalar with tag "tagnum" */
3506 * WARNING: duplicates parts of sv_setpv and breaks SV data encapsulation.
3511 * newSV did not upgrade to SVt_PV so the scalar is undefined.
3512 * To make it defined with an empty length, upgrade it now...
3514 sv_upgrade(sv, SVt_PV);
3516 *SvEND(sv) = '\0'; /* Ensure it's null terminated anyway */
3517 TRACEME(("ok (retrieve_scalar empty at 0x%"UVxf")", PTR2UV(sv)));
3520 * Now, for efficiency reasons, read data directly inside the SV buffer,
3521 * and perform the SV final settings directly by duplicating the final
3522 * work done by sv_setpv. Since we're going to allocate lots of scalars
3523 * this way, it's worth the hassle and risk.
3525 SAFEREAD(SvPVX(sv), len, sv);
3526 SvCUR_set(sv, len); /* Record C string length */
3527 *SvEND(sv) = '\0'; /* Ensure it's null terminated anyway */
3528 TRACEME(("small scalar len %d '%s'", len, SvPVX(sv)));
3531 (void) SvPOK_only(sv); /* Validate string pointer */
3532 if (cxt->s_tainted) /* Is input source tainted? */
3533 SvTAINT(sv); /* External data cannot be trusted */
3535 TRACEME(("ok (retrieve_scalar at 0x%"UVxf")", PTR2UV(sv)));
3542 * Like retrieve_scalar(), but tag result as utf8.
3543 * If we're retrieving UTF8 data in a non-UTF8 perl, croaks.
3545 static SV *retrieve_utf8str(stcxt_t *cxt)
3549 TRACEME(("retrieve_utf8str"));
3551 sv = retrieve_scalar(cxt);
3561 * Like retrieve_lscalar(), but tag result as utf8.
3562 * If we're retrieving UTF8 data in a non-UTF8 perl, croaks.
3564 static SV *retrieve_lutf8str(stcxt_t *cxt)
3568 TRACEME(("retrieve_lutf8str"));
3570 sv = retrieve_lscalar(cxt);
3580 * Retrieve defined integer.
3581 * Layout is SX_INTEGER <data>, whith SX_INTEGER already read.
3583 static SV *retrieve_integer(stcxt_t *cxt)
3588 TRACEME(("retrieve_integer (#%d)", cxt->tagnum));
3590 READ(&iv, sizeof(iv));
3592 SEEN(sv); /* Associate this new scalar with tag "tagnum" */
3594 TRACEME(("integer %"IVdf, iv));
3595 TRACEME(("ok (retrieve_integer at 0x%"UVxf")", PTR2UV(sv)));
3603 * Retrieve defined integer in network order.
3604 * Layout is SX_NETINT <data>, whith SX_NETINT already read.
3606 static SV *retrieve_netint(stcxt_t *cxt)
3611 TRACEME(("retrieve_netint (#%d)", cxt->tagnum));
3615 sv = newSViv((int) ntohl(iv));
3616 TRACEME(("network integer %d", (int) ntohl(iv)));
3619 TRACEME(("network integer (as-is) %d", iv));
3621 SEEN(sv); /* Associate this new scalar with tag "tagnum" */
3623 TRACEME(("ok (retrieve_netint at 0x%"UVxf")", PTR2UV(sv)));
3631 * Retrieve defined double.
3632 * Layout is SX_DOUBLE <data>, whith SX_DOUBLE already read.
3634 static SV *retrieve_double(stcxt_t *cxt)
3639 TRACEME(("retrieve_double (#%d)", cxt->tagnum));
3641 READ(&nv, sizeof(nv));
3643 SEEN(sv); /* Associate this new scalar with tag "tagnum" */
3645 TRACEME(("double %"NVff, nv));
3646 TRACEME(("ok (retrieve_double at 0x%"UVxf")", PTR2UV(sv)));
3654 * Retrieve defined byte (small integer within the [-128, +127] range).
3655 * Layout is SX_BYTE <data>, whith SX_BYTE already read.
3657 static SV *retrieve_byte(stcxt_t *cxt)
3662 TRACEME(("retrieve_byte (#%d)", cxt->tagnum));
3665 TRACEME(("small integer read as %d", (unsigned char) siv));
3666 sv = newSViv((unsigned char) siv - 128);
3667 SEEN(sv); /* Associate this new scalar with tag "tagnum" */
3669 TRACEME(("byte %d", (unsigned char) siv - 128));
3670 TRACEME(("ok (retrieve_byte at 0x%"UVxf")", PTR2UV(sv)));
3678 * Return the undefined value.
3680 static SV *retrieve_undef(stcxt_t *cxt)
3684 TRACEME(("retrieve_undef"));
3695 * Return the immortal undefined value.
3697 static SV *retrieve_sv_undef(stcxt_t *cxt)
3699 SV *sv = &PL_sv_undef;
3701 TRACEME(("retrieve_sv_undef"));
3710 * Return the immortal yes value.
3712 static SV *retrieve_sv_yes(stcxt_t *cxt)
3714 SV *sv = &PL_sv_yes;
3716 TRACEME(("retrieve_sv_yes"));
3725 * Return the immortal no value.
3727 static SV *retrieve_sv_no(stcxt_t *cxt)
3731 TRACEME(("retrieve_sv_no"));
3740 * Retrieve a whole array.
3741 * Layout is SX_ARRAY <size> followed by each item, in increading index order.
3742 * Each item is stored as <object>.
3744 * When we come here, SX_ARRAY has been read already.
3746 static SV *retrieve_array(stcxt_t *cxt)
3753 TRACEME(("retrieve_array (#%d)", cxt->tagnum));
3756 * Read length, and allocate array, then pre-extend it.
3760 TRACEME(("size = %d", len));
3762 SEEN(av); /* Will return if array not allocated nicely */
3766 return (SV *) av; /* No data follow if array is empty */
3769 * Now get each item in turn...
3772 for (i = 0; i < len; i++) {
3773 TRACEME(("(#%d) item", i));
3774 sv = retrieve(cxt); /* Retrieve item */
3777 if (av_store(av, i, sv) == 0)
3781 TRACEME(("ok (retrieve_array at 0x%"UVxf")", PTR2UV(av)));
3789 * Retrieve a whole hash table.
3790 * Layout is SX_HASH <size> followed by each key/value pair, in random order.
3791 * Keys are stored as <length> <data>, the <data> section being omitted
3793 * Values are stored as <object>.
3795 * When we come here, SX_HASH has been read already.
3797 static SV *retrieve_hash(stcxt_t *cxt)
3804 static SV *sv_h_undef = (SV *) 0; /* hv_store() bug */
3806 TRACEME(("retrieve_hash (#%d)", cxt->tagnum));
3809 * Read length, allocate table.
3813 TRACEME(("size = %d", len));
3815 SEEN(hv); /* Will return if table not allocated properly */
3817 return (SV *) hv; /* No data follow if table empty */
3820 * Now get each key/value pair in turn...
3823 for (i = 0; i < len; i++) {
3828 TRACEME(("(#%d) value", i));
3835 * Since we're reading into kbuf, we must ensure we're not
3836 * recursing between the read and the hv_store() where it's used.
3837 * Hence the key comes after the value.
3840 RLEN(size); /* Get key size */
3841 KBUFCHK(size); /* Grow hash key read pool if needed */
3844 kbuf[size] = '\0'; /* Mark string end, just in case */
3845 TRACEME(("(#%d) key '%s'", i, kbuf));
3848 * Enter key/value pair into hash table.
3851 if (hv_store(hv, kbuf, (U32) size, sv, 0) == 0)
3855 TRACEME(("ok (retrieve_hash at 0x%"UVxf")", PTR2UV(hv)));
3861 * old_retrieve_array
3863 * Retrieve a whole array in pre-0.6 binary format.
3865 * Layout is SX_ARRAY <size> followed by each item, in increading index order.
3866 * Each item is stored as SX_ITEM <object> or SX_IT_UNDEF for "holes".
3868 * When we come here, SX_ARRAY has been read already.
3870 static SV *old_retrieve_array(stcxt_t *cxt)
3878 TRACEME(("old_retrieve_array (#%d)", cxt->tagnum));
3881 * Read length, and allocate array, then pre-extend it.
3885 TRACEME(("size = %d", len));
3887 SEEN(av); /* Will return if array not allocated nicely */
3891 return (SV *) av; /* No data follow if array is empty */
3894 * Now get each item in turn...
3897 for (i = 0; i < len; i++) {
3899 if (c == SX_IT_UNDEF) {
3900 TRACEME(("(#%d) undef item", i));
3901 continue; /* av_extend() already filled us with undef */
3904 (void) retrieve_other((stcxt_t *) 0); /* Will croak out */
3905 TRACEME(("(#%d) item", i));
3906 sv = retrieve(cxt); /* Retrieve item */
3909 if (av_store(av, i, sv) == 0)
3913 TRACEME(("ok (old_retrieve_array at 0x%"UVxf")", PTR2UV(av)));
3921 * Retrieve a whole hash table in pre-0.6 binary format.
3923 * Layout is SX_HASH <size> followed by each key/value pair, in random order.
3924 * Keys are stored as SX_KEY <length> <data>, the <data> section being omitted
3926 * Values are stored as SX_VALUE <object> or SX_VL_UNDEF for "holes".
3928 * When we come here, SX_HASH has been read already.
3930 static SV *old_retrieve_hash(stcxt_t *cxt)
3938 static SV *sv_h_undef = (SV *) 0; /* hv_store() bug */
3940 TRACEME(("old_retrieve_hash (#%d)", cxt->tagnum));
3943 * Read length, allocate table.
3947 TRACEME(("size = %d", len));
3949 SEEN(hv); /* Will return if table not allocated properly */
3951 return (SV *) hv; /* No data follow if table empty */
3954 * Now get each key/value pair in turn...
3957 for (i = 0; i < len; i++) {
3963 if (c == SX_VL_UNDEF) {
3964 TRACEME(("(#%d) undef value", i));
3966 * Due to a bug in hv_store(), it's not possible to pass
3967 * &PL_sv_undef to hv_store() as a value, otherwise the
3968 * associated key will not be creatable any more. -- RAM, 14/01/97
3971 sv_h_undef = newSVsv(&PL_sv_undef);
3972 sv = SvREFCNT_inc(sv_h_undef);
3973 } else if (c == SX_VALUE) {
3974 TRACEME(("(#%d) value", i));
3979 (void) retrieve_other((stcxt_t *) 0); /* Will croak out */
3983 * Since we're reading into kbuf, we must ensure we're not
3984 * recursing between the read and the hv_store() where it's used.
3985 * Hence the key comes after the value.
3990 (void) retrieve_other((stcxt_t *) 0); /* Will croak out */
3991 RLEN(size); /* Get key size */
3992 KBUFCHK(size); /* Grow hash key read pool if needed */
3995 kbuf[size] = '\0'; /* Mark string end, just in case */
3996 TRACEME(("(#%d) key '%s'", i, kbuf));
3999 * Enter key/value pair into hash table.
4002 if (hv_store(hv, kbuf, (U32) size, sv, 0) == 0)
4006 TRACEME(("ok (retrieve_hash at 0x%"UVxf")", PTR2UV(hv)));
4012 *** Retrieval engine.
4018 * Make sure the stored data we're trying to retrieve has been produced
4019 * on an ILP compatible system with the same byteorder. It croaks out in
4020 * case an error is detected. [ILP = integer-long-pointer sizes]
4021 * Returns null if error is detected, &PL_sv_undef otherwise.
4023 * Note that there's no byte ordering info emitted when network order was
4024 * used at store time.
4026 static SV *magic_check(stcxt_t *cxt)
4029 char byteorder[256];
4031 int use_network_order;
4033 int version_minor = 0;
4035 TRACEME(("magic_check"));
4038 * The "magic number" is only for files, not when freezing in memory.
4042 STRLEN len = sizeof(magicstr) - 1;
4045 READ(buf, len); /* Not null-terminated */
4046 buf[len] = '\0'; /* Is now */
4048 if (0 == strcmp(buf, magicstr))
4052 * Try to read more bytes to check for the old magic number, which
4056 old_len = sizeof(old_magicstr) - 1;
4057 READ(&buf[len], old_len - len);
4058 buf[old_len] = '\0'; /* Is now null-terminated */
4060 if (strcmp(buf, old_magicstr))
4061 CROAK(("File is not a perl storable"));
4066 * Starting with 0.6, the "use_network_order" byte flag is also used to
4067 * indicate the version number of the binary, and therefore governs the
4068 * setting of sv_retrieve_vtbl. See magic_write().
4071 GETMARK(use_network_order);
4072 version_major = use_network_order >> 1;
4073 cxt->retrieve_vtbl = version_major ? sv_retrieve : sv_old_retrieve;
4075 TRACEME(("magic_check: netorder = 0x%x", use_network_order));
4079 * Starting with 0.7 (binary major 2), a full byte is dedicated to the
4080 * minor version of the protocol. See magic_write().
4083 if (version_major > 1)
4084 GETMARK(version_minor);
4086 cxt->ver_major = version_major;
4087 cxt->ver_minor = version_minor;
4089 TRACEME(("binary image version is %d.%d", version_major, version_minor));
4092 * Inter-operability sanity check: we can't retrieve something stored
4093 * using a format more recent than ours, because we have no way to
4094 * know what has changed, and letting retrieval go would mean a probable
4095 * failure reporting a "corrupted" storable file.
4099 version_major > STORABLE_BIN_MAJOR ||
4100 (version_major == STORABLE_BIN_MAJOR &&
4101 version_minor > STORABLE_BIN_MINOR)
4103 CROAK(("Storable binary image v%d.%d more recent than I am (v%d.%d)",
4104 version_major, version_minor,
4105 STORABLE_BIN_MAJOR, STORABLE_BIN_MINOR));
4108 * If they stored using network order, there's no byte ordering
4109 * information to check.
4112 if (cxt->netorder = (use_network_order & 0x1))
4113 return &PL_sv_undef; /* No byte ordering info */
4115 sprintf(byteorder, "%lx", (unsigned long) BYTEORDER);
4117 READ(buf, c); /* Not null-terminated */
4118 buf[c] = '\0'; /* Is now */
4120 if (strcmp(buf, byteorder))
4121 CROAK(("Byte order is not compatible"));
4123 GETMARK(c); /* sizeof(int) */
4124 if ((int) c != sizeof(int))
4125 CROAK(("Integer size is not compatible"));
4127 GETMARK(c); /* sizeof(long) */
4128 if ((int) c != sizeof(long))
4129 CROAK(("Long integer size is not compatible"));
4131 GETMARK(c); /* sizeof(char *) */
4132 if ((int) c != sizeof(char *))
4133 CROAK(("Pointer integer size is not compatible"));
4135 if (version_major >= 2 && version_minor >= 2) {
4136 GETMARK(c); /* sizeof(NV) */
4137 if ((int) c != sizeof(NV))
4138 CROAK(("Double size is not compatible"));
4141 return &PL_sv_undef; /* OK */
4147 * Recursively retrieve objects from the specified file and return their
4148 * root SV (which may be an AV or an HV for what we care).
4149 * Returns null if there is a problem.
4151 static SV *retrieve(stcxt_t *cxt)
4157 TRACEME(("retrieve"));
4160 * Grab address tag which identifies the object if we are retrieving
4161 * an older format. Since the new binary format counts objects and no
4162 * longer explicitely tags them, we must keep track of the correspondance
4165 * The following section will disappear one day when the old format is
4166 * no longer supported, hence the final "goto" in the "if" block.
4169 if (cxt->hseen) { /* Retrieving old binary */
4171 if (cxt->netorder) {
4173 READ(&nettag, sizeof(I32)); /* Ordered sequence of I32 */
4174 tag = (stag_t) nettag;
4176 READ(&tag, sizeof(stag_t)); /* Original address of the SV */
4179 if (type == SX_OBJECT) {
4181 svh = hv_fetch(cxt->hseen, (char *) &tag, sizeof(tag), FALSE);
4183 CROAK(("Old tag 0x%x should have been mapped already", (unsigned)tag));
4184 tagn = SvIV(*svh); /* Mapped tag number computed earlier below */
4187 * The following code is common with the SX_OBJECT case below.
4190 svh = av_fetch(cxt->aseen, tagn, FALSE);
4192 CROAK(("Object #%d should have been retrieved already", (int)tagn));
4194 TRACEME(("has retrieved #%d at 0x%"UVxf, tagn, PTR2UV(sv)));
4195 SvREFCNT_inc(sv); /* One more reference to this same sv */
4196 return sv; /* The SV pointer where object was retrieved */
4200 * Map new object, but don't increase tagnum. This will be done
4201 * by each of the retrieve_* functions when they call SEEN().
4203 * The mapping associates the "tag" initially present with a unique
4204 * tag number. See test for SX_OBJECT above to see how this is perused.
4207 if (!hv_store(cxt->hseen, (char *) &tag, sizeof(tag),
4208 newSViv(cxt->tagnum), 0))
4215 * Regular post-0.6 binary format.
4221 TRACEME(("retrieve type = %d", type));
4224 * Are we dealing with an object we should have already retrieved?
4227 if (type == SX_OBJECT) {
4231 svh = av_fetch(cxt->aseen, tag, FALSE);
4233 CROAK(("Object #%d should have been retrieved already", (int)tag));
4235 TRACEME(("had retrieved #%d at 0x%"UVxf, tag, PTR2UV(sv)));
4236 SvREFCNT_inc(sv); /* One more reference to this same sv */
4237 return sv; /* The SV pointer where object was retrieved */
4240 first_time: /* Will disappear when support for old format is dropped */
4243 * Okay, first time through for this one.
4246 sv = RETRIEVE(cxt, type)(cxt);
4248 return (SV *) 0; /* Failed */
4251 * Old binary formats (pre-0.7).
4253 * Final notifications, ended by SX_STORED may now follow.
4254 * Currently, the only pertinent notification to apply on the
4255 * freshly retrieved object is either:
4256 * SX_CLASS <char-len> <classname> for short classnames.
4257 * SX_LG_CLASS <int-len> <classname> for larger one (rare!).
4258 * Class name is then read into the key buffer pool used by
4259 * hash table key retrieval.
4262 if (cxt->ver_major < 2) {
4263 while ((type = GETCHAR()) != SX_STORED) {
4267 GETMARK(len); /* Length coded on a single char */
4269 case SX_LG_CLASS: /* Length coded on a regular integer */
4274 return (SV *) 0; /* Failed */
4276 KBUFCHK(len); /* Grow buffer as necessary */
4279 kbuf[len] = '\0'; /* Mark string end */
4284 TRACEME(("ok (retrieved 0x%"UVxf", refcnt=%d, %s)", PTR2UV(sv),
4285 SvREFCNT(sv) - 1, sv_reftype(sv, FALSE)));
4293 * Retrieve data held in file and return the root object.
4294 * Common routine for pretrieve and mretrieve.
4296 static SV *do_retrieve(
4303 int is_tainted; /* Is input source tainted? */
4304 struct extendable msave; /* Where potentially valid mbuf is saved */
4306 TRACEME(("do_retrieve (optype = 0x%x)", optype));
4308 optype |= ST_RETRIEVE;
4311 * Sanity assertions for retrieve dispatch tables.
4314 ASSERT(sizeof(sv_old_retrieve) == sizeof(sv_retrieve),
4315 ("old and new retrieve dispatch table have same size"));
4316 ASSERT(sv_old_retrieve[SX_ERROR] == retrieve_other,
4317 ("SX_ERROR entry correctly initialized in old dispatch table"));
4318 ASSERT(sv_retrieve[SX_ERROR] == retrieve_other,
4319 ("SX_ERROR entry correctly initialized in new dispatch table"));
4322 * Workaround for CROAK leak: if they enter with a "dirty" context,
4323 * free up memory for them now.
4330 * Now that STORABLE_xxx hooks exist, it is possible that they try to
4331 * re-enter retrieve() via the hooks.
4335 cxt = allocate_context(cxt);
4339 ASSERT(cxt->entry == 1, ("starting new recursion"));
4340 ASSERT(!cxt->s_dirty, ("clean context"));
4345 * Data is loaded into the memory buffer when f is NULL, unless `in' is
4346 * also NULL, in which case we're expecting the data to already lie
4347 * in the buffer (dclone case).
4350 KBUFINIT(); /* Allocate hash key reading pool once */
4353 StructCopy(&cxt->membuf, &msave, struct extendable);
4359 * Magic number verifications.
4361 * This needs to be done before calling init_retrieve_context()
4362 * since the format indication in the file are necessary to conduct
4363 * some of the initializations.
4366 cxt->fio = f; /* Where I/O are performed */
4368 if (!magic_check(cxt))
4369 CROAK(("Magic number checking on storable %s failed",
4370 cxt->fio ? "file" : "string"));
4372 TRACEME(("data stored in %s format",
4373 cxt->netorder ? "net order" : "native"));
4376 * Check whether input source is tainted, so that we don't wrongly
4377 * taint perfectly good values...
4379 * We assume file input is always tainted. If both `f' and `in' are
4380 * NULL, then we come from dclone, and tainted is already filled in
4381 * the context. That's a kludge, but the whole dclone() thing is
4382 * already quite a kludge anyway! -- RAM, 15/09/2000.
4385 is_tainted = f ? 1 : (in ? SvTAINTED(in) : cxt->s_tainted);
4386 TRACEME(("input source is %s", is_tainted ? "tainted" : "trusted"));
4387 init_retrieve_context(cxt, optype, is_tainted);
4389 ASSERT(is_retrieving(), ("within retrieve operation"));
4391 sv = retrieve(cxt); /* Recursively retrieve object, get root SV */
4398 StructCopy(&msave, &cxt->membuf, struct extendable);
4401 * The "root" context is never freed.
4404 clean_retrieve_context(cxt);
4405 if (cxt->prev) /* This context was stacked */
4406 free_context(cxt); /* It was not the "root" context */
4409 * Prepare returned value.
4413 TRACEME(("retrieve ERROR"));
4414 return &PL_sv_undef; /* Something went wrong, return undef */
4417 TRACEME(("retrieve got %s(0x%"UVxf")",
4418 sv_reftype(sv, FALSE), PTR2UV(sv)));
4421 * Backward compatibility with Storable-0.5@9 (which we know we
4422 * are retrieving if hseen is non-null): don't create an extra RV
4423 * for objects since we special-cased it at store time.
4425 * Build a reference to the SV returned by pretrieve even if it is
4426 * already one and not a scalar, for consistency reasons.
4428 * NB: although context might have been cleaned, the value of `cxt->hseen'
4429 * remains intact, and can be used as a flag.
4432 if (cxt->hseen) { /* Was not handling overloading by then */
4434 if (sv_type(sv) == svis_REF && (rv = SvRV(sv)) && SvOBJECT(rv))
4439 * If reference is overloaded, restore behaviour.
4441 * NB: minor glitch here: normally, overloaded refs are stored specially
4442 * so that we can croak when behaviour cannot be re-installed, and also
4443 * avoid testing for overloading magic at each reference retrieval.
4445 * Unfortunately, the root reference is implicitely stored, so we must
4446 * check for possible overloading now. Furthermore, if we don't restore
4447 * overloading, we cannot croak as if the original ref was, because we
4448 * have no way to determine whether it was an overloaded ref or not in
4451 * It's a pity that overloading magic is attached to the rv, and not to
4452 * the underlying sv as blessing is.
4456 HV *stash = (HV *) SvSTASH (sv);
4457 SV *rv = newRV_noinc(sv);
4458 if (stash && Gv_AMG(stash)) {
4460 TRACEME(("restored overloading on root reference"));
4465 return newRV_noinc(sv);
4471 * Retrieve data held in file and return the root object, undef on error.
4473 SV *pretrieve(PerlIO *f)
4475 TRACEME(("pretrieve"));
4476 return do_retrieve(f, Nullsv, 0);
4482 * Retrieve data held in scalar and return the root object, undef on error.
4484 SV *mretrieve(SV *sv)
4486 TRACEME(("mretrieve"));
4487 return do_retrieve((PerlIO*) 0, sv, 0);
4497 * Deep clone: returns a fresh copy of the original referenced SV tree.
4499 * This is achieved by storing the object in memory and restoring from
4500 * there. Not that efficient, but it should be faster than doing it from
4507 stcxt_t *real_context;
4510 TRACEME(("dclone"));
4513 * Workaround for CROAK leak: if they enter with a "dirty" context,
4514 * free up memory for them now.
4521 * do_store() optimizes for dclone by not freeing its context, should
4522 * we need to allocate one because we're deep cloning from a hook.
4525 if (!do_store((PerlIO*) 0, sv, ST_CLONE, FALSE, (SV**) 0))
4526 return &PL_sv_undef; /* Error during store */
4529 * Because of the above optimization, we have to refresh the context,
4530 * since a new one could have been allocated and stacked by do_store().
4533 { dSTCXT; real_context = cxt; } /* Sub-block needed for macro */
4534 cxt = real_context; /* And we need this temporary... */
4537 * Now, `cxt' may refer to a new context.
4540 ASSERT(!cxt->s_dirty, ("clean context"));
4541 ASSERT(!cxt->entry, ("entry will not cause new context allocation"));
4544 TRACEME(("dclone stored %d bytes", size));
4548 * Since we're passing do_retrieve() both a NULL file and sv, we need
4549 * to pre-compute the taintedness of the input by setting cxt->tainted
4550 * to whatever state our own input string was. -- RAM, 15/09/2000
4552 * do_retrieve() will free non-root context.
4555 cxt->s_tainted = SvTAINTED(sv);
4556 out = do_retrieve((PerlIO*) 0, Nullsv, ST_CLONE);
4558 TRACEME(("dclone returns 0x%"UVxf, PTR2UV(out)));
4568 * The Perl IO GV object distinguishes between input and output for sockets
4569 * but not for plain files. To allow Storable to transparently work on
4570 * plain files and sockets transparently, we have to ask xsubpp to fetch the
4571 * right object for us. Hence the OutputStream and InputStream declarations.
4573 * Before perl 5.004_05, those entries in the standard typemap are not
4574 * defined in perl include files, so we do that here.
4577 #ifndef OutputStream
4578 #define OutputStream PerlIO *
4579 #define InputStream PerlIO *
4580 #endif /* !OutputStream */
4582 MODULE = Storable PACKAGE = Storable
4620 last_op_in_netorder()