2 * Store and retrieve mechanism.
6 * $Id: Storable.xs,v 1.0.1.6 2001/01/03 09:40:40 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.1.6 2001/01/03 09:40:40 ram
15 * patch7: prototype and casting cleanup
16 * patch7: trace offending package when overloading cannot be restored
17 * patch7: made context cleanup safer to avoid dup freeing
19 * Revision 1.0.1.5 2000/11/05 17:21:24 ram
20 * patch6: fixed severe "object lost" bug for STORABLE_freeze returns
22 * Revision 1.0.1.4 2000/10/26 17:11:04 ram
23 * patch5: auto requires module of blessed ref when STORABLE_thaw misses
25 * Revision 1.0.1.3 2000/09/29 19:49:57 ram
26 * patch3: avoid using "tainted" and "dirty" since Perl remaps them via cpp
28 * $Log: Storable.xs,v $
29 * Revision 1.0 2000/09/01 19:40:41 ram
30 * Baseline for first official release.
36 #include <patchlevel.h> /* Perl's one, needed since 5.6 */
40 #define DEBUGME /* Debug mode, turns assertions on as well */
41 #define DASSERT /* Assertion mode */
45 * Pre PerlIO time when none of USE_PERLIO and PERLIO_IS_STDIO is defined
46 * Provide them with the necessary defines so they can build with pre-5.004.
49 #ifndef PERLIO_IS_STDIO
51 #define PerlIO_getc(x) getc(x)
52 #define PerlIO_putc(f,x) putc(x,f)
53 #define PerlIO_read(x,y,z) fread(y,1,z,x)
54 #define PerlIO_write(x,y,z) fwrite(y,1,z,x)
55 #define PerlIO_stdoutf printf
56 #endif /* PERLIO_IS_STDIO */
57 #endif /* USE_PERLIO */
60 * Earlier versions of perl might be used, we can't assume they have the latest!
63 #ifndef PERL_VERSION /* For perls < 5.6 */
64 #define PERL_VERSION PATCHLEVEL
66 #define newRV_noinc(sv) ((Sv = newRV(sv)), --SvREFCNT(SvRV(Sv)), Sv)
68 #if (PATCHLEVEL <= 4) /* Older perls (<= 5.004) lack PL_ namespace */
69 #define PL_sv_yes sv_yes
70 #define PL_sv_no sv_no
71 #define PL_sv_undef sv_undef
72 #if (SUBVERSION <= 4) /* 5.004_04 has been reported to lack newSVpvn */
73 #define newSVpvn newSVpv
75 #endif /* PATCHLEVEL <= 4 */
76 #ifndef HvSHAREKEYS_off
77 #define HvSHAREKEYS_off(hv) /* Ignore */
79 #ifndef AvFILLp /* Older perls (<=5.003) lack AvFILLp */
80 #define AvFILLp AvFILL
82 typedef double NV; /* Older perls lack the NV type */
83 #define IVdf "ld" /* Various printf formats for Perl types */
87 #define INT2PTR(t,v) (t)(IV)(v)
88 #define PTR2UV(v) (unsigned long)(v)
89 #endif /* PERL_VERSION -- perls < 5.6 */
91 #ifndef NVef /* The following were not part of perl 5.6 */
92 #if defined(USE_LONG_DOUBLE) && \
93 defined(HAS_LONG_DOUBLE) && defined(PERL_PRIfldbl)
94 #define NVef PERL_PRIeldbl
95 #define NVff PERL_PRIfldbl
96 #define NVgf PERL_PRIgldbl
106 * TRACEME() will only output things when the $Storable::DEBUGME is true.
109 #define TRACEME(x) do { \
110 if (SvTRUE(perl_get_sv("Storable::DEBUGME", TRUE))) \
111 { PerlIO_stdoutf x; PerlIO_stdoutf("\n"); } \
121 #define ASSERT(x,y) do { \
123 PerlIO_stdoutf("ASSERT FAILED (\"%s\", line %d): ", \
124 __FILE__, __LINE__); \
125 PerlIO_stdoutf y; PerlIO_stdoutf("\n"); \
136 #define C(x) ((char) (x)) /* For markers with dynamic retrieval handling */
138 #define SX_OBJECT C(0) /* Already stored object */
139 #define SX_LSCALAR C(1) /* Scalar (large binary) follows (length, data) */
140 #define SX_ARRAY C(2) /* Array forthcominng (size, item list) */
141 #define SX_HASH C(3) /* Hash forthcoming (size, key/value pair list) */
142 #define SX_REF C(4) /* Reference to object forthcoming */
143 #define SX_UNDEF C(5) /* Undefined scalar */
144 #define SX_INTEGER C(6) /* Integer forthcoming */
145 #define SX_DOUBLE C(7) /* Double forthcoming */
146 #define SX_BYTE C(8) /* (signed) byte forthcoming */
147 #define SX_NETINT C(9) /* Integer in network order forthcoming */
148 #define SX_SCALAR C(10) /* Scalar (binary, small) follows (length, data) */
149 #define SX_TIED_ARRAY C(11) /* Tied array forthcoming */
150 #define SX_TIED_HASH C(12) /* Tied hash forthcoming */
151 #define SX_TIED_SCALAR C(13) /* Tied scalar forthcoming */
152 #define SX_SV_UNDEF C(14) /* Perl's immortal PL_sv_undef */
153 #define SX_SV_YES C(15) /* Perl's immortal PL_sv_yes */
154 #define SX_SV_NO C(16) /* Perl's immortal PL_sv_no */
155 #define SX_BLESS C(17) /* Object is blessed */
156 #define SX_IX_BLESS C(18) /* Object is blessed, classname given by index */
157 #define SX_HOOK C(19) /* Stored via hook, user-defined */
158 #define SX_OVERLOAD C(20) /* Overloaded reference */
159 #define SX_TIED_KEY C(21) /* Tied magic key forthcoming */
160 #define SX_TIED_IDX C(22) /* Tied magic index forthcoming */
161 #define SX_UTF8STR C(23) /* UTF-8 string forthcoming (small) */
162 #define SX_LUTF8STR C(24) /* UTF-8 string forthcoming (large) */
163 #define SX_ERROR C(25) /* Error */
166 * Those are only used to retrieve "old" pre-0.6 binary images.
168 #define SX_ITEM 'i' /* An array item introducer */
169 #define SX_IT_UNDEF 'I' /* Undefined array item */
170 #define SX_KEY 'k' /* An hash key introducer */
171 #define SX_VALUE 'v' /* An hash value introducer */
172 #define SX_VL_UNDEF 'V' /* Undefined hash value */
175 * Those are only used to retrieve "old" pre-0.7 binary images
178 #define SX_CLASS 'b' /* Object is blessed, class name length <255 */
179 #define SX_LG_CLASS 'B' /* Object is blessed, class name length >255 */
180 #define SX_STORED 'X' /* End of object */
183 * Limits between short/long length representation.
186 #define LG_SCALAR 255 /* Large scalar length limit */
187 #define LG_BLESS 127 /* Large classname bless limit */
193 #define ST_STORE 0x1 /* Store operation */
194 #define ST_RETRIEVE 0x2 /* Retrieval operation */
195 #define ST_CLONE 0x4 /* Deep cloning operation */
198 * The following structure is used for hash table key retrieval. Since, when
199 * retrieving objects, we'll be facing blessed hash references, it's best
200 * to pre-allocate that buffer once and resize it as the need arises, never
201 * freeing it (keys will be saved away someplace else anyway, so even large
202 * keys are not enough a motivation to reclaim that space).
204 * This structure is also used for memory store/retrieve operations which
205 * happen in a fixed place before being malloc'ed elsewhere if persistency
206 * is required. Hence the aptr pointer.
209 char *arena; /* Will hold hash key strings, resized as needed */
210 STRLEN asiz; /* Size of aforementionned buffer */
211 char *aptr; /* Arena pointer, for in-place read/write ops */
212 char *aend; /* First invalid address */
217 * An hash table records the objects which have already been stored.
218 * Those are referred to as SX_OBJECT in the file, and their "tag" (i.e.
219 * an arbitrary sequence number) is used to identify them.
222 * An array table records the objects which have already been retrieved,
223 * as seen by the tag determind by counting the objects themselves. The
224 * reference to that retrieved object is kept in the table, and is returned
225 * when an SX_OBJECT is found bearing that same tag.
227 * The same processing is used to record "classname" for blessed objects:
228 * indexing by a hash at store time, and via an array at retrieve time.
231 typedef unsigned long stag_t; /* Used by pre-0.6 binary format */
234 * The following "thread-safe" related defines were contributed by
235 * Murray Nesbitt <murray@activestate.com> and integrated by RAM, who
236 * only renamed things a little bit to ensure consistency with surrounding
237 * code. -- RAM, 14/09/1999
239 * The original patch suffered from the fact that the stcxt_t structure
240 * was global. Murray tried to minimize the impact on the code as much as
243 * Starting with 0.7, Storable can be re-entrant, via the STORABLE_xxx hooks
244 * on objects. Therefore, the notion of context needs to be generalized,
248 #define MY_VERSION "Storable(" XS_VERSION ")"
251 * Fields s_tainted and s_dirty are prefixed with s_ because Perl's include
252 * files remap tainted and dirty when threading is enabled. That's bad for
253 * perl to remap such common words. -- RAM, 29/09/00
256 typedef struct stcxt {
257 int entry; /* flags recursion */
258 int optype; /* type of traversal operation */
259 HV *hseen; /* which objects have been seen, store time */
260 AV *hook_seen; /* which SVs were returned by STORABLE_freeze() */
261 AV *aseen; /* which objects have been seen, retrieve time */
262 HV *hclass; /* which classnames have been seen, store time */
263 AV *aclass; /* which classnames have been seen, retrieve time */
264 HV *hook; /* cache for hook methods per class name */
265 I32 tagnum; /* incremented at store time for each seen object */
266 I32 classnum; /* incremented at store time for each seen classname */
267 int netorder; /* true if network order used */
268 int s_tainted; /* true if input source is tainted, at retrieve time */
269 int forgive_me; /* whether to be forgiving... */
270 int canonical; /* whether to store hashes sorted by key */
271 int s_dirty; /* context is dirty due to CROAK() -- can be cleaned */
272 struct extendable keybuf; /* for hash key retrieval */
273 struct extendable membuf; /* for memory store/retrieve operations */
274 PerlIO *fio; /* where I/O are performed, NULL for memory */
275 int ver_major; /* major of version for retrieved object */
276 int ver_minor; /* minor of version for retrieved object */
277 SV *(**retrieve_vtbl)(); /* retrieve dispatch table */
278 struct stcxt *prev; /* contexts chained backwards in real recursion */
281 #if defined(MULTIPLICITY) || defined(PERL_OBJECT) || defined(PERL_CAPI)
283 #if (PATCHLEVEL <= 4) && (SUBVERSION < 68)
285 SV *perinterp_sv = perl_get_sv(MY_VERSION, FALSE)
286 #else /* >= perl5.004_68 */
288 SV *perinterp_sv = *hv_fetch(PL_modglobal, \
289 MY_VERSION, sizeof(MY_VERSION)-1, TRUE)
290 #endif /* < perl5.004_68 */
292 #define dSTCXT_PTR(T,name) \
293 T name = (perinterp_sv && SvIOK(perinterp_sv) \
294 ? INT2PTR(T, SvIVX(perinterp_sv)) : (T) 0)
297 dSTCXT_PTR(stcxt_t *, cxt)
301 Newz(0, cxt, 1, stcxt_t); \
302 sv_setiv(perinterp_sv, PTR2IV(cxt))
304 #define SET_STCXT(x) do { \
306 sv_setiv(perinterp_sv, PTR2IV(x)); \
309 #else /* !MULTIPLICITY && !PERL_OBJECT && !PERL_CAPI */
311 static stcxt_t Context;
312 static stcxt_t *Context_ptr = &Context;
313 #define dSTCXT stcxt_t *cxt = Context_ptr
314 #define INIT_STCXT dSTCXT
315 #define SET_STCXT(x) Context_ptr = x
317 #endif /* MULTIPLICITY || PERL_OBJECT || PERL_CAPI */
321 * Croaking implies a memory leak, since we don't use setjmp/longjmp
322 * to catch the exit and free memory used during store or retrieve
323 * operations. This is not too difficult to fix, but I need to understand
324 * how Perl does it, and croaking is exceptional anyway, so I lack the
325 * motivation to do it.
327 * The current workaround is to mark the context as dirty when croaking,
328 * so that data structures can be freed whenever we renter Storable code
329 * (but only *then*: it's a workaround, not a fix).
331 * This is also imperfect, because we don't really know how far they trapped
332 * the croak(), and when we were recursing, we won't be able to clean anything
333 * but the topmost context stacked.
336 #define CROAK(x) do { cxt->s_dirty = 1; croak x; } while (0)
339 * End of "thread-safe" related definitions.
345 * Keep only the low 32 bits of a pointer (used for tags, which are not
350 #define LOW_32BITS(x) ((I32) (x))
352 #define LOW_32BITS(x) ((I32) ((unsigned long) (x) & 0xffffffffUL))
358 * Hack for Crays, where sizeof(I32) == 8, and which are big-endians.
359 * Used in the WLEN and RLEN macros.
363 #define oI(x) ((I32 *) ((char *) (x) + 4))
364 #define oS(x) ((x) - 4)
365 #define oC(x) (x = 0)
374 * key buffer handling
376 #define kbuf (cxt->keybuf).arena
377 #define ksiz (cxt->keybuf).asiz
378 #define KBUFINIT() do { \
380 TRACEME(("** allocating kbuf of 128 bytes")); \
381 New(10003, kbuf, 128, char); \
385 #define KBUFCHK(x) do { \
387 TRACEME(("** extending kbuf to %d bytes", x+1)); \
388 Renew(kbuf, x+1, char); \
394 * memory buffer handling
396 #define mbase (cxt->membuf).arena
397 #define msiz (cxt->membuf).asiz
398 #define mptr (cxt->membuf).aptr
399 #define mend (cxt->membuf).aend
401 #define MGROW (1 << 13)
402 #define MMASK (MGROW - 1)
404 #define round_mgrow(x) \
405 ((unsigned long) (((unsigned long) (x) + MMASK) & ~MMASK))
406 #define trunc_int(x) \
407 ((unsigned long) ((unsigned long) (x) & ~(sizeof(int)-1)))
408 #define int_aligned(x) \
409 ((unsigned long) (x) == trunc_int(x))
411 #define MBUF_INIT(x) do { \
413 TRACEME(("** allocating mbase of %d bytes", MGROW)); \
414 New(10003, mbase, MGROW, char); \
421 mend = mbase + msiz; \
424 #define MBUF_TRUNC(x) mptr = mbase + x
425 #define MBUF_SIZE() (mptr - mbase)
428 * Use SvPOKp(), because SvPOK() fails on tainted scalars.
429 * See store_scalar() for other usage of this workaround.
431 #define MBUF_LOAD(v) do { \
433 CROAK(("Not a scalar string")); \
434 mptr = mbase = SvPV(v, msiz); \
435 mend = mbase + msiz; \
438 #define MBUF_XTEND(x) do { \
439 int nsz = (int) round_mgrow((x)+msiz); \
440 int offset = mptr - mbase; \
441 TRACEME(("** extending mbase to %d bytes", nsz)); \
442 Renew(mbase, nsz, char); \
444 mptr = mbase + offset; \
445 mend = mbase + nsz; \
448 #define MBUF_CHK(x) do { \
449 if ((mptr + (x)) > mend) \
453 #define MBUF_GETC(x) do { \
455 x = (int) (unsigned char) *mptr++; \
461 #define MBUF_GETINT(x) do { \
463 if ((mptr + 4) <= mend) { \
464 memcpy(oI(&x), mptr, 4); \
470 #define MBUF_GETINT(x) do { \
471 if ((mptr + sizeof(int)) <= mend) { \
472 if (int_aligned(mptr)) \
475 memcpy(&x, mptr, sizeof(int)); \
476 mptr += sizeof(int); \
482 #define MBUF_READ(x,s) do { \
483 if ((mptr + (s)) <= mend) { \
484 memcpy(x, mptr, s); \
490 #define MBUF_SAFEREAD(x,s,z) do { \
491 if ((mptr + (s)) <= mend) { \
492 memcpy(x, mptr, s); \
500 #define MBUF_PUTC(c) do { \
502 *mptr++ = (char) c; \
505 *mptr++ = (char) c; \
510 #define MBUF_PUTINT(i) do { \
512 memcpy(mptr, oI(&i), 4); \
516 #define MBUF_PUTINT(i) do { \
517 MBUF_CHK(sizeof(int)); \
518 if (int_aligned(mptr)) \
521 memcpy(mptr, &i, sizeof(int)); \
522 mptr += sizeof(int); \
526 #define MBUF_WRITE(x,s) do { \
528 memcpy(mptr, x, s); \
533 * Possible return values for sv_type().
537 #define svis_SCALAR 1
541 #define svis_TIED_ITEM 5
548 #define SHF_TYPE_MASK 0x03
549 #define SHF_LARGE_CLASSLEN 0x04
550 #define SHF_LARGE_STRLEN 0x08
551 #define SHF_LARGE_LISTLEN 0x10
552 #define SHF_IDX_CLASSNAME 0x20
553 #define SHF_NEED_RECURSE 0x40
554 #define SHF_HAS_LIST 0x80
557 * Types for SX_HOOK (2 bits).
565 * Before 0.6, the magic string was "perl-store" (binary version number 0).
567 * Since 0.6 introduced many binary incompatibilities, the magic string has
568 * been changed to "pst0" to allow an old image to be properly retrieved by
569 * a newer Storable, but ensure a newer image cannot be retrieved with an
572 * At 0.7, objects are given the ability to serialize themselves, and the
573 * set of markers is extended, backward compatibility is not jeopardized,
574 * so the binary version number could have remained unchanged. To correctly
575 * spot errors if a file making use of 0.7-specific extensions is given to
576 * 0.6 for retrieval, the binary version was moved to "2". And I'm introducing
577 * a "minor" version, to better track this kind of evolution from now on.
580 static char old_magicstr[] = "perl-store"; /* Magic number before 0.6 */
581 static char magicstr[] = "pst0"; /* Used as a magic number */
583 #define STORABLE_BIN_MAJOR 2 /* Binary major "version" */
584 #define STORABLE_BIN_MINOR 3 /* Binary minor "version" */
587 * Useful store shortcuts...
590 #define PUTMARK(x) do { \
593 else if (PerlIO_putc(cxt->fio, x) == EOF) \
597 #define WRITE_I32(x) do { \
598 ASSERT(sizeof(x) == sizeof(I32), ("writing an I32")); \
601 else if (PerlIO_write(cxt->fio, oI(&x), oS(sizeof(x))) != oS(sizeof(x))) \
606 #define WLEN(x) do { \
607 if (cxt->netorder) { \
608 int y = (int) htonl(x); \
611 else if (PerlIO_write(cxt->fio,oI(&y),oS(sizeof(y))) != oS(sizeof(y))) \
616 else if (PerlIO_write(cxt->fio,oI(&x),oS(sizeof(x))) != oS(sizeof(x))) \
621 #define WLEN(x) WRITE_I32(x)
624 #define WRITE(x,y) do { \
627 else if (PerlIO_write(cxt->fio, x, y) != y) \
631 #define STORE_PV_LEN(pv, len, small, large) do { \
632 if (len <= LG_SCALAR) { \
633 unsigned char clen = (unsigned char) len; \
645 #define STORE_SCALAR(pv, len) STORE_PV_LEN(pv, len, SX_SCALAR, SX_LSCALAR)
648 * Conditional UTF8 support.
649 * On non-UTF8 perls, UTF8 strings are returned as normal strings.
653 #define STORE_UTF8STR(pv, len) STORE_PV_LEN(pv, len, SX_UTF8STR, SX_LUTF8STR)
656 #define STORE_UTF8STR(pv, len) CROAK(("panic: storing UTF8 in non-UTF8 perl"))
657 #define SvUTF8_on(sv) CROAK(("Cannot retrieve UTF8 data in non-UTF8 perl"))
661 * Store undef in arrays and hashes without recursing through store().
663 #define STORE_UNDEF() do { \
669 * Useful retrieve shortcuts...
673 (cxt->fio ? PerlIO_getc(cxt->fio) : (mptr >= mend ? EOF : (int) *mptr++))
675 #define GETMARK(x) do { \
678 else if ((int) (x = PerlIO_getc(cxt->fio)) == EOF) \
682 #define READ_I32(x) do { \
683 ASSERT(sizeof(x) == sizeof(I32), ("reading an I32")); \
687 else if (PerlIO_read(cxt->fio, oI(&x), oS(sizeof(x))) != oS(sizeof(x))) \
692 #define RLEN(x) do { \
696 else if (PerlIO_read(cxt->fio, oI(&x), oS(sizeof(x))) != oS(sizeof(x))) \
699 x = (int) ntohl(x); \
702 #define RLEN(x) READ_I32(x)
705 #define READ(x,y) do { \
708 else if (PerlIO_read(cxt->fio, x, y) != y) \
712 #define SAFEREAD(x,y,z) do { \
714 MBUF_SAFEREAD(x,y,z); \
715 else if (PerlIO_read(cxt->fio, x, y) != y) { \
722 * This macro is used at retrieve time, to remember where object 'y', bearing a
723 * given tag 'tagnum', has been retrieved. Next time we see an SX_OBJECT marker,
724 * we'll therefore know where it has been retrieved and will be able to
725 * share the same reference, as in the original stored memory image.
727 #define SEEN(y) do { \
730 if (av_store(cxt->aseen, cxt->tagnum++, SvREFCNT_inc(y)) == 0) \
732 TRACEME(("aseen(#%d) = 0x%"UVxf" (refcnt=%d)", cxt->tagnum-1, \
733 PTR2UV(y), SvREFCNT(y)-1)); \
737 * Bless `s' in `p', via a temporary reference, required by sv_bless().
739 #define BLESS(s,p) do { \
742 TRACEME(("blessing 0x%"UVxf" in %s", PTR2UV(s), (p))); \
743 stash = gv_stashpv((p), TRUE); \
744 ref = newRV_noinc(s); \
745 (void) sv_bless(ref, stash); \
751 static SV *retrieve();
754 * Dynamic dispatching table for SV store.
757 static int store_ref(stcxt_t *cxt, SV *sv);
758 static int store_scalar(stcxt_t *cxt, SV *sv);
759 static int store_array(stcxt_t *cxt, AV *av);
760 static int store_hash(stcxt_t *cxt, HV *hv);
761 static int store_tied(stcxt_t *cxt, SV *sv);
762 static int store_tied_item(stcxt_t *cxt, SV *sv);
763 static int store_other(stcxt_t *cxt, SV *sv);
764 static int store_blessed(stcxt_t *cxt, SV *sv, int type, HV *pkg);
766 static int (*sv_store[])(stcxt_t *cxt, SV *sv) = {
767 store_ref, /* svis_REF */
768 store_scalar, /* svis_SCALAR */
769 (int (*)(stcxt_t *cxt, SV *sv)) store_array, /* svis_ARRAY */
770 (int (*)(stcxt_t *cxt, SV *sv)) store_hash, /* svis_HASH */
771 store_tied, /* svis_TIED */
772 store_tied_item, /* svis_TIED_ITEM */
773 store_other, /* svis_OTHER */
776 #define SV_STORE(x) (*sv_store[x])
779 * Dynamic dispatching tables for SV retrieval.
782 static SV *retrieve_lscalar(stcxt_t *cxt);
783 static SV *retrieve_lutf8str(stcxt_t *cxt);
784 static SV *old_retrieve_array(stcxt_t *cxt);
785 static SV *old_retrieve_hash(stcxt_t *cxt);
786 static SV *retrieve_ref(stcxt_t *cxt);
787 static SV *retrieve_undef(stcxt_t *cxt);
788 static SV *retrieve_integer(stcxt_t *cxt);
789 static SV *retrieve_double(stcxt_t *cxt);
790 static SV *retrieve_byte(stcxt_t *cxt);
791 static SV *retrieve_netint(stcxt_t *cxt);
792 static SV *retrieve_scalar(stcxt_t *cxt);
793 static SV *retrieve_utf8str(stcxt_t *cxt);
794 static SV *retrieve_tied_array(stcxt_t *cxt);
795 static SV *retrieve_tied_hash(stcxt_t *cxt);
796 static SV *retrieve_tied_scalar(stcxt_t *cxt);
797 static SV *retrieve_other(stcxt_t *cxt);
799 static SV *(*sv_old_retrieve[])(stcxt_t *cxt) = {
800 0, /* SX_OBJECT -- entry unused dynamically */
801 retrieve_lscalar, /* SX_LSCALAR */
802 old_retrieve_array, /* SX_ARRAY -- for pre-0.6 binaries */
803 old_retrieve_hash, /* SX_HASH -- for pre-0.6 binaries */
804 retrieve_ref, /* SX_REF */
805 retrieve_undef, /* SX_UNDEF */
806 retrieve_integer, /* SX_INTEGER */
807 retrieve_double, /* SX_DOUBLE */
808 retrieve_byte, /* SX_BYTE */
809 retrieve_netint, /* SX_NETINT */
810 retrieve_scalar, /* SX_SCALAR */
811 retrieve_tied_array, /* SX_ARRAY */
812 retrieve_tied_hash, /* SX_HASH */
813 retrieve_tied_scalar, /* SX_SCALAR */
814 retrieve_other, /* SX_SV_UNDEF not supported */
815 retrieve_other, /* SX_SV_YES not supported */
816 retrieve_other, /* SX_SV_NO not supported */
817 retrieve_other, /* SX_BLESS not supported */
818 retrieve_other, /* SX_IX_BLESS not supported */
819 retrieve_other, /* SX_HOOK not supported */
820 retrieve_other, /* SX_OVERLOADED not supported */
821 retrieve_other, /* SX_TIED_KEY not supported */
822 retrieve_other, /* SX_TIED_IDX not supported */
823 retrieve_other, /* SX_UTF8STR not supported */
824 retrieve_other, /* SX_LUTF8STR not supported */
825 retrieve_other, /* SX_ERROR */
828 static SV *retrieve_array(stcxt_t *cxt);
829 static SV *retrieve_hash(stcxt_t *cxt);
830 static SV *retrieve_sv_undef(stcxt_t *cxt);
831 static SV *retrieve_sv_yes(stcxt_t *cxt);
832 static SV *retrieve_sv_no(stcxt_t *cxt);
833 static SV *retrieve_blessed(stcxt_t *cxt);
834 static SV *retrieve_idx_blessed(stcxt_t *cxt);
835 static SV *retrieve_hook(stcxt_t *cxt);
836 static SV *retrieve_overloaded(stcxt_t *cxt);
837 static SV *retrieve_tied_key(stcxt_t *cxt);
838 static SV *retrieve_tied_idx(stcxt_t *cxt);
840 static SV *(*sv_retrieve[])(stcxt_t *cxt) = {
841 0, /* SX_OBJECT -- entry unused dynamically */
842 retrieve_lscalar, /* SX_LSCALAR */
843 retrieve_array, /* SX_ARRAY */
844 retrieve_hash, /* SX_HASH */
845 retrieve_ref, /* SX_REF */
846 retrieve_undef, /* SX_UNDEF */
847 retrieve_integer, /* SX_INTEGER */
848 retrieve_double, /* SX_DOUBLE */
849 retrieve_byte, /* SX_BYTE */
850 retrieve_netint, /* SX_NETINT */
851 retrieve_scalar, /* SX_SCALAR */
852 retrieve_tied_array, /* SX_ARRAY */
853 retrieve_tied_hash, /* SX_HASH */
854 retrieve_tied_scalar, /* SX_SCALAR */
855 retrieve_sv_undef, /* SX_SV_UNDEF */
856 retrieve_sv_yes, /* SX_SV_YES */
857 retrieve_sv_no, /* SX_SV_NO */
858 retrieve_blessed, /* SX_BLESS */
859 retrieve_idx_blessed, /* SX_IX_BLESS */
860 retrieve_hook, /* SX_HOOK */
861 retrieve_overloaded, /* SX_OVERLOAD */
862 retrieve_tied_key, /* SX_TIED_KEY */
863 retrieve_tied_idx, /* SX_TIED_IDX */
864 retrieve_utf8str, /* SX_UTF8STR */
865 retrieve_lutf8str, /* SX_LUTF8STR */
866 retrieve_other, /* SX_ERROR */
869 #define RETRIEVE(c,x) (*(c)->retrieve_vtbl[(x) >= SX_ERROR ? SX_ERROR : (x)])
871 static SV *mbuf2sv(void);
874 *** Context management.
880 * Called once per "thread" (interpreter) to initialize some global context.
882 static void init_perinterp(void)
886 cxt->netorder = 0; /* true if network order used */
887 cxt->forgive_me = -1; /* whether to be forgiving... */
893 * Initialize a new store context for real recursion.
895 static void init_store_context(
901 TRACEME(("init_store_context"));
903 cxt->netorder = network_order;
904 cxt->forgive_me = -1; /* Fetched from perl if needed */
905 cxt->canonical = -1; /* Idem */
906 cxt->tagnum = -1; /* Reset tag numbers */
907 cxt->classnum = -1; /* Reset class numbers */
908 cxt->fio = f; /* Where I/O are performed */
909 cxt->optype = optype; /* A store, or a deep clone */
910 cxt->entry = 1; /* No recursion yet */
913 * The `hseen' table is used to keep track of each SV stored and their
914 * associated tag numbers is special. It is "abused" because the
915 * values stored are not real SV, just integers cast to (SV *),
916 * which explains the freeing below.
918 * It is also one possible bottlneck to achieve good storing speed,
919 * so the "shared keys" optimization is turned off (unlikely to be
920 * of any use here), and the hash table is "pre-extended". Together,
921 * those optimizations increase the throughput by 12%.
924 cxt->hseen = newHV(); /* Table where seen objects are stored */
925 HvSHAREKEYS_off(cxt->hseen);
928 * The following does not work well with perl5.004_04, and causes
929 * a core dump later on, in a completely unrelated spot, which
930 * makes me think there is a memory corruption going on.
932 * Calling hv_ksplit(hseen, HBUCKETS) instead of manually hacking
933 * it below does not make any difference. It seems to work fine
934 * with perl5.004_68 but given the probable nature of the bug,
935 * that does not prove anything.
937 * It's a shame because increasing the amount of buckets raises
938 * store() throughput by 5%, but until I figure this out, I can't
939 * allow for this to go into production.
941 * It is reported fixed in 5.005, hence the #if.
943 #if PERL_VERSION >= 5
944 #define HBUCKETS 4096 /* Buckets for %hseen */
945 HvMAX(cxt->hseen) = HBUCKETS - 1; /* keys %hseen = $HBUCKETS; */
949 * The `hclass' hash uses the same settings as `hseen' above, but it is
950 * used to assign sequential tags (numbers) to class names for blessed
953 * We turn the shared key optimization on.
956 cxt->hclass = newHV(); /* Where seen classnames are stored */
958 #if PERL_VERSION >= 5
959 HvMAX(cxt->hclass) = HBUCKETS - 1; /* keys %hclass = $HBUCKETS; */
963 * The `hook' hash table is used to keep track of the references on
964 * the STORABLE_freeze hook routines, when found in some class name.
966 * It is assumed that the inheritance tree will not be changed during
967 * storing, and that no new method will be dynamically created by the
971 cxt->hook = newHV(); /* Table where hooks are cached */
974 * The `hook_seen' array keeps track of all the SVs returned by
975 * STORABLE_freeze hooks for us to serialize, so that they are not
976 * reclaimed until the end of the serialization process. Each SV is
977 * only stored once, the first time it is seen.
980 cxt->hook_seen = newAV(); /* Lists SVs returned by STORABLE_freeze */
984 * clean_store_context
986 * Clean store context by
988 static void clean_store_context(stcxt_t *cxt)
992 TRACEME(("clean_store_context"));
994 ASSERT(cxt->optype & ST_STORE, ("was performing a store()"));
997 * Insert real values into hashes where we stored faked pointers.
1000 hv_iterinit(cxt->hseen);
1001 while (he = hv_iternext(cxt->hseen))
1002 HeVAL(he) = &PL_sv_undef;
1004 hv_iterinit(cxt->hclass);
1005 while (he = hv_iternext(cxt->hclass))
1006 HeVAL(he) = &PL_sv_undef;
1009 * And now dispose of them...
1011 * The surrounding if() protection has been added because there might be
1012 * some cases where this routine is called more than once, during
1013 * exceptionnal events. This was reported by Marc Lehmann when Storable
1014 * is executed from mod_perl, and the fix was suggested by him.
1015 * -- RAM, 20/12/2000
1019 HV *hseen = cxt->hseen;
1022 sv_free((SV *) hseen);
1026 HV *hclass = cxt->hclass;
1029 sv_free((SV *) hclass);
1033 HV *hook = cxt->hook;
1036 sv_free((SV *) hook);
1039 if (cxt->hook_seen) {
1040 AV *hook_seen = cxt->hook_seen;
1042 av_undef(hook_seen);
1043 sv_free((SV *) hook_seen);
1051 * init_retrieve_context
1053 * Initialize a new retrieve context for real recursion.
1055 static void init_retrieve_context(stcxt_t *cxt, int optype, int is_tainted)
1057 TRACEME(("init_retrieve_context"));
1060 * The hook hash table is used to keep track of the references on
1061 * the STORABLE_thaw hook routines, when found in some class name.
1063 * It is assumed that the inheritance tree will not be changed during
1064 * storing, and that no new method will be dynamically created by the
1068 cxt->hook = newHV(); /* Caches STORABLE_thaw */
1071 * If retrieving an old binary version, the cxt->retrieve_vtbl variable
1072 * was set to sv_old_retrieve. We'll need a hash table to keep track of
1073 * the correspondance between the tags and the tag number used by the
1074 * new retrieve routines.
1077 cxt->hseen = (cxt->retrieve_vtbl == sv_old_retrieve) ? newHV() : 0;
1079 cxt->aseen = newAV(); /* Where retrieved objects are kept */
1080 cxt->aclass = newAV(); /* Where seen classnames are kept */
1081 cxt->tagnum = 0; /* Have to count objects... */
1082 cxt->classnum = 0; /* ...and class names as well */
1083 cxt->optype = optype;
1084 cxt->s_tainted = is_tainted;
1085 cxt->entry = 1; /* No recursion yet */
1089 * clean_retrieve_context
1091 * Clean retrieve context by
1093 static void clean_retrieve_context(stcxt_t *cxt)
1095 TRACEME(("clean_retrieve_context"));
1097 ASSERT(cxt->optype & ST_RETRIEVE, ("was performing a retrieve()"));
1100 AV *aseen = cxt->aseen;
1103 sv_free((SV *) aseen);
1107 AV *aclass = cxt->aclass;
1110 sv_free((SV *) aclass);
1114 HV *hook = cxt->hook;
1117 sv_free((SV *) hook);
1121 HV *hseen = cxt->hseen;
1124 sv_free((SV *) hseen); /* optional HV, for backward compat. */
1134 * A workaround for the CROAK bug: cleanup the last context.
1136 static void clean_context(cxt)
1139 TRACEME(("clean_context"));
1141 ASSERT(cxt->s_dirty, ("dirty context"));
1143 if (cxt->optype & ST_RETRIEVE)
1144 clean_retrieve_context(cxt);
1146 clean_store_context(cxt);
1148 ASSERT(!cxt->s_dirty, ("context is clean"));
1154 * Allocate a new context and push it on top of the parent one.
1155 * This new context is made globally visible via SET_STCXT().
1157 static stcxt_t *allocate_context(parent_cxt)
1158 stcxt_t *parent_cxt;
1162 TRACEME(("allocate_context"));
1164 ASSERT(!parent_cxt->s_dirty, ("parent context clean"));
1166 Newz(0, cxt, 1, stcxt_t);
1167 cxt->prev = parent_cxt;
1176 * Free current context, which cannot be the "root" one.
1177 * Make the context underneath globally visible via SET_STCXT().
1179 static void free_context(cxt)
1182 stcxt_t *prev = cxt->prev;
1184 TRACEME(("free_context"));
1186 ASSERT(!cxt->s_dirty, ("clean context"));
1187 ASSERT(prev, ("not freeing root context"));
1205 * Tells whether we're in the middle of a store operation.
1207 int is_storing(void)
1211 return cxt->entry && (cxt->optype & ST_STORE);
1217 * Tells whether we're in the middle of a retrieve operation.
1219 int is_retrieving(void)
1223 return cxt->entry && (cxt->optype & ST_RETRIEVE);
1227 * last_op_in_netorder
1229 * Returns whether last operation was made using network order.
1231 * This is typically out-of-band information that might prove useful
1232 * to people wishing to convert native to network order data when used.
1234 int last_op_in_netorder(void)
1238 return cxt->netorder;
1242 *** Hook lookup and calling routines.
1248 * A wrapper on gv_fetchmethod_autoload() which caches results.
1250 * Returns the routine reference as an SV*, or null if neither the package
1251 * nor its ancestors know about the method.
1253 static SV *pkg_fetchmeth(
1263 * The following code is the same as the one performed by UNIVERSAL::can
1267 gv = gv_fetchmethod_autoload(pkg, method, FALSE);
1268 if (gv && isGV(gv)) {
1269 sv = newRV((SV*) GvCV(gv));
1270 TRACEME(("%s->%s: 0x%"UVxf, HvNAME(pkg), method, PTR2UV(sv)));
1272 sv = newSVsv(&PL_sv_undef);
1273 TRACEME(("%s->%s: not found", HvNAME(pkg), method));
1277 * Cache the result, ignoring failure: if we can't store the value,
1278 * it just won't be cached.
1281 (void) hv_store(cache, HvNAME(pkg), strlen(HvNAME(pkg)), sv, 0);
1283 return SvOK(sv) ? sv : (SV *) 0;
1289 * Force cached value to be undef: hook ignored even if present.
1291 static void pkg_hide(
1296 (void) hv_store(cache,
1297 HvNAME(pkg), strlen(HvNAME(pkg)), newSVsv(&PL_sv_undef), 0);
1303 * Discard cached value: a whole fetch loop will be retried at next lookup.
1305 static void pkg_uncache(
1310 (void) hv_delete(cache, HvNAME(pkg), strlen(HvNAME(pkg)), G_DISCARD);
1316 * Our own "UNIVERSAL::can", which caches results.
1318 * Returns the routine reference as an SV*, or null if the object does not
1319 * know about the method.
1329 TRACEME(("pkg_can for %s->%s", HvNAME(pkg), method));
1332 * Look into the cache to see whether we already have determined
1333 * where the routine was, if any.
1335 * NOTA BENE: we don't use `method' at all in our lookup, since we know
1336 * that only one hook (i.e. always the same) is cached in a given cache.
1339 svh = hv_fetch(cache, HvNAME(pkg), strlen(HvNAME(pkg)), FALSE);
1343 TRACEME(("cached %s->%s: not found", HvNAME(pkg), method));
1346 TRACEME(("cached %s->%s: 0x%"UVxf,
1347 HvNAME(pkg), method, PTR2UV(sv)));
1352 TRACEME(("not cached yet"));
1353 return pkg_fetchmeth(cache, pkg, method); /* Fetch and cache */
1359 * Call routine as obj->hook(av) in scalar context.
1360 * Propagates the single returned value if not called in void context.
1362 static SV *scalar_call(
1373 TRACEME(("scalar_call (cloning=%d)", cloning));
1380 XPUSHs(sv_2mortal(newSViv(cloning))); /* Cloning flag */
1382 SV **ary = AvARRAY(av);
1383 int cnt = AvFILLp(av) + 1;
1385 XPUSHs(ary[0]); /* Frozen string */
1386 for (i = 1; i < cnt; i++) {
1387 TRACEME(("pushing arg #%d (0x%"UVxf")...",
1388 i, PTR2UV(ary[i])));
1389 XPUSHs(sv_2mortal(newRV(ary[i])));
1394 TRACEME(("calling..."));
1395 count = perl_call_sv(hook, flags); /* Go back to Perl code */
1396 TRACEME(("count = %d", count));
1402 SvREFCNT_inc(sv); /* We're returning it, must stay alive! */
1415 * Call routine obj->hook(cloning) in list context.
1416 * Returns the list of returned values in an array.
1418 static AV *array_call(
1428 TRACEME(("array_call (cloning=%d)", cloning));
1434 XPUSHs(obj); /* Target object */
1435 XPUSHs(sv_2mortal(newSViv(cloning))); /* Cloning flag */
1438 count = perl_call_sv(hook, G_ARRAY); /* Go back to Perl code */
1443 for (i = count - 1; i >= 0; i--) {
1445 av_store(av, i, SvREFCNT_inc(sv));
1458 * Lookup the class name in the `hclass' table and either assign it a new ID
1459 * or return the existing one, by filling in `classnum'.
1461 * Return true if the class was known, false if the ID was just generated.
1463 static int known_class(
1465 char *name, /* Class name */
1466 int len, /* Name length */
1470 HV *hclass = cxt->hclass;
1472 TRACEME(("known_class (%s)", name));
1475 * Recall that we don't store pointers in this hash table, but tags.
1476 * Therefore, we need LOW_32BITS() to extract the relevant parts.
1479 svh = hv_fetch(hclass, name, len, FALSE);
1481 *classnum = LOW_32BITS(*svh);
1486 * Unknown classname, we need to record it.
1490 if (!hv_store(hclass, name, len, INT2PTR(SV*, cxt->classnum), 0))
1491 CROAK(("Unable to record new classname"));
1493 *classnum = cxt->classnum;
1498 *** Sepcific store routines.
1504 * Store a reference.
1505 * Layout is SX_REF <object> or SX_OVERLOAD <object>.
1507 static int store_ref(stcxt_t *cxt, SV *sv)
1509 TRACEME(("store_ref (0x%"UVxf")", PTR2UV(sv)));
1512 * Follow reference, and check if target is overloaded.
1518 HV *stash = (HV *) SvSTASH(sv);
1519 if (stash && Gv_AMG(stash)) {
1520 TRACEME(("ref (0x%"UVxf") is overloaded", PTR2UV(sv)));
1521 PUTMARK(SX_OVERLOAD);
1527 return store(cxt, sv);
1535 * Layout is SX_LSCALAR <length> <data>, SX_SCALAR <lenght> <data> or SX_UNDEF.
1536 * The <data> section is omitted if <length> is 0.
1538 * If integer or double, the layout is SX_INTEGER <data> or SX_DOUBLE <data>.
1539 * Small integers (within [-127, +127]) are stored as SX_BYTE <byte>.
1541 static int store_scalar(stcxt_t *cxt, SV *sv)
1546 U32 flags = SvFLAGS(sv); /* "cc -O" may put it in register */
1548 TRACEME(("store_scalar (0x%"UVxf")", PTR2UV(sv)));
1551 * For efficiency, break the SV encapsulation by peaking at the flags
1552 * directly without using the Perl macros to avoid dereferencing
1553 * sv->sv_flags each time we wish to check the flags.
1556 if (!(flags & SVf_OK)) { /* !SvOK(sv) */
1557 if (sv == &PL_sv_undef) {
1558 TRACEME(("immortal undef"));
1559 PUTMARK(SX_SV_UNDEF);
1561 TRACEME(("undef at 0x%"UVxf, PTR2UV(sv)));
1568 * Always store the string representation of a scalar if it exists.
1569 * Gisle Aas provided me with this test case, better than a long speach:
1571 * perl -MDevel::Peek -le '$a="abc"; $a+0; Dump($a)'
1572 * SV = PVNV(0x80c8520)
1574 * FLAGS = (NOK,POK,pNOK,pPOK)
1577 * PV = 0x80c83d0 "abc"\0
1581 * Write SX_SCALAR, length, followed by the actual data.
1583 * Otherwise, write an SX_BYTE, SX_INTEGER or an SX_DOUBLE as
1584 * appropriate, followed by the actual (binary) data. A double
1585 * is written as a string if network order, for portability.
1587 * NOTE: instead of using SvNOK(sv), we test for SvNOKp(sv).
1588 * The reason is that when the scalar value is tainted, the SvNOK(sv)
1591 * The test for a read-only scalar with both POK and NOK set is meant
1592 * to quickly detect &PL_sv_yes and &PL_sv_no without having to pay the
1593 * address comparison for each scalar we store.
1596 #define SV_MAYBE_IMMORTAL (SVf_READONLY|SVf_POK|SVf_NOK)
1598 if ((flags & SV_MAYBE_IMMORTAL) == SV_MAYBE_IMMORTAL) {
1599 if (sv == &PL_sv_yes) {
1600 TRACEME(("immortal yes"));
1602 } else if (sv == &PL_sv_no) {
1603 TRACEME(("immortal no"));
1606 pv = SvPV(sv, len); /* We know it's SvPOK */
1607 goto string; /* Share code below */
1609 } else if (flags & SVp_POK) { /* SvPOKp(sv) => string */
1610 I32 wlen; /* For 64-bit machines */
1614 * Will come here from below with pv and len set if double & netorder,
1615 * or from above if it was readonly, POK and NOK but neither &PL_sv_yes
1620 wlen = (I32) len; /* WLEN via STORE_SCALAR expects I32 */
1622 STORE_UTF8STR(pv, wlen);
1624 STORE_SCALAR(pv, wlen);
1625 TRACEME(("ok (scalar 0x%"UVxf" '%s', length = %"IVdf")",
1626 PTR2UV(sv), SvPVX(sv), (IV)len));
1628 } else if (flags & SVp_NOK) { /* SvNOKp(sv) => double */
1632 * Watch for number being an integer in disguise.
1634 if (nv == (NV) (iv = I_V(nv))) {
1635 TRACEME(("double %"NVff" is actually integer %"IVdf, nv, iv));
1636 goto integer; /* Share code below */
1639 if (cxt->netorder) {
1640 TRACEME(("double %"NVff" stored as string", nv));
1642 goto string; /* Share code above */
1646 WRITE(&nv, sizeof(nv));
1648 TRACEME(("ok (double 0x%"UVxf", value = %"NVff")", PTR2UV(sv), nv));
1650 } else if (flags & SVp_IOK) { /* SvIOKp(sv) => integer */
1654 * Will come here from above with iv set if double is an integer.
1659 * Optimize small integers into a single byte, otherwise store as
1660 * a real integer (converted into network order if they asked).
1663 if (iv >= -128 && iv <= 127) {
1664 unsigned char siv = (unsigned char) (iv + 128); /* [0,255] */
1667 TRACEME(("small integer stored as %d", siv));
1668 } else if (cxt->netorder) {
1671 niv = (I32) htonl(iv);
1672 TRACEME(("using network order"));
1675 TRACEME(("as-is for network order"));
1680 PUTMARK(SX_INTEGER);
1681 WRITE(&iv, sizeof(iv));
1684 TRACEME(("ok (integer 0x%"UVxf", value = %"IVdf")", PTR2UV(sv), iv));
1687 CROAK(("Can't determine type of %s(0x%"UVxf")",
1688 sv_reftype(sv, FALSE),
1691 return 0; /* Ok, no recursion on scalars */
1699 * Layout is SX_ARRAY <size> followed by each item, in increading index order.
1700 * Each item is stored as <object>.
1702 static int store_array(stcxt_t *cxt, AV *av)
1705 I32 len = av_len(av) + 1;
1709 TRACEME(("store_array (0x%"UVxf")", PTR2UV(av)));
1712 * Signal array by emitting SX_ARRAY, followed by the array length.
1717 TRACEME(("size = %d", len));
1720 * Now store each item recursively.
1723 for (i = 0; i < len; i++) {
1724 sav = av_fetch(av, i, 0);
1726 TRACEME(("(#%d) undef item", i));
1730 TRACEME(("(#%d) item", i));
1731 if (ret = store(cxt, *sav))
1735 TRACEME(("ok (array)"));
1744 * Borrowed from perl source file pp_ctl.c, where it is used by pp_sort.
1747 sortcmp(const void *a, const void *b)
1749 return sv_cmp(*(SV * const *) a, *(SV * const *) b);
1756 * Store an hash table.
1758 * Layout is SX_HASH <size> followed by each key/value pair, in random order.
1759 * Values are stored as <object>.
1760 * Keys are stored as <length> <data>, the <data> section being omitted
1763 static int store_hash(stcxt_t *cxt, HV *hv)
1765 I32 len = HvKEYS(hv);
1771 TRACEME(("store_hash (0x%"UVxf")", PTR2UV(hv)));
1774 * Signal hash by emitting SX_HASH, followed by the table length.
1779 TRACEME(("size = %d", len));
1782 * Save possible iteration state via each() on that table.
1785 riter = HvRITER(hv);
1786 eiter = HvEITER(hv);
1790 * Now store each item recursively.
1792 * If canonical is defined to some true value then store each
1793 * key/value pair in sorted order otherwise the order is random.
1794 * Canonical order is irrelevant when a deep clone operation is performed.
1796 * Fetch the value from perl only once per store() operation, and only
1801 !(cxt->optype & ST_CLONE) && (cxt->canonical == 1 ||
1802 (cxt->canonical < 0 && (cxt->canonical =
1803 SvTRUE(perl_get_sv("Storable::canonical", TRUE)) ? 1 : 0)))
1806 * Storing in order, sorted by key.
1807 * Run through the hash, building up an array of keys in a
1808 * mortal array, sort the array and then run through the
1814 TRACEME(("using canonical order"));
1816 for (i = 0; i < len; i++) {
1817 HE *he = hv_iternext(hv);
1818 SV *key = hv_iterkeysv(he);
1819 av_store(av, AvFILLp(av)+1, key); /* av_push(), really */
1822 qsort((char *) AvARRAY(av), len, sizeof(SV *), sortcmp);
1824 for (i = 0; i < len; i++) {
1827 SV *key = av_shift(av);
1828 HE *he = hv_fetch_ent(hv, key, 0, 0);
1829 SV *val = HeVAL(he);
1831 return 1; /* Internal error, not I/O error */
1834 * Store value first.
1837 TRACEME(("(#%d) value 0x%"UVxf, i, PTR2UV(val)));
1839 if (ret = store(cxt, val))
1844 * Keys are written after values to make sure retrieval
1845 * can be optimal in terms of memory usage, where keys are
1846 * read into a fixed unique buffer called kbuf.
1847 * See retrieve_hash() for details.
1850 keyval = hv_iterkey(he, &keylen);
1851 TRACEME(("(#%d) key '%s'", i, keyval));
1854 WRITE(keyval, keylen);
1858 * Free up the temporary array
1867 * Storing in "random" order (in the order the keys are stored
1868 * within the the hash). This is the default and will be faster!
1871 for (i = 0; i < len; i++) {
1874 SV *val = hv_iternextsv(hv, &key, &len);
1877 return 1; /* Internal error, not I/O error */
1880 * Store value first.
1883 TRACEME(("(#%d) value 0x%"UVxf, i, PTR2UV(val)));
1885 if (ret = store(cxt, val))
1890 * Keys are written after values to make sure retrieval
1891 * can be optimal in terms of memory usage, where keys are
1892 * read into a fixed unique buffer called kbuf.
1893 * See retrieve_hash() for details.
1896 TRACEME(("(#%d) key '%s'", i, key));
1903 TRACEME(("ok (hash 0x%"UVxf")", PTR2UV(hv)));
1906 HvRITER(hv) = riter; /* Restore hash iterator state */
1907 HvEITER(hv) = eiter;
1915 * When storing a tied object (be it a tied scalar, array or hash), we lay out
1916 * a special mark, followed by the underlying tied object. For instance, when
1917 * dealing with a tied hash, we store SX_TIED_HASH <hash object>, where
1918 * <hash object> stands for the serialization of the tied hash.
1920 static int store_tied(stcxt_t *cxt, SV *sv)
1924 int svt = SvTYPE(sv);
1927 TRACEME(("store_tied (0x%"UVxf")", PTR2UV(sv)));
1930 * We have a small run-time penalty here because we chose to factorise
1931 * all tieds objects into the same routine, and not have a store_tied_hash,
1932 * a store_tied_array, etc...
1934 * Don't use a switch() statement, as most compilers don't optimize that
1935 * well for 2/3 values. An if() else if() cascade is just fine. We put
1936 * tied hashes first, as they are the most likely beasts.
1939 if (svt == SVt_PVHV) {
1940 TRACEME(("tied hash"));
1941 PUTMARK(SX_TIED_HASH); /* Introduces tied hash */
1942 } else if (svt == SVt_PVAV) {
1943 TRACEME(("tied array"));
1944 PUTMARK(SX_TIED_ARRAY); /* Introduces tied array */
1946 TRACEME(("tied scalar"));
1947 PUTMARK(SX_TIED_SCALAR); /* Introduces tied scalar */
1951 if (!(mg = mg_find(sv, mtype)))
1952 CROAK(("No magic '%c' found while storing tied %s", mtype,
1953 (svt == SVt_PVHV) ? "hash" :
1954 (svt == SVt_PVAV) ? "array" : "scalar"));
1957 * The mg->mg_obj found by mg_find() above actually points to the
1958 * underlying tied Perl object implementation. For instance, if the
1959 * original SV was that of a tied array, then mg->mg_obj is an AV.
1961 * Note that we store the Perl object as-is. We don't call its FETCH
1962 * method along the way. At retrieval time, we won't call its STORE
1963 * method either, but the tieing magic will be re-installed. In itself,
1964 * that ensures that the tieing semantics are preserved since futher
1965 * accesses on the retrieved object will indeed call the magic methods...
1968 if (ret = store(cxt, mg->mg_obj))
1971 TRACEME(("ok (tied)"));
1979 * Stores a reference to an item within a tied structure:
1981 * . \$h{key}, stores both the (tied %h) object and 'key'.
1982 * . \$a[idx], stores both the (tied @a) object and 'idx'.
1984 * Layout is therefore either:
1985 * SX_TIED_KEY <object> <key>
1986 * SX_TIED_IDX <object> <index>
1988 static int store_tied_item(stcxt_t *cxt, SV *sv)
1993 TRACEME(("store_tied_item (0x%"UVxf")", PTR2UV(sv)));
1995 if (!(mg = mg_find(sv, 'p')))
1996 CROAK(("No magic 'p' found while storing reference to tied item"));
1999 * We discriminate between \$h{key} and \$a[idx] via mg_ptr.
2003 TRACEME(("store_tied_item: storing a ref to a tied hash item"));
2004 PUTMARK(SX_TIED_KEY);
2005 TRACEME(("store_tied_item: storing OBJ 0x%"UVxf, PTR2UV(mg->mg_obj)));
2007 if (ret = store(cxt, mg->mg_obj))
2010 TRACEME(("store_tied_item: storing PTR 0x%"UVxf, PTR2UV(mg->mg_ptr)));
2012 if (ret = store(cxt, (SV *) mg->mg_ptr))
2015 I32 idx = mg->mg_len;
2017 TRACEME(("store_tied_item: storing a ref to a tied array item "));
2018 PUTMARK(SX_TIED_IDX);
2019 TRACEME(("store_tied_item: storing OBJ 0x%"UVxf, PTR2UV(mg->mg_obj)));
2021 if (ret = store(cxt, mg->mg_obj))
2024 TRACEME(("store_tied_item: storing IDX %d", idx));
2029 TRACEME(("ok (tied item)"));
2035 * store_hook -- dispatched manually, not via sv_store[]
2037 * The blessed SV is serialized by a hook.
2041 * SX_HOOK <flags> <len> <classname> <len2> <str> [<len3> <object-IDs>]
2043 * where <flags> indicates how long <len>, <len2> and <len3> are, whether
2044 * the trailing part [] is present, the type of object (scalar, array or hash).
2045 * There is also a bit which says how the classname is stored between:
2050 * and when the <index> form is used (classname already seen), the "large
2051 * classname" bit in <flags> indicates how large the <index> is.
2053 * The serialized string returned by the hook is of length <len2> and comes
2054 * next. It is an opaque string for us.
2056 * Those <len3> object IDs which are listed last represent the extra references
2057 * not directly serialized by the hook, but which are linked to the object.
2059 * When recursion is mandated to resolve object-IDs not yet seen, we have
2060 * instead, with <header> being flags with bits set to indicate the object type
2061 * and that recursion was indeed needed:
2063 * SX_HOOK <header> <object> <header> <object> <flags>
2065 * that same header being repeated between serialized objects obtained through
2066 * recursion, until we reach flags indicating no recursion, at which point
2067 * we know we've resynchronized with a single layout, after <flags>.
2069 static int store_hook(
2082 int count; /* really len3 + 1 */
2083 unsigned char flags;
2086 int recursed = 0; /* counts recursion */
2087 int obj_type; /* object type, on 2 bits */
2090 int clone = cxt->optype & ST_CLONE;
2092 TRACEME(("store_hook, class \"%s\", tagged #%d", HvNAME(pkg), cxt->tagnum));
2095 * Determine object type on 2 bits.
2100 obj_type = SHT_SCALAR;
2103 obj_type = SHT_ARRAY;
2106 obj_type = SHT_HASH;
2109 CROAK(("Unexpected object type (%d) in store_hook()", type));
2111 flags = SHF_NEED_RECURSE | obj_type;
2113 class = HvNAME(pkg);
2114 len = strlen(class);
2117 * To call the hook, we need to fake a call like:
2119 * $object->STORABLE_freeze($cloning);
2121 * but we don't have the $object here. For instance, if $object is
2122 * a blessed array, what we have in `sv' is the array, and we can't
2123 * call a method on those.
2125 * Therefore, we need to create a temporary reference to the object and
2126 * make the call on that reference.
2129 TRACEME(("about to call STORABLE_freeze on class %s", class));
2131 ref = newRV_noinc(sv); /* Temporary reference */
2132 av = array_call(ref, hook, clone); /* @a = $object->STORABLE_freeze($c) */
2134 SvREFCNT_dec(ref); /* Reclaim temporary reference */
2136 count = AvFILLp(av) + 1;
2137 TRACEME(("store_hook, array holds %d items", count));
2140 * If they return an empty list, it means they wish to ignore the
2141 * hook for this class (and not just this instance -- that's for them
2142 * to handle if they so wish).
2144 * Simply disable the cached entry for the hook (it won't be recomputed
2145 * since it's present in the cache) and recurse to store_blessed().
2150 * They must not change their mind in the middle of a serialization.
2153 if (hv_fetch(cxt->hclass, class, len, FALSE))
2154 CROAK(("Too late to ignore hooks for %s class \"%s\"",
2155 (cxt->optype & ST_CLONE) ? "cloning" : "storing", class));
2157 pkg_hide(cxt->hook, pkg, "STORABLE_freeze");
2159 ASSERT(!pkg_can(cxt->hook, pkg, "STORABLE_freeze"), ("hook invisible"));
2160 TRACEME(("ignoring STORABLE_freeze in class \"%s\"", class));
2162 return store_blessed(cxt, sv, type, pkg);
2166 * Get frozen string.
2170 pv = SvPV(ary[0], len2);
2173 * If they returned more than one item, we need to serialize some
2174 * extra references if not already done.
2176 * Loop over the array, starting at postion #1, and for each item,
2177 * ensure it is a reference, serialize it if not already done, and
2178 * replace the entry with the tag ID of the corresponding serialized
2181 * We CHEAT by not calling av_fetch() and read directly within the
2185 for (i = 1; i < count; i++) {
2189 AV *av_hook = cxt->hook_seen;
2192 CROAK(("Item #%d returned by STORABLE_freeze "
2193 "for %s is not a reference", i, class));
2194 xsv = SvRV(rsv); /* Follow ref to know what to look for */
2197 * Look in hseen and see if we have a tag already.
2198 * Serialize entry if not done already, and get its tag.
2201 if (svh = hv_fetch(cxt->hseen, (char *) &xsv, sizeof(xsv), FALSE))
2202 goto sv_seen; /* Avoid moving code too far to the right */
2204 TRACEME(("listed object %d at 0x%"UVxf" is unknown", i-1, PTR2UV(xsv)));
2207 * We need to recurse to store that object and get it to be known
2208 * so that we can resolve the list of object-IDs at retrieve time.
2210 * The first time we do this, we need to emit the proper header
2211 * indicating that we recursed, and what the type of object is (the
2212 * object we're storing via a user-hook). Indeed, during retrieval,
2213 * we'll have to create the object before recursing to retrieve the
2214 * others, in case those would point back at that object.
2217 /* [SX_HOOK] <flags> <object>*/
2222 if (ret = store(cxt, xsv)) /* Given by hook for us to store */
2225 svh = hv_fetch(cxt->hseen, (char *) &xsv, sizeof(xsv), FALSE);
2227 CROAK(("Could not serialize item #%d from hook in %s", i, class));
2230 * It was the first time we serialized `xsv'.
2232 * Keep this SV alive until the end of the serialization: if we
2233 * disposed of it right now by decrementing its refcount, and it was
2234 * a temporary value, some next temporary value allocated during
2235 * another STORABLE_freeze might take its place, and we'd wrongly
2236 * assume that new SV was already serialized, based on its presence
2239 * Therefore, push it away in cxt->hook_seen.
2242 av_store(av_hook, AvFILLp(av_hook)+1, SvREFCNT_inc(xsv));
2246 * Dispose of the REF they returned. If we saved the `xsv' away
2247 * in the array of returned SVs, that will not cause the underlying
2248 * referenced SV to be reclaimed.
2251 ASSERT(SvREFCNT(xsv) > 1, ("SV will survive disposal of its REF"));
2252 SvREFCNT_dec(rsv); /* Dispose of reference */
2255 * Replace entry with its tag (not a real SV, so no refcnt increment)
2259 TRACEME(("listed object %d at 0x%"UVxf" is tag #%"UVuf,
2260 i-1, PTR2UV(xsv), PTR2UV(*svh)));
2264 * Allocate a class ID if not already done.
2266 * This needs to be done after the recursion above, since at retrieval
2267 * time, we'll see the inner objects first. Many thanks to
2268 * Salvador Ortiz Garcia <sog@msg.com.mx> who spot that bug and
2269 * proposed the right fix. -- RAM, 15/09/2000
2272 if (!known_class(cxt, class, len, &classnum)) {
2273 TRACEME(("first time we see class %s, ID = %d", class, classnum));
2274 classnum = -1; /* Mark: we must store classname */
2276 TRACEME(("already seen class %s, ID = %d", class, classnum));
2280 * Compute leading flags.
2284 if (((classnum == -1) ? len : classnum) > LG_SCALAR)
2285 flags |= SHF_LARGE_CLASSLEN;
2287 flags |= SHF_IDX_CLASSNAME;
2288 if (len2 > LG_SCALAR)
2289 flags |= SHF_LARGE_STRLEN;
2291 flags |= SHF_HAS_LIST;
2292 if (count > (LG_SCALAR + 1))
2293 flags |= SHF_LARGE_LISTLEN;
2296 * We're ready to emit either serialized form:
2298 * SX_HOOK <flags> <len> <classname> <len2> <str> [<len3> <object-IDs>]
2299 * SX_HOOK <flags> <index> <len2> <str> [<len3> <object-IDs>]
2301 * If we recursed, the SX_HOOK has already been emitted.
2304 TRACEME(("SX_HOOK (recursed=%d) flags=0x%x "
2305 "class=%"IVdf" len=%"IVdf" len2=%"IVdf" len3=%d",
2306 recursed, flags, (IV)classnum, (IV)len, (IV)len2, count-1));
2308 /* SX_HOOK <flags> */
2313 /* <len> <classname> or <index> */
2314 if (flags & SHF_IDX_CLASSNAME) {
2315 if (flags & SHF_LARGE_CLASSLEN)
2318 unsigned char cnum = (unsigned char) classnum;
2322 if (flags & SHF_LARGE_CLASSLEN)
2325 unsigned char clen = (unsigned char) len;
2328 WRITE(class, len); /* Final \0 is omitted */
2331 /* <len2> <frozen-str> */
2332 if (flags & SHF_LARGE_STRLEN) {
2333 I32 wlen2 = len2; /* STRLEN might be 8 bytes */
2334 WLEN(wlen2); /* Must write an I32 for 64-bit machines */
2336 unsigned char clen = (unsigned char) len2;
2340 WRITE(pv, len2); /* Final \0 is omitted */
2342 /* [<len3> <object-IDs>] */
2343 if (flags & SHF_HAS_LIST) {
2344 int len3 = count - 1;
2345 if (flags & SHF_LARGE_LISTLEN)
2348 unsigned char clen = (unsigned char) len3;
2353 * NOTA BENE, for 64-bit machines: the ary[i] below does not yield a
2354 * real pointer, rather a tag number, well under the 32-bit limit.
2357 for (i = 1; i < count; i++) {
2358 I32 tagval = htonl(LOW_32BITS(ary[i]));
2360 TRACEME(("object %d, tag #%d", i-1, ntohl(tagval)));
2365 * Free the array. We need extra care for indices after 0, since they
2366 * don't hold real SVs but integers cast.
2370 AvFILLp(av) = 0; /* Cheat, nothing after 0 interests us */
2378 * store_blessed -- dispatched manually, not via sv_store[]
2380 * Check whether there is a STORABLE_xxx hook defined in the class or in one
2381 * of its ancestors. If there is, then redispatch to store_hook();
2383 * Otherwise, the blessed SV is stored using the following layout:
2385 * SX_BLESS <flag> <len> <classname> <object>
2387 * where <flag> indicates whether <len> is stored on 0 or 4 bytes, depending
2388 * on the high-order bit in flag: if 1, then length follows on 4 bytes.
2389 * Otherwise, the low order bits give the length, thereby giving a compact
2390 * representation for class names less than 127 chars long.
2392 * Each <classname> seen is remembered and indexed, so that the next time
2393 * an object in the blessed in the same <classname> is stored, the following
2396 * SX_IX_BLESS <flag> <index> <object>
2398 * where <index> is the classname index, stored on 0 or 4 bytes depending
2399 * on the high-order bit in flag (same encoding as above for <len>).
2401 static int store_blessed(
2412 TRACEME(("store_blessed, type %d, class \"%s\"", type, HvNAME(pkg)));
2415 * Look for a hook for this blessed SV and redirect to store_hook()
2419 hook = pkg_can(cxt->hook, pkg, "STORABLE_freeze");
2421 return store_hook(cxt, sv, type, pkg, hook);
2424 * This is a blessed SV without any serialization hook.
2427 class = HvNAME(pkg);
2428 len = strlen(class);
2430 TRACEME(("blessed 0x%"UVxf" in %s, no hook: tagged #%d",
2431 PTR2UV(sv), class, cxt->tagnum));
2434 * Determine whether it is the first time we see that class name (in which
2435 * case it will be stored in the SX_BLESS form), or whether we already
2436 * saw that class name before (in which case the SX_IX_BLESS form will be
2440 if (known_class(cxt, class, len, &classnum)) {
2441 TRACEME(("already seen class %s, ID = %d", class, classnum));
2442 PUTMARK(SX_IX_BLESS);
2443 if (classnum <= LG_BLESS) {
2444 unsigned char cnum = (unsigned char) classnum;
2447 unsigned char flag = (unsigned char) 0x80;
2452 TRACEME(("first time we see class %s, ID = %d", class, classnum));
2454 if (len <= LG_BLESS) {
2455 unsigned char clen = (unsigned char) len;
2458 unsigned char flag = (unsigned char) 0x80;
2460 WLEN(len); /* Don't BER-encode, this should be rare */
2462 WRITE(class, len); /* Final \0 is omitted */
2466 * Now emit the <object> part.
2469 return SV_STORE(type)(cxt, sv);
2475 * We don't know how to store the item we reached, so return an error condition.
2476 * (it's probably a GLOB, some CODE reference, etc...)
2478 * If they defined the `forgive_me' variable at the Perl level to some
2479 * true value, then don't croak, just warn, and store a placeholder string
2482 static int store_other(stcxt_t *cxt, SV *sv)
2485 static char buf[80];
2487 TRACEME(("store_other"));
2490 * Fetch the value from perl only once per store() operation.
2494 cxt->forgive_me == 0 ||
2495 (cxt->forgive_me < 0 && !(cxt->forgive_me =
2496 SvTRUE(perl_get_sv("Storable::forgive_me", TRUE)) ? 1 : 0))
2498 CROAK(("Can't store %s items", sv_reftype(sv, FALSE)));
2500 warn("Can't store item %s(0x%"UVxf")",
2501 sv_reftype(sv, FALSE), PTR2UV(sv));
2504 * Store placeholder string as a scalar instead...
2507 (void) sprintf(buf, "You lost %s(0x%"UVxf")\0", sv_reftype(sv, FALSE),
2511 STORE_SCALAR(buf, len);
2512 TRACEME(("ok (dummy \"%s\", length = %"IVdf")", buf, len));
2518 *** Store driving routines
2524 * WARNING: partially duplicates Perl's sv_reftype for speed.
2526 * Returns the type of the SV, identified by an integer. That integer
2527 * may then be used to index the dynamic routine dispatch table.
2529 static int sv_type(SV *sv)
2531 switch (SvTYPE(sv)) {
2536 * No need to check for ROK, that can't be set here since there
2537 * is no field capable of hodling the xrv_rv reference.
2545 * Starting from SVt_PV, it is possible to have the ROK flag
2546 * set, the pointer to the other SV being either stored in
2547 * the xrv_rv (in the case of a pure SVt_RV), or as the
2548 * xpv_pv field of an SVt_PV and its heirs.
2550 * However, those SV cannot be magical or they would be an
2551 * SVt_PVMG at least.
2553 return SvROK(sv) ? svis_REF : svis_SCALAR;
2555 case SVt_PVLV: /* Workaround for perl5.004_04 "LVALUE" bug */
2556 if (SvRMAGICAL(sv) && (mg_find(sv, 'p')))
2557 return svis_TIED_ITEM;
2560 if (SvRMAGICAL(sv) && (mg_find(sv, 'q')))
2562 return SvROK(sv) ? svis_REF : svis_SCALAR;
2564 if (SvRMAGICAL(sv) && (mg_find(sv, 'P')))
2568 if (SvRMAGICAL(sv) && (mg_find(sv, 'P')))
2581 * Recursively store objects pointed to by the sv to the specified file.
2583 * Layout is <content> or SX_OBJECT <tagnum> if we reach an already stored
2584 * object (one for which storage has started -- it may not be over if we have
2585 * a self-referenced structure). This data set forms a stored <object>.
2587 static int store(stcxt_t *cxt, SV *sv)
2593 HV *hseen = cxt->hseen;
2595 TRACEME(("store (0x%"UVxf")", PTR2UV(sv)));
2598 * If object has already been stored, do not duplicate data.
2599 * Simply emit the SX_OBJECT marker followed by its tag data.
2600 * The tag is always written in network order.
2602 * NOTA BENE, for 64-bit machines: the "*svh" below does not yield a
2603 * real pointer, rather a tag number (watch the insertion code below).
2604 * That means it pobably safe to assume it is well under the 32-bit limit,
2605 * and makes the truncation safe.
2606 * -- RAM, 14/09/1999
2609 svh = hv_fetch(hseen, (char *) &sv, sizeof(sv), FALSE);
2611 I32 tagval = htonl(LOW_32BITS(*svh));
2613 TRACEME(("object 0x%"UVxf" seen as #%d", PTR2UV(sv), ntohl(tagval)));
2621 * Allocate a new tag and associate it with the address of the sv being
2622 * stored, before recursing...
2624 * In order to avoid creating new SvIVs to hold the tagnum we just
2625 * cast the tagnum to a SV pointer and store that in the hash. This
2626 * means that we must clean up the hash manually afterwards, but gives
2627 * us a 15% throughput increase.
2632 if (!hv_store(hseen,
2633 (char *) &sv, sizeof(sv), INT2PTR(SV*, cxt->tagnum), 0))
2637 * Store `sv' and everything beneath it, using appropriate routine.
2638 * Abort immediately if we get a non-zero status back.
2643 TRACEME(("storing 0x%"UVxf" tag #%d, type %d...",
2644 PTR2UV(sv), cxt->tagnum, type));
2647 HV *pkg = SvSTASH(sv);
2648 ret = store_blessed(cxt, sv, type, pkg);
2650 ret = SV_STORE(type)(cxt, sv);
2652 TRACEME(("%s (stored 0x%"UVxf", refcnt=%d, %s)",
2653 ret ? "FAILED" : "ok", PTR2UV(sv),
2654 SvREFCNT(sv), sv_reftype(sv, FALSE)));
2662 * Write magic number and system information into the file.
2663 * Layout is <magic> <network> [<len> <byteorder> <sizeof int> <sizeof long>
2664 * <sizeof ptr>] where <len> is the length of the byteorder hexa string.
2665 * All size and lenghts are written as single characters here.
2667 * Note that no byte ordering info is emitted when <network> is true, since
2668 * integers will be emitted in network order in that case.
2670 static int magic_write(stcxt_t *cxt)
2672 char buf[256]; /* Enough room for 256 hexa digits */
2674 int use_network_order = cxt->netorder;
2676 TRACEME(("magic_write on fd=%d", cxt->fio ? fileno(cxt->fio) : -1));
2679 WRITE(magicstr, strlen(magicstr)); /* Don't write final \0 */
2682 * Starting with 0.6, the "use_network_order" byte flag is also used to
2683 * indicate the version number of the binary image, encoded in the upper
2684 * bits. The bit 0 is always used to indicate network order.
2688 ((use_network_order ? 0x1 : 0x0) | (STORABLE_BIN_MAJOR << 1));
2692 * Starting with 0.7, a full byte is dedicated to the minor version of
2693 * the binary format, which is incremented only when new markers are
2694 * introduced, for instance, but when backward compatibility is preserved.
2697 PUTMARK((unsigned char) STORABLE_BIN_MINOR);
2699 if (use_network_order)
2700 return 0; /* Don't bother with byte ordering */
2702 sprintf(buf, "%lx", (unsigned long) BYTEORDER);
2703 c = (unsigned char) strlen(buf);
2705 WRITE(buf, (unsigned int) c); /* Don't write final \0 */
2706 PUTMARK((unsigned char) sizeof(int));
2707 PUTMARK((unsigned char) sizeof(long));
2708 PUTMARK((unsigned char) sizeof(char *));
2709 PUTMARK((unsigned char) sizeof(NV));
2711 TRACEME(("ok (magic_write byteorder = 0x%lx [%d], I%d L%d P%d D%d)",
2712 (unsigned long) BYTEORDER, (int) c,
2713 (int) sizeof(int), (int) sizeof(long),
2714 (int) sizeof(char *), (int) sizeof(NV)));
2722 * Common code for store operations.
2724 * When memory store is requested (f = NULL) and a non null SV* is given in
2725 * `res', it is filled with a new SV created out of the memory buffer.
2727 * It is required to provide a non-null `res' when the operation type is not
2728 * dclone() and store() is performed to memory.
2730 static int do_store(
2740 ASSERT(!(f == 0 && !(optype & ST_CLONE)) || res,
2741 ("must supply result SV pointer for real recursion to memory"));
2743 TRACEME(("do_store (optype=%d, netorder=%d)",
2744 optype, network_order));
2749 * Workaround for CROAK leak: if they enter with a "dirty" context,
2750 * free up memory for them now.
2757 * Now that STORABLE_xxx hooks exist, it is possible that they try to
2758 * re-enter store() via the hooks. We need to stack contexts.
2762 cxt = allocate_context(cxt);
2766 ASSERT(cxt->entry == 1, ("starting new recursion"));
2767 ASSERT(!cxt->s_dirty, ("clean context"));
2770 * Ensure sv is actually a reference. From perl, we called something
2772 * pstore(FILE, \@array);
2773 * so we must get the scalar value behing that reference.
2777 CROAK(("Not a reference"));
2778 sv = SvRV(sv); /* So follow it to know what to store */
2781 * If we're going to store to memory, reset the buffer.
2788 * Prepare context and emit headers.
2791 init_store_context(cxt, f, optype, network_order);
2793 if (-1 == magic_write(cxt)) /* Emit magic and ILP info */
2794 return 0; /* Error */
2797 * Recursively store object...
2800 ASSERT(is_storing(), ("within store operation"));
2802 status = store(cxt, sv); /* Just do it! */
2805 * If they asked for a memory store and they provided an SV pointer,
2806 * make an SV string out of the buffer and fill their pointer.
2808 * When asking for ST_REAL, it's MANDATORY for the caller to provide
2809 * an SV, since context cleanup might free the buffer if we did recurse.
2810 * (unless caller is dclone(), which is aware of that).
2813 if (!cxt->fio && res)
2819 * The "root" context is never freed, since it is meant to be always
2820 * handy for the common case where no recursion occurs at all (i.e.
2821 * we enter store() outside of any Storable code and leave it, period).
2822 * We know it's the "root" context because there's nothing stacked
2827 * When deep cloning, we don't free the context: doing so would force
2828 * us to copy the data in the memory buffer. Sicne we know we're
2829 * about to enter do_retrieve...
2832 clean_store_context(cxt);
2833 if (cxt->prev && !(cxt->optype & ST_CLONE))
2836 TRACEME(("do_store returns %d", status));
2844 * Store the transitive data closure of given object to disk.
2845 * Returns 0 on error, a true value otherwise.
2847 int pstore(PerlIO *f, SV *sv)
2849 TRACEME(("pstore"));
2850 return do_store(f, sv, 0, FALSE, (SV**) 0);
2857 * Same as pstore(), but network order is used for integers and doubles are
2858 * emitted as strings.
2860 int net_pstore(PerlIO *f, SV *sv)
2862 TRACEME(("net_pstore"));
2863 return do_store(f, sv, 0, TRUE, (SV**) 0);
2873 * Build a new SV out of the content of the internal memory buffer.
2875 static SV *mbuf2sv(void)
2879 return newSVpv(mbase, MBUF_SIZE());
2885 * Store the transitive data closure of given object to memory.
2886 * Returns undef on error, a scalar value containing the data otherwise.
2893 TRACEME(("mstore"));
2895 if (!do_store((PerlIO*) 0, sv, 0, FALSE, &out))
2896 return &PL_sv_undef;
2904 * Same as mstore(), but network order is used for integers and doubles are
2905 * emitted as strings.
2907 SV *net_mstore(SV *sv)
2912 TRACEME(("net_mstore"));
2914 if (!do_store((PerlIO*) 0, sv, 0, TRUE, &out))
2915 return &PL_sv_undef;
2921 *** Specific retrieve callbacks.
2927 * Return an error via croak, since it is not possible that we get here
2928 * under normal conditions, when facing a file produced via pstore().
2930 static SV *retrieve_other(stcxt_t *cxt)
2933 cxt->ver_major != STORABLE_BIN_MAJOR &&
2934 cxt->ver_minor != STORABLE_BIN_MINOR
2936 CROAK(("Corrupted storable %s (binary v%d.%d), current is v%d.%d",
2937 cxt->fio ? "file" : "string",
2938 cxt->ver_major, cxt->ver_minor,
2939 STORABLE_BIN_MAJOR, STORABLE_BIN_MINOR));
2941 CROAK(("Corrupted storable %s (binary v%d.%d)",
2942 cxt->fio ? "file" : "string",
2943 cxt->ver_major, cxt->ver_minor));
2946 return (SV *) 0; /* Just in case */
2950 * retrieve_idx_blessed
2952 * Layout is SX_IX_BLESS <index> <object> with SX_IX_BLESS already read.
2953 * <index> can be coded on either 1 or 5 bytes.
2955 static SV *retrieve_idx_blessed(stcxt_t *cxt)
2962 TRACEME(("retrieve_idx_blessed (#%d)", cxt->tagnum));
2964 GETMARK(idx); /* Index coded on a single char? */
2969 * Fetch classname in `aclass'
2972 sva = av_fetch(cxt->aclass, idx, FALSE);
2974 CROAK(("Class name #%d should have been seen already", (int)idx));
2976 class = SvPVX(*sva); /* We know it's a PV, by construction */
2978 TRACEME(("class ID %d => %s", idx, class));
2981 * Retrieve object and bless it.
2994 * Layout is SX_BLESS <len> <classname> <object> with SX_BLESS already read.
2995 * <len> can be coded on either 1 or 5 bytes.
2997 static SV *retrieve_blessed(stcxt_t *cxt)
3001 char buf[LG_BLESS + 1]; /* Avoid malloc() if possible */
3004 TRACEME(("retrieve_blessed (#%d)", cxt->tagnum));
3007 * Decode class name length and read that name.
3009 * Short classnames have two advantages: their length is stored on one
3010 * single byte, and the string can be read on the stack.
3013 GETMARK(len); /* Length coded on a single char? */
3016 TRACEME(("** allocating %d bytes for class name", len+1));
3017 New(10003, class, len+1, char);
3020 class[len] = '\0'; /* Mark string end */
3023 * It's a new classname, otherwise it would have been an SX_IX_BLESS.
3026 if (!av_store(cxt->aclass, cxt->classnum++, newSVpvn(class, len)))
3030 * Retrieve object and bless it.
3046 * Layout: SX_HOOK <flags> <len> <classname> <len2> <str> [<len3> <object-IDs>]
3047 * with leading mark already read, as usual.
3049 * When recursion was involved during serialization of the object, there
3050 * is an unknown amount of serialized objects after the SX_HOOK mark. Until
3051 * we reach a <flags> marker with the recursion bit cleared.
3053 static SV *retrieve_hook(stcxt_t *cxt)
3056 char buf[LG_BLESS + 1]; /* Avoid malloc() if possible */
3068 int clone = cxt->optype & ST_CLONE;
3070 TRACEME(("retrieve_hook (#%d)", cxt->tagnum));
3073 * Read flags, which tell us about the type, and whether we need to recurse.
3079 * Create the (empty) object, and mark it as seen.
3081 * This must be done now, because tags are incremented, and during
3082 * serialization, the object tag was affected before recursion could
3086 obj_type = flags & SHF_TYPE_MASK;
3092 sv = (SV *) newAV();
3095 sv = (SV *) newHV();
3098 return retrieve_other(cxt); /* Let it croak */
3103 * Whilst flags tell us to recurse, do so.
3105 * We don't need to remember the addresses returned by retrieval, because
3106 * all the references will be obtained through indirection via the object
3107 * tags in the object-ID list.
3110 while (flags & SHF_NEED_RECURSE) {
3111 TRACEME(("retrieve_hook recursing..."));
3115 TRACEME(("retrieve_hook back with rv=0x%"UVxf,
3120 if (flags & SHF_IDX_CLASSNAME) {
3125 * Fetch index from `aclass'
3128 if (flags & SHF_LARGE_CLASSLEN)
3133 sva = av_fetch(cxt->aclass, idx, FALSE);
3135 CROAK(("Class name #%d should have been seen already", (int)idx));
3137 class = SvPVX(*sva); /* We know it's a PV, by construction */
3138 TRACEME(("class ID %d => %s", idx, class));
3142 * Decode class name length and read that name.
3144 * NOTA BENE: even if the length is stored on one byte, we don't read
3145 * on the stack. Just like retrieve_blessed(), we limit the name to
3146 * LG_BLESS bytes. This is an arbitrary decision.
3149 if (flags & SHF_LARGE_CLASSLEN)
3154 if (len > LG_BLESS) {
3155 TRACEME(("** allocating %d bytes for class name", len+1));
3156 New(10003, class, len+1, char);
3160 class[len] = '\0'; /* Mark string end */
3163 * Record new classname.
3166 if (!av_store(cxt->aclass, cxt->classnum++, newSVpvn(class, len)))
3170 TRACEME(("class name: %s", class));
3173 * Decode user-frozen string length and read it in a SV.
3175 * For efficiency reasons, we read data directly into the SV buffer.
3176 * To understand that code, read retrieve_scalar()
3179 if (flags & SHF_LARGE_STRLEN)
3184 frozen = NEWSV(10002, len2);
3186 SAFEREAD(SvPVX(frozen), len2, frozen);
3187 SvCUR_set(frozen, len2);
3188 *SvEND(frozen) = '\0';
3190 (void) SvPOK_only(frozen); /* Validates string pointer */
3191 if (cxt->s_tainted) /* Is input source tainted? */
3194 TRACEME(("frozen string: %d bytes", len2));
3197 * Decode object-ID list length, if present.
3200 if (flags & SHF_HAS_LIST) {
3201 if (flags & SHF_LARGE_LISTLEN)
3207 av_extend(av, len3 + 1); /* Leave room for [0] */
3208 AvFILLp(av) = len3; /* About to be filled anyway */
3212 TRACEME(("has %d object IDs to link", len3));
3215 * Read object-ID list into array.
3216 * Because we pre-extended it, we can cheat and fill it manually.
3218 * We read object tags and we can convert them into SV* on the fly
3219 * because we know all the references listed in there (as tags)
3220 * have been already serialized, hence we have a valid correspondance
3221 * between each of those tags and the recreated SV.
3225 SV **ary = AvARRAY(av);
3227 for (i = 1; i <= len3; i++) { /* We leave [0] alone */
3234 svh = av_fetch(cxt->aseen, tag, FALSE);
3236 CROAK(("Object #%d should have been retrieved already", (int)tag));
3238 ary[i] = SvREFCNT_inc(xsv);
3243 * Bless the object and look up the STORABLE_thaw hook.
3247 hook = pkg_can(cxt->hook, SvSTASH(sv), "STORABLE_thaw");
3250 * Hook not found. Maybe they did not require the module where this
3251 * hook is defined yet?
3253 * If the require below succeeds, we'll be able to find the hook.
3254 * Still, it only works reliably when each class is defined in a
3258 SV *psv = newSVpvn("require ", 8);
3259 sv_catpv(psv, class);
3261 TRACEME(("No STORABLE_thaw defined for objects of class %s", class));
3262 TRACEME(("Going to require module '%s' with '%s'", class, SvPVX(psv)));
3264 perl_eval_sv(psv, G_DISCARD);
3268 * We cache results of pkg_can, so we need to uncache before attempting
3272 pkg_uncache(cxt->hook, SvSTASH(sv), "STORABLE_thaw");
3273 hook = pkg_can(cxt->hook, SvSTASH(sv), "STORABLE_thaw");
3276 CROAK(("No STORABLE_thaw defined for objects of class %s "
3277 "(even after a \"require %s;\")", class, class));
3281 * If we don't have an `av' yet, prepare one.
3282 * Then insert the frozen string as item [0].
3290 AvARRAY(av)[0] = SvREFCNT_inc(frozen);
3295 * $object->STORABLE_thaw($cloning, $frozen, @refs);
3297 * where $object is our blessed (empty) object, $cloning is a boolean
3298 * telling whether we're running a deep clone, $frozen is the frozen
3299 * string the user gave us in his serializing hook, and @refs, which may
3300 * be empty, is the list of extra references he returned along for us
3303 * In effect, the hook is an alternate creation routine for the class,
3304 * the object itself being already created by the runtime.
3307 TRACEME(("calling STORABLE_thaw on %s at 0x%"UVxf" (%"IVdf" args)",
3308 class, PTR2UV(sv), AvFILLp(av) + 1));
3311 (void) scalar_call(rv, hook, clone, av, G_SCALAR|G_DISCARD);
3318 SvREFCNT_dec(frozen);
3321 if (!(flags & SHF_IDX_CLASSNAME) && class != buf)
3330 * Retrieve reference to some other scalar.
3331 * Layout is SX_REF <object>, with SX_REF already read.
3333 static SV *retrieve_ref(stcxt_t *cxt)
3338 TRACEME(("retrieve_ref (#%d)", cxt->tagnum));
3341 * We need to create the SV that holds the reference to the yet-to-retrieve
3342 * object now, so that we may record the address in the seen table.
3343 * Otherwise, if the object to retrieve references us, we won't be able
3344 * to resolve the SX_OBJECT we'll see at that point! Hence we cannot
3345 * do the retrieve first and use rv = newRV(sv) since it will be too late
3346 * for SEEN() recording.
3349 rv = NEWSV(10002, 0);
3350 SEEN(rv); /* Will return if rv is null */
3351 sv = retrieve(cxt); /* Retrieve <object> */
3353 return (SV *) 0; /* Failed */
3356 * WARNING: breaks RV encapsulation.
3358 * Now for the tricky part. We have to upgrade our existing SV, so that
3359 * it is now an RV on sv... Again, we cheat by duplicating the code
3360 * held in newSVrv(), since we already got our SV from retrieve().
3364 * SvRV(rv) = SvREFCNT_inc(sv);
3366 * here because the reference count we got from retrieve() above is
3367 * already correct: if the object was retrieved from the file, then
3368 * its reference count is one. Otherwise, if it was retrieved via
3369 * an SX_OBJECT indication, a ref count increment was done.
3372 sv_upgrade(rv, SVt_RV);
3373 SvRV(rv) = sv; /* $rv = \$sv */
3376 TRACEME(("ok (retrieve_ref at 0x%"UVxf")", PTR2UV(rv)));
3382 * retrieve_overloaded
3384 * Retrieve reference to some other scalar with overloading.
3385 * Layout is SX_OVERLOAD <object>, with SX_OVERLOAD already read.
3387 static SV *retrieve_overloaded(stcxt_t *cxt)
3393 TRACEME(("retrieve_overloaded (#%d)", cxt->tagnum));
3396 * Same code as retrieve_ref(), duplicated to avoid extra call.
3399 rv = NEWSV(10002, 0);
3400 SEEN(rv); /* Will return if rv is null */
3401 sv = retrieve(cxt); /* Retrieve <object> */
3403 return (SV *) 0; /* Failed */
3406 * WARNING: breaks RV encapsulation.
3409 sv_upgrade(rv, SVt_RV);
3410 SvRV(rv) = sv; /* $rv = \$sv */
3414 * Restore overloading magic.
3417 stash = (HV *) SvSTASH (sv);
3418 if (!stash || !Gv_AMG(stash))
3419 CROAK(("Cannot restore overloading on %s(0x%"UVxf") (package %s)",
3420 sv_reftype(sv, FALSE),
3422 stash ? HvNAME(stash) : "<unknown>"));
3426 TRACEME(("ok (retrieve_overloaded at 0x%"UVxf")", PTR2UV(rv)));
3432 * retrieve_tied_array
3434 * Retrieve tied array
3435 * Layout is SX_TIED_ARRAY <object>, with SX_TIED_ARRAY already read.
3437 static SV *retrieve_tied_array(stcxt_t *cxt)
3442 TRACEME(("retrieve_tied_array (#%d)", cxt->tagnum));
3444 tv = NEWSV(10002, 0);
3445 SEEN(tv); /* Will return if tv is null */
3446 sv = retrieve(cxt); /* Retrieve <object> */
3448 return (SV *) 0; /* Failed */
3450 sv_upgrade(tv, SVt_PVAV);
3451 AvREAL_off((AV *)tv);
3452 sv_magic(tv, sv, 'P', Nullch, 0);
3453 SvREFCNT_dec(sv); /* Undo refcnt inc from sv_magic() */
3455 TRACEME(("ok (retrieve_tied_array at 0x%"UVxf")", PTR2UV(tv)));
3461 * retrieve_tied_hash
3463 * Retrieve tied hash
3464 * Layout is SX_TIED_HASH <object>, with SX_TIED_HASH already read.
3466 static SV *retrieve_tied_hash(stcxt_t *cxt)
3471 TRACEME(("retrieve_tied_hash (#%d)", cxt->tagnum));
3473 tv = NEWSV(10002, 0);
3474 SEEN(tv); /* Will return if tv is null */
3475 sv = retrieve(cxt); /* Retrieve <object> */
3477 return (SV *) 0; /* Failed */
3479 sv_upgrade(tv, SVt_PVHV);
3480 sv_magic(tv, sv, 'P', Nullch, 0);
3481 SvREFCNT_dec(sv); /* Undo refcnt inc from sv_magic() */
3483 TRACEME(("ok (retrieve_tied_hash at 0x%"UVxf")", PTR2UV(tv)));
3489 * retrieve_tied_scalar
3491 * Retrieve tied scalar
3492 * Layout is SX_TIED_SCALAR <object>, with SX_TIED_SCALAR already read.
3494 static SV *retrieve_tied_scalar(cxt)
3500 TRACEME(("retrieve_tied_scalar (#%d)", cxt->tagnum));
3502 tv = NEWSV(10002, 0);
3503 SEEN(tv); /* Will return if rv is null */
3504 sv = retrieve(cxt); /* Retrieve <object> */
3506 return (SV *) 0; /* Failed */
3508 sv_upgrade(tv, SVt_PVMG);
3509 sv_magic(tv, sv, 'q', Nullch, 0);
3510 SvREFCNT_dec(sv); /* Undo refcnt inc from sv_magic() */
3512 TRACEME(("ok (retrieve_tied_scalar at 0x%"UVxf")", PTR2UV(tv)));
3520 * Retrieve reference to value in a tied hash.
3521 * Layout is SX_TIED_KEY <object> <key>, with SX_TIED_KEY already read.
3523 static SV *retrieve_tied_key(stcxt_t *cxt)
3529 TRACEME(("retrieve_tied_key (#%d)", cxt->tagnum));
3531 tv = NEWSV(10002, 0);
3532 SEEN(tv); /* Will return if tv is null */
3533 sv = retrieve(cxt); /* Retrieve <object> */
3535 return (SV *) 0; /* Failed */
3537 key = retrieve(cxt); /* Retrieve <key> */
3539 return (SV *) 0; /* Failed */
3541 sv_upgrade(tv, SVt_PVMG);
3542 sv_magic(tv, sv, 'p', (char *)key, HEf_SVKEY);
3543 SvREFCNT_dec(key); /* Undo refcnt inc from sv_magic() */
3544 SvREFCNT_dec(sv); /* Undo refcnt inc from sv_magic() */
3552 * Retrieve reference to value in a tied array.
3553 * Layout is SX_TIED_IDX <object> <idx>, with SX_TIED_IDX already read.
3555 static SV *retrieve_tied_idx(stcxt_t *cxt)
3561 TRACEME(("retrieve_tied_idx (#%d)", cxt->tagnum));
3563 tv = NEWSV(10002, 0);
3564 SEEN(tv); /* Will return if tv is null */
3565 sv = retrieve(cxt); /* Retrieve <object> */
3567 return (SV *) 0; /* Failed */
3569 RLEN(idx); /* Retrieve <idx> */
3571 sv_upgrade(tv, SVt_PVMG);
3572 sv_magic(tv, sv, 'p', Nullch, idx);
3573 SvREFCNT_dec(sv); /* Undo refcnt inc from sv_magic() */
3582 * Retrieve defined long (string) scalar.
3584 * Layout is SX_LSCALAR <length> <data>, with SX_LSCALAR already read.
3585 * The scalar is "long" in that <length> is larger than LG_SCALAR so it
3586 * was not stored on a single byte.
3588 static SV *retrieve_lscalar(stcxt_t *cxt)
3594 TRACEME(("retrieve_lscalar (#%d), len = %"IVdf, cxt->tagnum, len));
3597 * Allocate an empty scalar of the suitable length.
3600 sv = NEWSV(10002, len);
3601 SEEN(sv); /* Associate this new scalar with tag "tagnum" */
3604 * WARNING: duplicates parts of sv_setpv and breaks SV data encapsulation.
3606 * Now, for efficiency reasons, read data directly inside the SV buffer,
3607 * and perform the SV final settings directly by duplicating the final
3608 * work done by sv_setpv. Since we're going to allocate lots of scalars
3609 * this way, it's worth the hassle and risk.
3612 SAFEREAD(SvPVX(sv), len, sv);
3613 SvCUR_set(sv, len); /* Record C string length */
3614 *SvEND(sv) = '\0'; /* Ensure it's null terminated anyway */
3615 (void) SvPOK_only(sv); /* Validate string pointer */
3616 if (cxt->s_tainted) /* Is input source tainted? */
3617 SvTAINT(sv); /* External data cannot be trusted */
3619 TRACEME(("large scalar len %"IVdf" '%s'", len, SvPVX(sv)));
3620 TRACEME(("ok (retrieve_lscalar at 0x%"UVxf")", PTR2UV(sv)));
3628 * Retrieve defined short (string) scalar.
3630 * Layout is SX_SCALAR <length> <data>, with SX_SCALAR already read.
3631 * The scalar is "short" so <length> is single byte. If it is 0, there
3632 * is no <data> section.
3634 static SV *retrieve_scalar(stcxt_t *cxt)
3640 TRACEME(("retrieve_scalar (#%d), len = %d", cxt->tagnum, len));
3643 * Allocate an empty scalar of the suitable length.
3646 sv = NEWSV(10002, len);
3647 SEEN(sv); /* Associate this new scalar with tag "tagnum" */
3650 * WARNING: duplicates parts of sv_setpv and breaks SV data encapsulation.
3655 * newSV did not upgrade to SVt_PV so the scalar is undefined.
3656 * To make it defined with an empty length, upgrade it now...
3658 sv_upgrade(sv, SVt_PV);
3660 *SvEND(sv) = '\0'; /* Ensure it's null terminated anyway */
3661 TRACEME(("ok (retrieve_scalar empty at 0x%"UVxf")", PTR2UV(sv)));
3664 * Now, for efficiency reasons, read data directly inside the SV buffer,
3665 * and perform the SV final settings directly by duplicating the final
3666 * work done by sv_setpv. Since we're going to allocate lots of scalars
3667 * this way, it's worth the hassle and risk.
3669 SAFEREAD(SvPVX(sv), len, sv);
3670 SvCUR_set(sv, len); /* Record C string length */
3671 *SvEND(sv) = '\0'; /* Ensure it's null terminated anyway */
3672 TRACEME(("small scalar len %d '%s'", len, SvPVX(sv)));
3675 (void) SvPOK_only(sv); /* Validate string pointer */
3676 if (cxt->s_tainted) /* Is input source tainted? */
3677 SvTAINT(sv); /* External data cannot be trusted */
3679 TRACEME(("ok (retrieve_scalar at 0x%"UVxf")", PTR2UV(sv)));
3686 * Like retrieve_scalar(), but tag result as utf8.
3687 * If we're retrieving UTF8 data in a non-UTF8 perl, croaks.
3689 static SV *retrieve_utf8str(stcxt_t *cxt)
3693 TRACEME(("retrieve_utf8str"));
3695 sv = retrieve_scalar(cxt);
3705 * Like retrieve_lscalar(), but tag result as utf8.
3706 * If we're retrieving UTF8 data in a non-UTF8 perl, croaks.
3708 static SV *retrieve_lutf8str(stcxt_t *cxt)
3712 TRACEME(("retrieve_lutf8str"));
3714 sv = retrieve_lscalar(cxt);
3724 * Retrieve defined integer.
3725 * Layout is SX_INTEGER <data>, whith SX_INTEGER already read.
3727 static SV *retrieve_integer(stcxt_t *cxt)
3732 TRACEME(("retrieve_integer (#%d)", cxt->tagnum));
3734 READ(&iv, sizeof(iv));
3736 SEEN(sv); /* Associate this new scalar with tag "tagnum" */
3738 TRACEME(("integer %"IVdf, iv));
3739 TRACEME(("ok (retrieve_integer at 0x%"UVxf")", PTR2UV(sv)));
3747 * Retrieve defined integer in network order.
3748 * Layout is SX_NETINT <data>, whith SX_NETINT already read.
3750 static SV *retrieve_netint(stcxt_t *cxt)
3755 TRACEME(("retrieve_netint (#%d)", cxt->tagnum));
3759 sv = newSViv((int) ntohl(iv));
3760 TRACEME(("network integer %d", (int) ntohl(iv)));
3763 TRACEME(("network integer (as-is) %d", iv));
3765 SEEN(sv); /* Associate this new scalar with tag "tagnum" */
3767 TRACEME(("ok (retrieve_netint at 0x%"UVxf")", PTR2UV(sv)));
3775 * Retrieve defined double.
3776 * Layout is SX_DOUBLE <data>, whith SX_DOUBLE already read.
3778 static SV *retrieve_double(stcxt_t *cxt)
3783 TRACEME(("retrieve_double (#%d)", cxt->tagnum));
3785 READ(&nv, sizeof(nv));
3787 SEEN(sv); /* Associate this new scalar with tag "tagnum" */
3789 TRACEME(("double %"NVff, nv));
3790 TRACEME(("ok (retrieve_double at 0x%"UVxf")", PTR2UV(sv)));
3798 * Retrieve defined byte (small integer within the [-128, +127] range).
3799 * Layout is SX_BYTE <data>, whith SX_BYTE already read.
3801 static SV *retrieve_byte(stcxt_t *cxt)
3806 TRACEME(("retrieve_byte (#%d)", cxt->tagnum));
3809 TRACEME(("small integer read as %d", (unsigned char) siv));
3810 sv = newSViv((unsigned char) siv - 128);
3811 SEEN(sv); /* Associate this new scalar with tag "tagnum" */
3813 TRACEME(("byte %d", (unsigned char) siv - 128));
3814 TRACEME(("ok (retrieve_byte at 0x%"UVxf")", PTR2UV(sv)));
3822 * Return the undefined value.
3824 static SV *retrieve_undef(stcxt_t *cxt)
3828 TRACEME(("retrieve_undef"));
3839 * Return the immortal undefined value.
3841 static SV *retrieve_sv_undef(stcxt_t *cxt)
3843 SV *sv = &PL_sv_undef;
3845 TRACEME(("retrieve_sv_undef"));
3854 * Return the immortal yes value.
3856 static SV *retrieve_sv_yes(stcxt_t *cxt)
3858 SV *sv = &PL_sv_yes;
3860 TRACEME(("retrieve_sv_yes"));
3869 * Return the immortal no value.
3871 static SV *retrieve_sv_no(stcxt_t *cxt)
3875 TRACEME(("retrieve_sv_no"));
3884 * Retrieve a whole array.
3885 * Layout is SX_ARRAY <size> followed by each item, in increading index order.
3886 * Each item is stored as <object>.
3888 * When we come here, SX_ARRAY has been read already.
3890 static SV *retrieve_array(stcxt_t *cxt)
3897 TRACEME(("retrieve_array (#%d)", cxt->tagnum));
3900 * Read length, and allocate array, then pre-extend it.
3904 TRACEME(("size = %d", len));
3906 SEEN(av); /* Will return if array not allocated nicely */
3910 return (SV *) av; /* No data follow if array is empty */
3913 * Now get each item in turn...
3916 for (i = 0; i < len; i++) {
3917 TRACEME(("(#%d) item", i));
3918 sv = retrieve(cxt); /* Retrieve item */
3921 if (av_store(av, i, sv) == 0)
3925 TRACEME(("ok (retrieve_array at 0x%"UVxf")", PTR2UV(av)));
3933 * Retrieve a whole hash table.
3934 * Layout is SX_HASH <size> followed by each key/value pair, in random order.
3935 * Keys are stored as <length> <data>, the <data> section being omitted
3937 * Values are stored as <object>.
3939 * When we come here, SX_HASH has been read already.
3941 static SV *retrieve_hash(stcxt_t *cxt)
3948 static SV *sv_h_undef = (SV *) 0; /* hv_store() bug */
3950 TRACEME(("retrieve_hash (#%d)", cxt->tagnum));
3953 * Read length, allocate table.
3957 TRACEME(("size = %d", len));
3959 SEEN(hv); /* Will return if table not allocated properly */
3961 return (SV *) hv; /* No data follow if table empty */
3964 * Now get each key/value pair in turn...
3967 for (i = 0; i < len; i++) {
3972 TRACEME(("(#%d) value", i));
3979 * Since we're reading into kbuf, we must ensure we're not
3980 * recursing between the read and the hv_store() where it's used.
3981 * Hence the key comes after the value.
3984 RLEN(size); /* Get key size */
3985 KBUFCHK(size); /* Grow hash key read pool if needed */
3988 kbuf[size] = '\0'; /* Mark string end, just in case */
3989 TRACEME(("(#%d) key '%s'", i, kbuf));
3992 * Enter key/value pair into hash table.
3995 if (hv_store(hv, kbuf, (U32) size, sv, 0) == 0)
3999 TRACEME(("ok (retrieve_hash at 0x%"UVxf")", PTR2UV(hv)));
4005 * old_retrieve_array
4007 * Retrieve a whole array in pre-0.6 binary format.
4009 * Layout is SX_ARRAY <size> followed by each item, in increading index order.
4010 * Each item is stored as SX_ITEM <object> or SX_IT_UNDEF for "holes".
4012 * When we come here, SX_ARRAY has been read already.
4014 static SV *old_retrieve_array(stcxt_t *cxt)
4022 TRACEME(("old_retrieve_array (#%d)", cxt->tagnum));
4025 * Read length, and allocate array, then pre-extend it.
4029 TRACEME(("size = %d", len));
4031 SEEN(av); /* Will return if array not allocated nicely */
4035 return (SV *) av; /* No data follow if array is empty */
4038 * Now get each item in turn...
4041 for (i = 0; i < len; i++) {
4043 if (c == SX_IT_UNDEF) {
4044 TRACEME(("(#%d) undef item", i));
4045 continue; /* av_extend() already filled us with undef */
4048 (void) retrieve_other((stcxt_t *) 0); /* Will croak out */
4049 TRACEME(("(#%d) item", i));
4050 sv = retrieve(cxt); /* Retrieve item */
4053 if (av_store(av, i, sv) == 0)
4057 TRACEME(("ok (old_retrieve_array at 0x%"UVxf")", PTR2UV(av)));
4065 * Retrieve a whole hash table in pre-0.6 binary format.
4067 * Layout is SX_HASH <size> followed by each key/value pair, in random order.
4068 * Keys are stored as SX_KEY <length> <data>, the <data> section being omitted
4070 * Values are stored as SX_VALUE <object> or SX_VL_UNDEF for "holes".
4072 * When we come here, SX_HASH has been read already.
4074 static SV *old_retrieve_hash(stcxt_t *cxt)
4082 static SV *sv_h_undef = (SV *) 0; /* hv_store() bug */
4084 TRACEME(("old_retrieve_hash (#%d)", cxt->tagnum));
4087 * Read length, allocate table.
4091 TRACEME(("size = %d", len));
4093 SEEN(hv); /* Will return if table not allocated properly */
4095 return (SV *) hv; /* No data follow if table empty */
4098 * Now get each key/value pair in turn...
4101 for (i = 0; i < len; i++) {
4107 if (c == SX_VL_UNDEF) {
4108 TRACEME(("(#%d) undef value", i));
4110 * Due to a bug in hv_store(), it's not possible to pass
4111 * &PL_sv_undef to hv_store() as a value, otherwise the
4112 * associated key will not be creatable any more. -- RAM, 14/01/97
4115 sv_h_undef = newSVsv(&PL_sv_undef);
4116 sv = SvREFCNT_inc(sv_h_undef);
4117 } else if (c == SX_VALUE) {
4118 TRACEME(("(#%d) value", i));
4123 (void) retrieve_other((stcxt_t *) 0); /* Will croak out */
4127 * Since we're reading into kbuf, we must ensure we're not
4128 * recursing between the read and the hv_store() where it's used.
4129 * Hence the key comes after the value.
4134 (void) retrieve_other((stcxt_t *) 0); /* Will croak out */
4135 RLEN(size); /* Get key size */
4136 KBUFCHK(size); /* Grow hash key read pool if needed */
4139 kbuf[size] = '\0'; /* Mark string end, just in case */
4140 TRACEME(("(#%d) key '%s'", i, kbuf));
4143 * Enter key/value pair into hash table.
4146 if (hv_store(hv, kbuf, (U32) size, sv, 0) == 0)
4150 TRACEME(("ok (retrieve_hash at 0x%"UVxf")", PTR2UV(hv)));
4156 *** Retrieval engine.
4162 * Make sure the stored data we're trying to retrieve has been produced
4163 * on an ILP compatible system with the same byteorder. It croaks out in
4164 * case an error is detected. [ILP = integer-long-pointer sizes]
4165 * Returns null if error is detected, &PL_sv_undef otherwise.
4167 * Note that there's no byte ordering info emitted when network order was
4168 * used at store time.
4170 static SV *magic_check(stcxt_t *cxt)
4173 char byteorder[256];
4175 int use_network_order;
4177 int version_minor = 0;
4179 TRACEME(("magic_check"));
4182 * The "magic number" is only for files, not when freezing in memory.
4186 STRLEN len = sizeof(magicstr) - 1;
4189 READ(buf, len); /* Not null-terminated */
4190 buf[len] = '\0'; /* Is now */
4192 if (0 == strcmp(buf, magicstr))
4196 * Try to read more bytes to check for the old magic number, which
4200 old_len = sizeof(old_magicstr) - 1;
4201 READ(&buf[len], old_len - len);
4202 buf[old_len] = '\0'; /* Is now null-terminated */
4204 if (strcmp(buf, old_magicstr))
4205 CROAK(("File is not a perl storable"));
4210 * Starting with 0.6, the "use_network_order" byte flag is also used to
4211 * indicate the version number of the binary, and therefore governs the
4212 * setting of sv_retrieve_vtbl. See magic_write().
4215 GETMARK(use_network_order);
4216 version_major = use_network_order >> 1;
4217 cxt->retrieve_vtbl = version_major ? sv_retrieve : sv_old_retrieve;
4219 TRACEME(("magic_check: netorder = 0x%x", use_network_order));
4223 * Starting with 0.7 (binary major 2), a full byte is dedicated to the
4224 * minor version of the protocol. See magic_write().
4227 if (version_major > 1)
4228 GETMARK(version_minor);
4230 cxt->ver_major = version_major;
4231 cxt->ver_minor = version_minor;
4233 TRACEME(("binary image version is %d.%d", version_major, version_minor));
4236 * Inter-operability sanity check: we can't retrieve something stored
4237 * using a format more recent than ours, because we have no way to
4238 * know what has changed, and letting retrieval go would mean a probable
4239 * failure reporting a "corrupted" storable file.
4243 version_major > STORABLE_BIN_MAJOR ||
4244 (version_major == STORABLE_BIN_MAJOR &&
4245 version_minor > STORABLE_BIN_MINOR)
4247 CROAK(("Storable binary image v%d.%d more recent than I am (v%d.%d)",
4248 version_major, version_minor,
4249 STORABLE_BIN_MAJOR, STORABLE_BIN_MINOR));
4252 * If they stored using network order, there's no byte ordering
4253 * information to check.
4256 if (cxt->netorder = (use_network_order & 0x1))
4257 return &PL_sv_undef; /* No byte ordering info */
4259 sprintf(byteorder, "%lx", (unsigned long) BYTEORDER);
4261 READ(buf, c); /* Not null-terminated */
4262 buf[c] = '\0'; /* Is now */
4264 if (strcmp(buf, byteorder))
4265 CROAK(("Byte order is not compatible"));
4267 GETMARK(c); /* sizeof(int) */
4268 if ((int) c != sizeof(int))
4269 CROAK(("Integer size is not compatible"));
4271 GETMARK(c); /* sizeof(long) */
4272 if ((int) c != sizeof(long))
4273 CROAK(("Long integer size is not compatible"));
4275 GETMARK(c); /* sizeof(char *) */
4276 if ((int) c != sizeof(char *))
4277 CROAK(("Pointer integer size is not compatible"));
4279 if (version_major >= 2 && version_minor >= 2) {
4280 GETMARK(c); /* sizeof(NV) */
4281 if ((int) c != sizeof(NV))
4282 CROAK(("Double size is not compatible"));
4285 return &PL_sv_undef; /* OK */
4291 * Recursively retrieve objects from the specified file and return their
4292 * root SV (which may be an AV or an HV for what we care).
4293 * Returns null if there is a problem.
4295 static SV *retrieve(stcxt_t *cxt)
4301 TRACEME(("retrieve"));
4304 * Grab address tag which identifies the object if we are retrieving
4305 * an older format. Since the new binary format counts objects and no
4306 * longer explicitely tags them, we must keep track of the correspondance
4309 * The following section will disappear one day when the old format is
4310 * no longer supported, hence the final "goto" in the "if" block.
4313 if (cxt->hseen) { /* Retrieving old binary */
4315 if (cxt->netorder) {
4317 READ(&nettag, sizeof(I32)); /* Ordered sequence of I32 */
4318 tag = (stag_t) nettag;
4320 READ(&tag, sizeof(stag_t)); /* Original address of the SV */
4323 if (type == SX_OBJECT) {
4325 svh = hv_fetch(cxt->hseen, (char *) &tag, sizeof(tag), FALSE);
4327 CROAK(("Old tag 0x%x should have been mapped already", (unsigned)tag));
4328 tagn = SvIV(*svh); /* Mapped tag number computed earlier below */
4331 * The following code is common with the SX_OBJECT case below.
4334 svh = av_fetch(cxt->aseen, tagn, FALSE);
4336 CROAK(("Object #%d should have been retrieved already", (int)tagn));
4338 TRACEME(("has retrieved #%d at 0x%"UVxf, tagn, PTR2UV(sv)));
4339 SvREFCNT_inc(sv); /* One more reference to this same sv */
4340 return sv; /* The SV pointer where object was retrieved */
4344 * Map new object, but don't increase tagnum. This will be done
4345 * by each of the retrieve_* functions when they call SEEN().
4347 * The mapping associates the "tag" initially present with a unique
4348 * tag number. See test for SX_OBJECT above to see how this is perused.
4351 if (!hv_store(cxt->hseen, (char *) &tag, sizeof(tag),
4352 newSViv(cxt->tagnum), 0))
4359 * Regular post-0.6 binary format.
4365 TRACEME(("retrieve type = %d", type));
4368 * Are we dealing with an object we should have already retrieved?
4371 if (type == SX_OBJECT) {
4375 svh = av_fetch(cxt->aseen, tag, FALSE);
4377 CROAK(("Object #%d should have been retrieved already", (int)tag));
4379 TRACEME(("had retrieved #%d at 0x%"UVxf, tag, PTR2UV(sv)));
4380 SvREFCNT_inc(sv); /* One more reference to this same sv */
4381 return sv; /* The SV pointer where object was retrieved */
4384 first_time: /* Will disappear when support for old format is dropped */
4387 * Okay, first time through for this one.
4390 sv = RETRIEVE(cxt, type)(cxt);
4392 return (SV *) 0; /* Failed */
4395 * Old binary formats (pre-0.7).
4397 * Final notifications, ended by SX_STORED may now follow.
4398 * Currently, the only pertinent notification to apply on the
4399 * freshly retrieved object is either:
4400 * SX_CLASS <char-len> <classname> for short classnames.
4401 * SX_LG_CLASS <int-len> <classname> for larger one (rare!).
4402 * Class name is then read into the key buffer pool used by
4403 * hash table key retrieval.
4406 if (cxt->ver_major < 2) {
4407 while ((type = GETCHAR()) != SX_STORED) {
4411 GETMARK(len); /* Length coded on a single char */
4413 case SX_LG_CLASS: /* Length coded on a regular integer */
4418 return (SV *) 0; /* Failed */
4420 KBUFCHK(len); /* Grow buffer as necessary */
4423 kbuf[len] = '\0'; /* Mark string end */
4428 TRACEME(("ok (retrieved 0x%"UVxf", refcnt=%d, %s)", PTR2UV(sv),
4429 SvREFCNT(sv) - 1, sv_reftype(sv, FALSE)));
4437 * Retrieve data held in file and return the root object.
4438 * Common routine for pretrieve and mretrieve.
4440 static SV *do_retrieve(
4447 int is_tainted; /* Is input source tainted? */
4448 struct extendable msave; /* Where potentially valid mbuf is saved */
4450 TRACEME(("do_retrieve (optype = 0x%x)", optype));
4452 optype |= ST_RETRIEVE;
4455 * Sanity assertions for retrieve dispatch tables.
4458 ASSERT(sizeof(sv_old_retrieve) == sizeof(sv_retrieve),
4459 ("old and new retrieve dispatch table have same size"));
4460 ASSERT(sv_old_retrieve[SX_ERROR] == retrieve_other,
4461 ("SX_ERROR entry correctly initialized in old dispatch table"));
4462 ASSERT(sv_retrieve[SX_ERROR] == retrieve_other,
4463 ("SX_ERROR entry correctly initialized in new dispatch table"));
4466 * Workaround for CROAK leak: if they enter with a "dirty" context,
4467 * free up memory for them now.
4474 * Now that STORABLE_xxx hooks exist, it is possible that they try to
4475 * re-enter retrieve() via the hooks.
4479 cxt = allocate_context(cxt);
4483 ASSERT(cxt->entry == 1, ("starting new recursion"));
4484 ASSERT(!cxt->s_dirty, ("clean context"));
4489 * Data is loaded into the memory buffer when f is NULL, unless `in' is
4490 * also NULL, in which case we're expecting the data to already lie
4491 * in the buffer (dclone case).
4494 KBUFINIT(); /* Allocate hash key reading pool once */
4497 StructCopy(&cxt->membuf, &msave, struct extendable);
4503 * Magic number verifications.
4505 * This needs to be done before calling init_retrieve_context()
4506 * since the format indication in the file are necessary to conduct
4507 * some of the initializations.
4510 cxt->fio = f; /* Where I/O are performed */
4512 if (!magic_check(cxt))
4513 CROAK(("Magic number checking on storable %s failed",
4514 cxt->fio ? "file" : "string"));
4516 TRACEME(("data stored in %s format",
4517 cxt->netorder ? "net order" : "native"));
4520 * Check whether input source is tainted, so that we don't wrongly
4521 * taint perfectly good values...
4523 * We assume file input is always tainted. If both `f' and `in' are
4524 * NULL, then we come from dclone, and tainted is already filled in
4525 * the context. That's a kludge, but the whole dclone() thing is
4526 * already quite a kludge anyway! -- RAM, 15/09/2000.
4529 is_tainted = f ? 1 : (in ? SvTAINTED(in) : cxt->s_tainted);
4530 TRACEME(("input source is %s", is_tainted ? "tainted" : "trusted"));
4531 init_retrieve_context(cxt, optype, is_tainted);
4533 ASSERT(is_retrieving(), ("within retrieve operation"));
4535 sv = retrieve(cxt); /* Recursively retrieve object, get root SV */
4542 StructCopy(&msave, &cxt->membuf, struct extendable);
4545 * The "root" context is never freed.
4548 clean_retrieve_context(cxt);
4549 if (cxt->prev) /* This context was stacked */
4550 free_context(cxt); /* It was not the "root" context */
4553 * Prepare returned value.
4557 TRACEME(("retrieve ERROR"));
4558 return &PL_sv_undef; /* Something went wrong, return undef */
4561 TRACEME(("retrieve got %s(0x%"UVxf")",
4562 sv_reftype(sv, FALSE), PTR2UV(sv)));
4565 * Backward compatibility with Storable-0.5@9 (which we know we
4566 * are retrieving if hseen is non-null): don't create an extra RV
4567 * for objects since we special-cased it at store time.
4569 * Build a reference to the SV returned by pretrieve even if it is
4570 * already one and not a scalar, for consistency reasons.
4572 * NB: although context might have been cleaned, the value of `cxt->hseen'
4573 * remains intact, and can be used as a flag.
4576 if (cxt->hseen) { /* Was not handling overloading by then */
4578 if (sv_type(sv) == svis_REF && (rv = SvRV(sv)) && SvOBJECT(rv))
4583 * If reference is overloaded, restore behaviour.
4585 * NB: minor glitch here: normally, overloaded refs are stored specially
4586 * so that we can croak when behaviour cannot be re-installed, and also
4587 * avoid testing for overloading magic at each reference retrieval.
4589 * Unfortunately, the root reference is implicitely stored, so we must
4590 * check for possible overloading now. Furthermore, if we don't restore
4591 * overloading, we cannot croak as if the original ref was, because we
4592 * have no way to determine whether it was an overloaded ref or not in
4595 * It's a pity that overloading magic is attached to the rv, and not to
4596 * the underlying sv as blessing is.
4600 HV *stash = (HV *) SvSTASH (sv);
4601 SV *rv = newRV_noinc(sv);
4602 if (stash && Gv_AMG(stash)) {
4604 TRACEME(("restored overloading on root reference"));
4609 return newRV_noinc(sv);
4615 * Retrieve data held in file and return the root object, undef on error.
4617 SV *pretrieve(PerlIO *f)
4619 TRACEME(("pretrieve"));
4620 return do_retrieve(f, Nullsv, 0);
4626 * Retrieve data held in scalar and return the root object, undef on error.
4628 SV *mretrieve(SV *sv)
4630 TRACEME(("mretrieve"));
4631 return do_retrieve((PerlIO*) 0, sv, 0);
4641 * Deep clone: returns a fresh copy of the original referenced SV tree.
4643 * This is achieved by storing the object in memory and restoring from
4644 * there. Not that efficient, but it should be faster than doing it from
4651 stcxt_t *real_context;
4654 TRACEME(("dclone"));
4657 * Workaround for CROAK leak: if they enter with a "dirty" context,
4658 * free up memory for them now.
4665 * do_store() optimizes for dclone by not freeing its context, should
4666 * we need to allocate one because we're deep cloning from a hook.
4669 if (!do_store((PerlIO*) 0, sv, ST_CLONE, FALSE, (SV**) 0))
4670 return &PL_sv_undef; /* Error during store */
4673 * Because of the above optimization, we have to refresh the context,
4674 * since a new one could have been allocated and stacked by do_store().
4677 { dSTCXT; real_context = cxt; } /* Sub-block needed for macro */
4678 cxt = real_context; /* And we need this temporary... */
4681 * Now, `cxt' may refer to a new context.
4684 ASSERT(!cxt->s_dirty, ("clean context"));
4685 ASSERT(!cxt->entry, ("entry will not cause new context allocation"));
4688 TRACEME(("dclone stored %d bytes", size));
4692 * Since we're passing do_retrieve() both a NULL file and sv, we need
4693 * to pre-compute the taintedness of the input by setting cxt->tainted
4694 * to whatever state our own input string was. -- RAM, 15/09/2000
4696 * do_retrieve() will free non-root context.
4699 cxt->s_tainted = SvTAINTED(sv);
4700 out = do_retrieve((PerlIO*) 0, Nullsv, ST_CLONE);
4702 TRACEME(("dclone returns 0x%"UVxf, PTR2UV(out)));
4712 * The Perl IO GV object distinguishes between input and output for sockets
4713 * but not for plain files. To allow Storable to transparently work on
4714 * plain files and sockets transparently, we have to ask xsubpp to fetch the
4715 * right object for us. Hence the OutputStream and InputStream declarations.
4717 * Before perl 5.004_05, those entries in the standard typemap are not
4718 * defined in perl include files, so we do that here.
4721 #ifndef OutputStream
4722 #define OutputStream PerlIO *
4723 #define InputStream PerlIO *
4724 #endif /* !OutputStream */
4726 MODULE = Storable PACKAGE = Storable
4764 last_op_in_netorder()