2 * Store and retrieve mechanism.
6 * $Id: Storable.xs,v 1.0.1.10 2001/08/28 21:52:14 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.
17 #include <patchlevel.h> /* Perl's one, needed since 5.6 */
22 #define DEBUGME /* Debug mode, turns assertions on as well */
23 #define DASSERT /* Assertion mode */
26 #if 0 /* On NetWare USE_PERLIO is not used */
27 #define DEBUGME /* Debug mode, turns assertions on as well */
28 #define DASSERT /* Assertion mode */
33 * Pre PerlIO time when none of USE_PERLIO and PERLIO_IS_STDIO is defined
34 * Provide them with the necessary defines so they can build with pre-5.004.
37 #ifndef PERLIO_IS_STDIO
39 #define PerlIO_getc(x) getc(x)
40 #define PerlIO_putc(f,x) putc(x,f)
41 #define PerlIO_read(x,y,z) fread(y,1,z,x)
42 #define PerlIO_write(x,y,z) fwrite(y,1,z,x)
43 #define PerlIO_stdoutf printf
44 #endif /* PERLIO_IS_STDIO */
45 #endif /* USE_PERLIO */
48 * Earlier versions of perl might be used, we can't assume they have the latest!
51 #ifndef PERL_VERSION /* For perls < 5.6 */
52 #define PERL_VERSION PATCHLEVEL
54 #define newRV_noinc(sv) ((Sv = newRV(sv)), --SvREFCNT(SvRV(Sv)), Sv)
56 #if (PATCHLEVEL <= 4) /* Older perls (<= 5.004) lack PL_ namespace */
57 #define PL_sv_yes sv_yes
58 #define PL_sv_no sv_no
59 #define PL_sv_undef sv_undef
60 #if (SUBVERSION <= 4) /* 5.004_04 has been reported to lack newSVpvn */
61 #define newSVpvn newSVpv
63 #endif /* PATCHLEVEL <= 4 */
64 #ifndef HvSHAREKEYS_off
65 #define HvSHAREKEYS_off(hv) /* Ignore */
67 #ifndef AvFILLp /* Older perls (<=5.003) lack AvFILLp */
68 #define AvFILLp AvFILL
70 typedef double NV; /* Older perls lack the NV type */
71 #define IVdf "ld" /* Various printf formats for Perl types */
75 #define INT2PTR(t,v) (t)(IV)(v)
76 #define PTR2UV(v) (unsigned long)(v)
77 #endif /* PERL_VERSION -- perls < 5.6 */
79 #ifndef NVef /* The following were not part of perl 5.6 */
80 #if defined(USE_LONG_DOUBLE) && \
81 defined(HAS_LONG_DOUBLE) && defined(PERL_PRIfldbl)
82 #define NVef PERL_PRIeldbl
83 #define NVff PERL_PRIfldbl
84 #define NVgf PERL_PRIgldbl
99 * TRACEME() will only output things when the $Storable::DEBUGME is true.
104 if (SvTRUE(perl_get_sv("Storable::DEBUGME", TRUE))) \
105 { PerlIO_stdoutf x; PerlIO_stdoutf("\n"); } \
112 #define ASSERT(x,y) \
115 PerlIO_stdoutf("ASSERT FAILED (\"%s\", line %d): ", \
116 __FILE__, __LINE__); \
117 PerlIO_stdoutf y; PerlIO_stdoutf("\n"); \
128 #define C(x) ((char) (x)) /* For markers with dynamic retrieval handling */
130 #define SX_OBJECT C(0) /* Already stored object */
131 #define SX_LSCALAR C(1) /* Scalar (large binary) follows (length, data) */
132 #define SX_ARRAY C(2) /* Array forthcominng (size, item list) */
133 #define SX_HASH C(3) /* Hash forthcoming (size, key/value pair list) */
134 #define SX_REF C(4) /* Reference to object forthcoming */
135 #define SX_UNDEF C(5) /* Undefined scalar */
136 #define SX_INTEGER C(6) /* Integer forthcoming */
137 #define SX_DOUBLE C(7) /* Double forthcoming */
138 #define SX_BYTE C(8) /* (signed) byte forthcoming */
139 #define SX_NETINT C(9) /* Integer in network order forthcoming */
140 #define SX_SCALAR C(10) /* Scalar (binary, small) follows (length, data) */
141 #define SX_TIED_ARRAY C(11) /* Tied array forthcoming */
142 #define SX_TIED_HASH C(12) /* Tied hash forthcoming */
143 #define SX_TIED_SCALAR C(13) /* Tied scalar forthcoming */
144 #define SX_SV_UNDEF C(14) /* Perl's immortal PL_sv_undef */
145 #define SX_SV_YES C(15) /* Perl's immortal PL_sv_yes */
146 #define SX_SV_NO C(16) /* Perl's immortal PL_sv_no */
147 #define SX_BLESS C(17) /* Object is blessed */
148 #define SX_IX_BLESS C(18) /* Object is blessed, classname given by index */
149 #define SX_HOOK C(19) /* Stored via hook, user-defined */
150 #define SX_OVERLOAD C(20) /* Overloaded reference */
151 #define SX_TIED_KEY C(21) /* Tied magic key forthcoming */
152 #define SX_TIED_IDX C(22) /* Tied magic index forthcoming */
153 #define SX_UTF8STR C(23) /* UTF-8 string forthcoming (small) */
154 #define SX_LUTF8STR C(24) /* UTF-8 string forthcoming (large) */
155 #define SX_FLAG_HASH C(25) /* Hash with flags forthcoming (size, flags, key/flags/value triplet list) */
156 #define SX_ERROR C(26) /* Error */
159 * Those are only used to retrieve "old" pre-0.6 binary images.
161 #define SX_ITEM 'i' /* An array item introducer */
162 #define SX_IT_UNDEF 'I' /* Undefined array item */
163 #define SX_KEY 'k' /* A hash key introducer */
164 #define SX_VALUE 'v' /* A hash value introducer */
165 #define SX_VL_UNDEF 'V' /* Undefined hash value */
168 * Those are only used to retrieve "old" pre-0.7 binary images
171 #define SX_CLASS 'b' /* Object is blessed, class name length <255 */
172 #define SX_LG_CLASS 'B' /* Object is blessed, class name length >255 */
173 #define SX_STORED 'X' /* End of object */
176 * Limits between short/long length representation.
179 #define LG_SCALAR 255 /* Large scalar length limit */
180 #define LG_BLESS 127 /* Large classname bless limit */
186 #define ST_STORE 0x1 /* Store operation */
187 #define ST_RETRIEVE 0x2 /* Retrieval operation */
188 #define ST_CLONE 0x4 /* Deep cloning operation */
191 * The following structure is used for hash table key retrieval. Since, when
192 * retrieving objects, we'll be facing blessed hash references, it's best
193 * to pre-allocate that buffer once and resize it as the need arises, never
194 * freeing it (keys will be saved away someplace else anyway, so even large
195 * keys are not enough a motivation to reclaim that space).
197 * This structure is also used for memory store/retrieve operations which
198 * happen in a fixed place before being malloc'ed elsewhere if persistency
199 * is required. Hence the aptr pointer.
202 char *arena; /* Will hold hash key strings, resized as needed */
203 STRLEN asiz; /* Size of aforementionned buffer */
204 char *aptr; /* Arena pointer, for in-place read/write ops */
205 char *aend; /* First invalid address */
210 * A hash table records the objects which have already been stored.
211 * Those are referred to as SX_OBJECT in the file, and their "tag" (i.e.
212 * an arbitrary sequence number) is used to identify them.
215 * An array table records the objects which have already been retrieved,
216 * as seen by the tag determind by counting the objects themselves. The
217 * reference to that retrieved object is kept in the table, and is returned
218 * when an SX_OBJECT is found bearing that same tag.
220 * The same processing is used to record "classname" for blessed objects:
221 * indexing by a hash at store time, and via an array at retrieve time.
224 typedef unsigned long stag_t; /* Used by pre-0.6 binary format */
227 * The following "thread-safe" related defines were contributed by
228 * Murray Nesbitt <murray@activestate.com> and integrated by RAM, who
229 * only renamed things a little bit to ensure consistency with surrounding
230 * code. -- RAM, 14/09/1999
232 * The original patch suffered from the fact that the stcxt_t structure
233 * was global. Murray tried to minimize the impact on the code as much as
236 * Starting with 0.7, Storable can be re-entrant, via the STORABLE_xxx hooks
237 * on objects. Therefore, the notion of context needs to be generalized,
241 #define MY_VERSION "Storable(" XS_VERSION ")"
245 * Conditional UTF8 support.
249 #define STORE_UTF8STR(pv, len) STORE_PV_LEN(pv, len, SX_UTF8STR, SX_LUTF8STR)
250 #define HAS_UTF8_SCALARS
252 #define HAS_UTF8_HASHES
255 /* 5.6 perl has utf8 scalars but not hashes */
259 #define STORE_UTF8STR(pv, len) CROAK(("panic: storing UTF8 in non-UTF8 perl"))
262 #define UTF8_CROAK() CROAK(("Cannot retrieve UTF8 data in non-UTF8 perl"))
265 #ifdef HvPLACEHOLDERS
266 #define HAS_RESTRICTED_HASHES
268 #define HVhek_PLACEHOLD 0x200
269 #define RESTRICTED_HASH_CROAK() CROAK(("Cannot retrieve restricted hash"))
273 #define HAS_HASH_KEY_FLAGS
277 * Fields s_tainted and s_dirty are prefixed with s_ because Perl's include
278 * files remap tainted and dirty when threading is enabled. That's bad for
279 * perl to remap such common words. -- RAM, 29/09/00
282 typedef struct stcxt {
283 int entry; /* flags recursion */
284 int optype; /* type of traversal operation */
285 HV *hseen; /* which objects have been seen, store time */
286 AV *hook_seen; /* which SVs were returned by STORABLE_freeze() */
287 AV *aseen; /* which objects have been seen, retrieve time */
288 HV *hclass; /* which classnames have been seen, store time */
289 AV *aclass; /* which classnames have been seen, retrieve time */
290 HV *hook; /* cache for hook methods per class name */
291 IV tagnum; /* incremented at store time for each seen object */
292 IV classnum; /* incremented at store time for each seen classname */
293 int netorder; /* true if network order used */
294 int s_tainted; /* true if input source is tainted, at retrieve time */
295 int forgive_me; /* whether to be forgiving... */
296 int canonical; /* whether to store hashes sorted by key */
297 #ifndef HAS_RESTRICTED_HASHES
298 int derestrict; /* whether to downgrade restrcted hashes */
301 int use_bytes; /* whether to bytes-ify utf8 */
303 int accept_future_minor; /* croak immediately on future minor versions? */
304 int s_dirty; /* context is dirty due to CROAK() -- can be cleaned */
305 int membuf_ro; /* true means membuf is read-only and msaved is rw */
306 struct extendable keybuf; /* for hash key retrieval */
307 struct extendable membuf; /* for memory store/retrieve operations */
308 struct extendable msaved; /* where potentially valid mbuf is saved */
309 PerlIO *fio; /* where I/O are performed, NULL for memory */
310 int ver_major; /* major of version for retrieved object */
311 int ver_minor; /* minor of version for retrieved object */
312 SV *(**retrieve_vtbl)(); /* retrieve dispatch table */
313 SV *prev; /* contexts chained backwards in real recursion */
314 SV *my_sv; /* the blessed scalar who's SvPVX() I am */
317 #define NEW_STORABLE_CXT_OBJ(cxt) \
319 SV *self = newSV(sizeof(stcxt_t) - 1); \
320 SV *my_sv = newRV_noinc(self); \
321 sv_bless(my_sv, gv_stashpv("Storable::Cxt", TRUE)); \
322 cxt = (stcxt_t *)SvPVX(self); \
323 Zero(cxt, 1, stcxt_t); \
324 cxt->my_sv = my_sv; \
327 #if defined(MULTIPLICITY) || defined(PERL_OBJECT) || defined(PERL_CAPI)
329 #if (PATCHLEVEL <= 4) && (SUBVERSION < 68)
331 SV *perinterp_sv = perl_get_sv(MY_VERSION, FALSE)
332 #else /* >= perl5.004_68 */
334 SV *perinterp_sv = *hv_fetch(PL_modglobal, \
335 MY_VERSION, sizeof(MY_VERSION)-1, TRUE)
336 #endif /* < perl5.004_68 */
338 #define dSTCXT_PTR(T,name) \
339 T name = ((perinterp_sv && SvIOK(perinterp_sv) && SvIVX(perinterp_sv) \
340 ? (T)SvPVX(SvRV(INT2PTR(SV*,SvIVX(perinterp_sv)))) : (T) 0))
343 dSTCXT_PTR(stcxt_t *, cxt)
347 NEW_STORABLE_CXT_OBJ(cxt); \
348 sv_setiv(perinterp_sv, PTR2IV(cxt->my_sv))
350 #define SET_STCXT(x) \
353 sv_setiv(perinterp_sv, PTR2IV(x->my_sv)); \
356 #else /* !MULTIPLICITY && !PERL_OBJECT && !PERL_CAPI */
358 static stcxt_t Context;
359 static stcxt_t *Context_ptr = &Context;
360 #define dSTCXT stcxt_t *cxt = Context_ptr
363 NEW_STORABLE_CXT_OBJ(cxt)
365 #define SET_STCXT(x) Context_ptr = x
367 #endif /* MULTIPLICITY || PERL_OBJECT || PERL_CAPI */
371 * Croaking implies a memory leak, since we don't use setjmp/longjmp
372 * to catch the exit and free memory used during store or retrieve
373 * operations. This is not too difficult to fix, but I need to understand
374 * how Perl does it, and croaking is exceptional anyway, so I lack the
375 * motivation to do it.
377 * The current workaround is to mark the context as dirty when croaking,
378 * so that data structures can be freed whenever we renter Storable code
379 * (but only *then*: it's a workaround, not a fix).
381 * This is also imperfect, because we don't really know how far they trapped
382 * the croak(), and when we were recursing, we won't be able to clean anything
383 * but the topmost context stacked.
386 #define CROAK(x) STMT_START { cxt->s_dirty = 1; croak x; } STMT_END
389 * End of "thread-safe" related definitions.
395 * Keep only the low 32 bits of a pointer (used for tags, which are not
400 #define LOW_32BITS(x) ((I32) (x))
402 #define LOW_32BITS(x) ((I32) ((unsigned long) (x) & 0xffffffffUL))
408 * Hack for Crays, where sizeof(I32) == 8, and which are big-endians.
409 * Used in the WLEN and RLEN macros.
413 #define oI(x) ((I32 *) ((char *) (x) + 4))
414 #define oS(x) ((x) - 4)
415 #define oC(x) (x = 0)
424 * key buffer handling
426 #define kbuf (cxt->keybuf).arena
427 #define ksiz (cxt->keybuf).asiz
431 TRACEME(("** allocating kbuf of 128 bytes")); \
432 New(10003, kbuf, 128, char); \
439 TRACEME(("** extending kbuf to %d bytes (had %d)", x+1, ksiz)); \
440 Renew(kbuf, x+1, char); \
446 * memory buffer handling
448 #define mbase (cxt->membuf).arena
449 #define msiz (cxt->membuf).asiz
450 #define mptr (cxt->membuf).aptr
451 #define mend (cxt->membuf).aend
453 #define MGROW (1 << 13)
454 #define MMASK (MGROW - 1)
456 #define round_mgrow(x) \
457 ((unsigned long) (((unsigned long) (x) + MMASK) & ~MMASK))
458 #define trunc_int(x) \
459 ((unsigned long) ((unsigned long) (x) & ~(sizeof(int)-1)))
460 #define int_aligned(x) \
461 ((unsigned long) (x) == trunc_int(x))
463 #define MBUF_INIT(x) \
466 TRACEME(("** allocating mbase of %d bytes", MGROW)); \
467 New(10003, mbase, MGROW, char); \
474 mend = mbase + msiz; \
477 #define MBUF_TRUNC(x) mptr = mbase + x
478 #define MBUF_SIZE() (mptr - mbase)
484 * Those macros are used in do_retrieve() to save the current memory
485 * buffer into cxt->msaved, before MBUF_LOAD() can be used to retrieve
486 * data from a string.
488 #define MBUF_SAVE_AND_LOAD(in) \
490 ASSERT(!cxt->membuf_ro, ("mbase not already saved")); \
491 cxt->membuf_ro = 1; \
492 TRACEME(("saving mbuf")); \
493 StructCopy(&cxt->membuf, &cxt->msaved, struct extendable); \
497 #define MBUF_RESTORE() \
499 ASSERT(cxt->membuf_ro, ("mbase is read-only")); \
500 cxt->membuf_ro = 0; \
501 TRACEME(("restoring mbuf")); \
502 StructCopy(&cxt->msaved, &cxt->membuf, struct extendable); \
506 * Use SvPOKp(), because SvPOK() fails on tainted scalars.
507 * See store_scalar() for other usage of this workaround.
509 #define MBUF_LOAD(v) \
511 ASSERT(cxt->membuf_ro, ("mbase is read-only")); \
513 CROAK(("Not a scalar string")); \
514 mptr = mbase = SvPV(v, msiz); \
515 mend = mbase + msiz; \
518 #define MBUF_XTEND(x) \
520 int nsz = (int) round_mgrow((x)+msiz); \
521 int offset = mptr - mbase; \
522 ASSERT(!cxt->membuf_ro, ("mbase is not read-only")); \
523 TRACEME(("** extending mbase from %d to %d bytes (wants %d new)", \
525 Renew(mbase, nsz, char); \
527 mptr = mbase + offset; \
528 mend = mbase + nsz; \
531 #define MBUF_CHK(x) \
533 if ((mptr + (x)) > mend) \
537 #define MBUF_GETC(x) \
540 x = (int) (unsigned char) *mptr++; \
546 #define MBUF_GETINT(x) \
549 if ((mptr + 4) <= mend) { \
550 memcpy(oI(&x), mptr, 4); \
556 #define MBUF_GETINT(x) \
558 if ((mptr + sizeof(int)) <= mend) { \
559 if (int_aligned(mptr)) \
562 memcpy(&x, mptr, sizeof(int)); \
563 mptr += sizeof(int); \
569 #define MBUF_READ(x,s) \
571 if ((mptr + (s)) <= mend) { \
572 memcpy(x, mptr, s); \
578 #define MBUF_SAFEREAD(x,s,z) \
580 if ((mptr + (s)) <= mend) { \
581 memcpy(x, mptr, s); \
589 #define MBUF_PUTC(c) \
592 *mptr++ = (char) c; \
595 *mptr++ = (char) c; \
600 #define MBUF_PUTINT(i) \
603 memcpy(mptr, oI(&i), 4); \
607 #define MBUF_PUTINT(i) \
609 MBUF_CHK(sizeof(int)); \
610 if (int_aligned(mptr)) \
613 memcpy(mptr, &i, sizeof(int)); \
614 mptr += sizeof(int); \
618 #define MBUF_WRITE(x,s) \
621 memcpy(mptr, x, s); \
626 * Possible return values for sv_type().
630 #define svis_SCALAR 1
634 #define svis_TIED_ITEM 5
641 #define SHF_TYPE_MASK 0x03
642 #define SHF_LARGE_CLASSLEN 0x04
643 #define SHF_LARGE_STRLEN 0x08
644 #define SHF_LARGE_LISTLEN 0x10
645 #define SHF_IDX_CLASSNAME 0x20
646 #define SHF_NEED_RECURSE 0x40
647 #define SHF_HAS_LIST 0x80
650 * Types for SX_HOOK (last 2 bits in flags).
656 #define SHT_EXTRA 3 /* Read extra byte for type */
659 * The following are held in the "extra byte"...
662 #define SHT_TSCALAR 4 /* 4 + 0 -- tied scalar */
663 #define SHT_TARRAY 5 /* 4 + 1 -- tied array */
664 #define SHT_THASH 6 /* 4 + 2 -- tied hash */
667 * per hash flags for flagged hashes
670 #define SHV_RESTRICTED 0x01
673 * per key flags for flagged hashes
676 #define SHV_K_UTF8 0x01
677 #define SHV_K_WASUTF8 0x02
678 #define SHV_K_LOCKED 0x04
679 #define SHV_K_ISSV 0x08
680 #define SHV_K_PLACEHOLDER 0x10
683 * Before 0.6, the magic string was "perl-store" (binary version number 0).
685 * Since 0.6 introduced many binary incompatibilities, the magic string has
686 * been changed to "pst0" to allow an old image to be properly retrieved by
687 * a newer Storable, but ensure a newer image cannot be retrieved with an
690 * At 0.7, objects are given the ability to serialize themselves, and the
691 * set of markers is extended, backward compatibility is not jeopardized,
692 * so the binary version number could have remained unchanged. To correctly
693 * spot errors if a file making use of 0.7-specific extensions is given to
694 * 0.6 for retrieval, the binary version was moved to "2". And I'm introducing
695 * a "minor" version, to better track this kind of evolution from now on.
698 static const char old_magicstr[] = "perl-store"; /* Magic number before 0.6 */
699 static const char magicstr[] = "pst0"; /* Used as a magic number */
701 #define MAGICSTR_BYTES 'p','s','t','0'
702 #define OLDMAGICSTR_BYTES 'p','e','r','l','-','s','t','o','r','e'
704 #if BYTEORDER == 0x1234
705 #define BYTEORDER_BYTES '1','2','3','4'
707 #if BYTEORDER == 0x12345678
708 #define BYTEORDER_BYTES '1','2','3','4','5','6','7','8'
710 #if BYTEORDER == 0x87654321
711 #define BYTEORDER_BYTES '8','7','6','5','4','3','2','1'
713 #if BYTEORDER == 0x4321
714 #define BYTEORDER_BYTES '4','3','2','1'
716 #error Unknown byteoder. Please append your byteorder to Storable.xs
722 static const char byteorderstr[] = {BYTEORDER_BYTES, 0};
724 #define STORABLE_BIN_MAJOR 2 /* Binary major "version" */
725 #define STORABLE_BIN_MINOR 5 /* Binary minor "version" */
727 /* If we aren't 5.7.3 or later, we won't be writing out files that use the
728 * new flagged hash introdued in 2.5, so put 2.4 in the binary header to
729 * maximise ease of interoperation with older Storables.
730 * Could we write 2.3s if we're on 5.005_03? NWC
732 #if (PATCHLEVEL <= 6)
733 #define STORABLE_BIN_WRITE_MINOR 4
736 * As of perl 5.7.3, utf8 hash key is introduced.
737 * So this must change -- dankogai
739 #define STORABLE_BIN_WRITE_MINOR 5
740 #endif /* (PATCHLEVEL <= 6) */
743 * Useful store shortcuts...
750 else if (PerlIO_putc(cxt->fio, x) == EOF) \
754 #define WRITE_I32(x) \
756 ASSERT(sizeof(x) == sizeof(I32), ("writing an I32")); \
759 else if (PerlIO_write(cxt->fio, oI(&x), oS(sizeof(x))) != oS(sizeof(x))) \
766 if (cxt->netorder) { \
767 int y = (int) htonl(x); \
770 else if (PerlIO_write(cxt->fio,oI(&y),oS(sizeof(y))) != oS(sizeof(y))) \
775 else if (PerlIO_write(cxt->fio,oI(&x),oS(sizeof(x))) != oS(sizeof(x))) \
780 #define WLEN(x) WRITE_I32(x)
787 else if (PerlIO_write(cxt->fio, x, y) != y) \
791 #define STORE_PV_LEN(pv, len, small, large) \
793 if (len <= LG_SCALAR) { \
794 unsigned char clen = (unsigned char) len; \
806 #define STORE_SCALAR(pv, len) STORE_PV_LEN(pv, len, SX_SCALAR, SX_LSCALAR)
809 * Store undef in arrays and hashes without recursing through store().
811 #define STORE_UNDEF() \
818 * Useful retrieve shortcuts...
822 (cxt->fio ? PerlIO_getc(cxt->fio) : (mptr >= mend ? EOF : (int) *mptr++))
828 else if ((int) (x = PerlIO_getc(cxt->fio)) == EOF) \
832 #define READ_I32(x) \
834 ASSERT(sizeof(x) == sizeof(I32), ("reading an I32")); \
838 else if (PerlIO_read(cxt->fio, oI(&x), oS(sizeof(x))) != oS(sizeof(x))) \
848 else if (PerlIO_read(cxt->fio, oI(&x), oS(sizeof(x))) != oS(sizeof(x))) \
851 x = (int) ntohl(x); \
854 #define RLEN(x) READ_I32(x)
861 else if (PerlIO_read(cxt->fio, x, y) != y) \
865 #define SAFEREAD(x,y,z) \
868 MBUF_SAFEREAD(x,y,z); \
869 else if (PerlIO_read(cxt->fio, x, y) != y) { \
876 * This macro is used at retrieve time, to remember where object 'y', bearing a
877 * given tag 'tagnum', has been retrieved. Next time we see an SX_OBJECT marker,
878 * we'll therefore know where it has been retrieved and will be able to
879 * share the same reference, as in the original stored memory image.
881 * We also need to bless objects ASAP for hooks (which may compute "ref $x"
882 * on the objects given to STORABLE_thaw and expect that to be defined), and
883 * also for overloaded objects (for which we might not find the stash if the
884 * object is not blessed yet--this might occur for overloaded objects that
885 * refer to themselves indirectly: if we blessed upon return from a sub
886 * retrieve(), the SX_OBJECT marker we'd found could not have overloading
887 * restored on it because the underlying object would not be blessed yet!).
889 * To achieve that, the class name of the last retrieved object is passed down
890 * recursively, and the first SEEN() call for which the class name is not NULL
891 * will bless the object.
897 if (av_store(cxt->aseen, cxt->tagnum++, SvREFCNT_inc(y)) == 0) \
899 TRACEME(("aseen(#%d) = 0x%"UVxf" (refcnt=%d)", cxt->tagnum-1, \
900 PTR2UV(y), SvREFCNT(y)-1)); \
902 BLESS((SV *) (y), c); \
906 * Bless `s' in `p', via a temporary reference, required by sv_bless().
912 TRACEME(("blessing 0x%"UVxf" in %s", PTR2UV(s), (p))); \
913 stash = gv_stashpv((p), TRUE); \
914 ref = newRV_noinc(s); \
915 (void) sv_bless(ref, stash); \
921 static SV *retrieve(stcxt_t *cxt, char *cname);
924 * Dynamic dispatching table for SV store.
927 static int store_ref(stcxt_t *cxt, SV *sv);
928 static int store_scalar(stcxt_t *cxt, SV *sv);
929 static int store_array(stcxt_t *cxt, AV *av);
930 static int store_hash(stcxt_t *cxt, HV *hv);
931 static int store_tied(stcxt_t *cxt, SV *sv);
932 static int store_tied_item(stcxt_t *cxt, SV *sv);
933 static int store_other(stcxt_t *cxt, SV *sv);
934 static int store_blessed(stcxt_t *cxt, SV *sv, int type, HV *pkg);
936 static int (*sv_store[])(stcxt_t *cxt, SV *sv) = {
937 store_ref, /* svis_REF */
938 store_scalar, /* svis_SCALAR */
939 (int (*)(stcxt_t *cxt, SV *sv)) store_array, /* svis_ARRAY */
940 (int (*)(stcxt_t *cxt, SV *sv)) store_hash, /* svis_HASH */
941 store_tied, /* svis_TIED */
942 store_tied_item, /* svis_TIED_ITEM */
943 store_other, /* svis_OTHER */
946 #define SV_STORE(x) (*sv_store[x])
949 * Dynamic dispatching tables for SV retrieval.
952 static SV *retrieve_lscalar(stcxt_t *cxt, char *cname);
953 static SV *retrieve_lutf8str(stcxt_t *cxt, char *cname);
954 static SV *old_retrieve_array(stcxt_t *cxt, char *cname);
955 static SV *old_retrieve_hash(stcxt_t *cxt, char *cname);
956 static SV *retrieve_ref(stcxt_t *cxt, char *cname);
957 static SV *retrieve_undef(stcxt_t *cxt, char *cname);
958 static SV *retrieve_integer(stcxt_t *cxt, char *cname);
959 static SV *retrieve_double(stcxt_t *cxt, char *cname);
960 static SV *retrieve_byte(stcxt_t *cxt, char *cname);
961 static SV *retrieve_netint(stcxt_t *cxt, char *cname);
962 static SV *retrieve_scalar(stcxt_t *cxt, char *cname);
963 static SV *retrieve_utf8str(stcxt_t *cxt, char *cname);
964 static SV *retrieve_tied_array(stcxt_t *cxt, char *cname);
965 static SV *retrieve_tied_hash(stcxt_t *cxt, char *cname);
966 static SV *retrieve_tied_scalar(stcxt_t *cxt, char *cname);
967 static SV *retrieve_other(stcxt_t *cxt, char *cname);
969 static SV *(*sv_old_retrieve[])(stcxt_t *cxt, char *cname) = {
970 0, /* SX_OBJECT -- entry unused dynamically */
971 retrieve_lscalar, /* SX_LSCALAR */
972 old_retrieve_array, /* SX_ARRAY -- for pre-0.6 binaries */
973 old_retrieve_hash, /* SX_HASH -- for pre-0.6 binaries */
974 retrieve_ref, /* SX_REF */
975 retrieve_undef, /* SX_UNDEF */
976 retrieve_integer, /* SX_INTEGER */
977 retrieve_double, /* SX_DOUBLE */
978 retrieve_byte, /* SX_BYTE */
979 retrieve_netint, /* SX_NETINT */
980 retrieve_scalar, /* SX_SCALAR */
981 retrieve_tied_array, /* SX_ARRAY */
982 retrieve_tied_hash, /* SX_HASH */
983 retrieve_tied_scalar, /* SX_SCALAR */
984 retrieve_other, /* SX_SV_UNDEF not supported */
985 retrieve_other, /* SX_SV_YES not supported */
986 retrieve_other, /* SX_SV_NO not supported */
987 retrieve_other, /* SX_BLESS not supported */
988 retrieve_other, /* SX_IX_BLESS not supported */
989 retrieve_other, /* SX_HOOK not supported */
990 retrieve_other, /* SX_OVERLOADED not supported */
991 retrieve_other, /* SX_TIED_KEY not supported */
992 retrieve_other, /* SX_TIED_IDX not supported */
993 retrieve_other, /* SX_UTF8STR not supported */
994 retrieve_other, /* SX_LUTF8STR not supported */
995 retrieve_other, /* SX_FLAG_HASH not supported */
996 retrieve_other, /* SX_ERROR */
999 static SV *retrieve_array(stcxt_t *cxt, char *cname);
1000 static SV *retrieve_hash(stcxt_t *cxt, char *cname);
1001 static SV *retrieve_sv_undef(stcxt_t *cxt, char *cname);
1002 static SV *retrieve_sv_yes(stcxt_t *cxt, char *cname);
1003 static SV *retrieve_sv_no(stcxt_t *cxt, char *cname);
1004 static SV *retrieve_blessed(stcxt_t *cxt, char *cname);
1005 static SV *retrieve_idx_blessed(stcxt_t *cxt, char *cname);
1006 static SV *retrieve_hook(stcxt_t *cxt, char *cname);
1007 static SV *retrieve_overloaded(stcxt_t *cxt, char *cname);
1008 static SV *retrieve_tied_key(stcxt_t *cxt, char *cname);
1009 static SV *retrieve_tied_idx(stcxt_t *cxt, char *cname);
1010 static SV *retrieve_flag_hash(stcxt_t *cxt, char *cname);
1012 static SV *(*sv_retrieve[])(stcxt_t *cxt, char *cname) = {
1013 0, /* SX_OBJECT -- entry unused dynamically */
1014 retrieve_lscalar, /* SX_LSCALAR */
1015 retrieve_array, /* SX_ARRAY */
1016 retrieve_hash, /* SX_HASH */
1017 retrieve_ref, /* SX_REF */
1018 retrieve_undef, /* SX_UNDEF */
1019 retrieve_integer, /* SX_INTEGER */
1020 retrieve_double, /* SX_DOUBLE */
1021 retrieve_byte, /* SX_BYTE */
1022 retrieve_netint, /* SX_NETINT */
1023 retrieve_scalar, /* SX_SCALAR */
1024 retrieve_tied_array, /* SX_ARRAY */
1025 retrieve_tied_hash, /* SX_HASH */
1026 retrieve_tied_scalar, /* SX_SCALAR */
1027 retrieve_sv_undef, /* SX_SV_UNDEF */
1028 retrieve_sv_yes, /* SX_SV_YES */
1029 retrieve_sv_no, /* SX_SV_NO */
1030 retrieve_blessed, /* SX_BLESS */
1031 retrieve_idx_blessed, /* SX_IX_BLESS */
1032 retrieve_hook, /* SX_HOOK */
1033 retrieve_overloaded, /* SX_OVERLOAD */
1034 retrieve_tied_key, /* SX_TIED_KEY */
1035 retrieve_tied_idx, /* SX_TIED_IDX */
1036 retrieve_utf8str, /* SX_UTF8STR */
1037 retrieve_lutf8str, /* SX_LUTF8STR */
1038 retrieve_flag_hash, /* SX_HASH */
1039 retrieve_other, /* SX_ERROR */
1042 #define RETRIEVE(c,x) (*(c)->retrieve_vtbl[(x) >= SX_ERROR ? SX_ERROR : (x)])
1044 static SV *mbuf2sv(void);
1047 *** Context management.
1053 * Called once per "thread" (interpreter) to initialize some global context.
1055 static void init_perinterp(void)
1059 cxt->netorder = 0; /* true if network order used */
1060 cxt->forgive_me = -1; /* whether to be forgiving... */
1066 * Called at the end of every context cleaning, to perform common reset
1069 static void reset_context(stcxt_t *cxt)
1073 cxt->optype &= ~(ST_STORE|ST_RETRIEVE); /* Leave ST_CLONE alone */
1077 * init_store_context
1079 * Initialize a new store context for real recursion.
1081 static void init_store_context(
1087 TRACEME(("init_store_context"));
1089 cxt->netorder = network_order;
1090 cxt->forgive_me = -1; /* Fetched from perl if needed */
1091 cxt->canonical = -1; /* Idem */
1092 cxt->tagnum = -1; /* Reset tag numbers */
1093 cxt->classnum = -1; /* Reset class numbers */
1094 cxt->fio = f; /* Where I/O are performed */
1095 cxt->optype = optype; /* A store, or a deep clone */
1096 cxt->entry = 1; /* No recursion yet */
1099 * The `hseen' table is used to keep track of each SV stored and their
1100 * associated tag numbers is special. It is "abused" because the
1101 * values stored are not real SV, just integers cast to (SV *),
1102 * which explains the freeing below.
1104 * It is also one possible bottlneck to achieve good storing speed,
1105 * so the "shared keys" optimization is turned off (unlikely to be
1106 * of any use here), and the hash table is "pre-extended". Together,
1107 * those optimizations increase the throughput by 12%.
1110 cxt->hseen = newHV(); /* Table where seen objects are stored */
1111 HvSHAREKEYS_off(cxt->hseen);
1114 * The following does not work well with perl5.004_04, and causes
1115 * a core dump later on, in a completely unrelated spot, which
1116 * makes me think there is a memory corruption going on.
1118 * Calling hv_ksplit(hseen, HBUCKETS) instead of manually hacking
1119 * it below does not make any difference. It seems to work fine
1120 * with perl5.004_68 but given the probable nature of the bug,
1121 * that does not prove anything.
1123 * It's a shame because increasing the amount of buckets raises
1124 * store() throughput by 5%, but until I figure this out, I can't
1125 * allow for this to go into production.
1127 * It is reported fixed in 5.005, hence the #if.
1129 #if PERL_VERSION >= 5
1130 #define HBUCKETS 4096 /* Buckets for %hseen */
1131 HvMAX(cxt->hseen) = HBUCKETS - 1; /* keys %hseen = $HBUCKETS; */
1135 * The `hclass' hash uses the same settings as `hseen' above, but it is
1136 * used to assign sequential tags (numbers) to class names for blessed
1139 * We turn the shared key optimization on.
1142 cxt->hclass = newHV(); /* Where seen classnames are stored */
1144 #if PERL_VERSION >= 5
1145 HvMAX(cxt->hclass) = HBUCKETS - 1; /* keys %hclass = $HBUCKETS; */
1149 * The `hook' hash table is used to keep track of the references on
1150 * the STORABLE_freeze hook routines, when found in some class name.
1152 * It is assumed that the inheritance tree will not be changed during
1153 * storing, and that no new method will be dynamically created by the
1157 cxt->hook = newHV(); /* Table where hooks are cached */
1160 * The `hook_seen' array keeps track of all the SVs returned by
1161 * STORABLE_freeze hooks for us to serialize, so that they are not
1162 * reclaimed until the end of the serialization process. Each SV is
1163 * only stored once, the first time it is seen.
1166 cxt->hook_seen = newAV(); /* Lists SVs returned by STORABLE_freeze */
1170 * clean_store_context
1172 * Clean store context by
1174 static void clean_store_context(stcxt_t *cxt)
1178 TRACEME(("clean_store_context"));
1180 ASSERT(cxt->optype & ST_STORE, ("was performing a store()"));
1183 * Insert real values into hashes where we stored faked pointers.
1187 hv_iterinit(cxt->hseen);
1188 while ((he = hv_iternext(cxt->hseen))) /* Extra () for -Wall, grr.. */
1189 HeVAL(he) = &PL_sv_undef;
1193 hv_iterinit(cxt->hclass);
1194 while ((he = hv_iternext(cxt->hclass))) /* Extra () for -Wall, grr.. */
1195 HeVAL(he) = &PL_sv_undef;
1199 * And now dispose of them...
1201 * The surrounding if() protection has been added because there might be
1202 * some cases where this routine is called more than once, during
1203 * exceptionnal events. This was reported by Marc Lehmann when Storable
1204 * is executed from mod_perl, and the fix was suggested by him.
1205 * -- RAM, 20/12/2000
1209 HV *hseen = cxt->hseen;
1212 sv_free((SV *) hseen);
1216 HV *hclass = cxt->hclass;
1219 sv_free((SV *) hclass);
1223 HV *hook = cxt->hook;
1226 sv_free((SV *) hook);
1229 if (cxt->hook_seen) {
1230 AV *hook_seen = cxt->hook_seen;
1232 av_undef(hook_seen);
1233 sv_free((SV *) hook_seen);
1236 cxt->forgive_me = -1; /* Fetched from perl if needed */
1237 cxt->canonical = -1; /* Idem */
1243 * init_retrieve_context
1245 * Initialize a new retrieve context for real recursion.
1247 static void init_retrieve_context(stcxt_t *cxt, int optype, int is_tainted)
1249 TRACEME(("init_retrieve_context"));
1252 * The hook hash table is used to keep track of the references on
1253 * the STORABLE_thaw hook routines, when found in some class name.
1255 * It is assumed that the inheritance tree will not be changed during
1256 * storing, and that no new method will be dynamically created by the
1260 cxt->hook = newHV(); /* Caches STORABLE_thaw */
1263 * If retrieving an old binary version, the cxt->retrieve_vtbl variable
1264 * was set to sv_old_retrieve. We'll need a hash table to keep track of
1265 * the correspondance between the tags and the tag number used by the
1266 * new retrieve routines.
1269 cxt->hseen = ((cxt->retrieve_vtbl == sv_old_retrieve) ? newHV() : 0);
1271 cxt->aseen = newAV(); /* Where retrieved objects are kept */
1272 cxt->aclass = newAV(); /* Where seen classnames are kept */
1273 cxt->tagnum = 0; /* Have to count objects... */
1274 cxt->classnum = 0; /* ...and class names as well */
1275 cxt->optype = optype;
1276 cxt->s_tainted = is_tainted;
1277 cxt->entry = 1; /* No recursion yet */
1278 #ifndef HAS_RESTRICTED_HASHES
1279 cxt->derestrict = -1; /* Fetched from perl if needed */
1281 #ifndef HAS_UTF8_ALL
1282 cxt->use_bytes = -1; /* Fetched from perl if needed */
1284 cxt->accept_future_minor = -1; /* Fetched from perl if needed */
1288 * clean_retrieve_context
1290 * Clean retrieve context by
1292 static void clean_retrieve_context(stcxt_t *cxt)
1294 TRACEME(("clean_retrieve_context"));
1296 ASSERT(cxt->optype & ST_RETRIEVE, ("was performing a retrieve()"));
1299 AV *aseen = cxt->aseen;
1302 sv_free((SV *) aseen);
1306 AV *aclass = cxt->aclass;
1309 sv_free((SV *) aclass);
1313 HV *hook = cxt->hook;
1316 sv_free((SV *) hook);
1320 HV *hseen = cxt->hseen;
1323 sv_free((SV *) hseen); /* optional HV, for backward compat. */
1326 #ifndef HAS_RESTRICTED_HASHES
1327 cxt->derestrict = -1; /* Fetched from perl if needed */
1329 #ifndef HAS_UTF8_ALL
1330 cxt->use_bytes = -1; /* Fetched from perl if needed */
1332 cxt->accept_future_minor = -1; /* Fetched from perl if needed */
1340 * A workaround for the CROAK bug: cleanup the last context.
1342 static void clean_context(stcxt_t *cxt)
1344 TRACEME(("clean_context"));
1346 ASSERT(cxt->s_dirty, ("dirty context"));
1351 ASSERT(!cxt->membuf_ro, ("mbase is not read-only"));
1353 if (cxt->optype & ST_RETRIEVE)
1354 clean_retrieve_context(cxt);
1355 else if (cxt->optype & ST_STORE)
1356 clean_store_context(cxt);
1360 ASSERT(!cxt->s_dirty, ("context is clean"));
1361 ASSERT(cxt->entry == 0, ("context is reset"));
1367 * Allocate a new context and push it on top of the parent one.
1368 * This new context is made globally visible via SET_STCXT().
1370 static stcxt_t *allocate_context(parent_cxt)
1371 stcxt_t *parent_cxt;
1375 TRACEME(("allocate_context"));
1377 ASSERT(!parent_cxt->s_dirty, ("parent context clean"));
1379 NEW_STORABLE_CXT_OBJ(cxt);
1380 cxt->prev = parent_cxt->my_sv;
1383 ASSERT(!cxt->s_dirty, ("clean context"));
1391 * Free current context, which cannot be the "root" one.
1392 * Make the context underneath globally visible via SET_STCXT().
1394 static void free_context(cxt)
1397 stcxt_t *prev = (stcxt_t *)(cxt->prev ? SvPVX(SvRV(cxt->prev)) : 0);
1399 TRACEME(("free_context"));
1401 ASSERT(!cxt->s_dirty, ("clean context"));
1402 ASSERT(prev, ("not freeing root context"));
1404 SvREFCNT_dec(cxt->my_sv);
1407 ASSERT(cxt, ("context not void"));
1417 * Tells whether we're in the middle of a store operation.
1419 int is_storing(void)
1423 return cxt->entry && (cxt->optype & ST_STORE);
1429 * Tells whether we're in the middle of a retrieve operation.
1431 int is_retrieving(void)
1435 return cxt->entry && (cxt->optype & ST_RETRIEVE);
1439 * last_op_in_netorder
1441 * Returns whether last operation was made using network order.
1443 * This is typically out-of-band information that might prove useful
1444 * to people wishing to convert native to network order data when used.
1446 int last_op_in_netorder(void)
1450 return cxt->netorder;
1454 *** Hook lookup and calling routines.
1460 * A wrapper on gv_fetchmethod_autoload() which caches results.
1462 * Returns the routine reference as an SV*, or null if neither the package
1463 * nor its ancestors know about the method.
1465 static SV *pkg_fetchmeth(
1474 * The following code is the same as the one performed by UNIVERSAL::can
1478 gv = gv_fetchmethod_autoload(pkg, method, FALSE);
1479 if (gv && isGV(gv)) {
1480 sv = newRV((SV*) GvCV(gv));
1481 TRACEME(("%s->%s: 0x%"UVxf, HvNAME(pkg), method, PTR2UV(sv)));
1483 sv = newSVsv(&PL_sv_undef);
1484 TRACEME(("%s->%s: not found", HvNAME(pkg), method));
1488 * Cache the result, ignoring failure: if we can't store the value,
1489 * it just won't be cached.
1492 (void) hv_store(cache, HvNAME(pkg), strlen(HvNAME(pkg)), sv, 0);
1494 return SvOK(sv) ? sv : (SV *) 0;
1500 * Force cached value to be undef: hook ignored even if present.
1502 static void pkg_hide(
1507 (void) hv_store(cache,
1508 HvNAME(pkg), strlen(HvNAME(pkg)), newSVsv(&PL_sv_undef), 0);
1514 * Discard cached value: a whole fetch loop will be retried at next lookup.
1516 static void pkg_uncache(
1521 (void) hv_delete(cache, HvNAME(pkg), strlen(HvNAME(pkg)), G_DISCARD);
1527 * Our own "UNIVERSAL::can", which caches results.
1529 * Returns the routine reference as an SV*, or null if the object does not
1530 * know about the method.
1540 TRACEME(("pkg_can for %s->%s", HvNAME(pkg), method));
1543 * Look into the cache to see whether we already have determined
1544 * where the routine was, if any.
1546 * NOTA BENE: we don't use `method' at all in our lookup, since we know
1547 * that only one hook (i.e. always the same) is cached in a given cache.
1550 svh = hv_fetch(cache, HvNAME(pkg), strlen(HvNAME(pkg)), FALSE);
1554 TRACEME(("cached %s->%s: not found", HvNAME(pkg), method));
1557 TRACEME(("cached %s->%s: 0x%"UVxf,
1558 HvNAME(pkg), method, PTR2UV(sv)));
1563 TRACEME(("not cached yet"));
1564 return pkg_fetchmeth(cache, pkg, method); /* Fetch and cache */
1570 * Call routine as obj->hook(av) in scalar context.
1571 * Propagates the single returned value if not called in void context.
1573 static SV *scalar_call(
1584 TRACEME(("scalar_call (cloning=%d)", cloning));
1591 XPUSHs(sv_2mortal(newSViv(cloning))); /* Cloning flag */
1593 SV **ary = AvARRAY(av);
1594 int cnt = AvFILLp(av) + 1;
1596 XPUSHs(ary[0]); /* Frozen string */
1597 for (i = 1; i < cnt; i++) {
1598 TRACEME(("pushing arg #%d (0x%"UVxf")...",
1599 i, PTR2UV(ary[i])));
1600 XPUSHs(sv_2mortal(newRV(ary[i])));
1605 TRACEME(("calling..."));
1606 count = perl_call_sv(hook, flags); /* Go back to Perl code */
1607 TRACEME(("count = %d", count));
1613 SvREFCNT_inc(sv); /* We're returning it, must stay alive! */
1626 * Call routine obj->hook(cloning) in list context.
1627 * Returns the list of returned values in an array.
1629 static AV *array_call(
1639 TRACEME(("array_call (cloning=%d)", cloning));
1645 XPUSHs(obj); /* Target object */
1646 XPUSHs(sv_2mortal(newSViv(cloning))); /* Cloning flag */
1649 count = perl_call_sv(hook, G_ARRAY); /* Go back to Perl code */
1654 for (i = count - 1; i >= 0; i--) {
1656 av_store(av, i, SvREFCNT_inc(sv));
1669 * Lookup the class name in the `hclass' table and either assign it a new ID
1670 * or return the existing one, by filling in `classnum'.
1672 * Return true if the class was known, false if the ID was just generated.
1674 static int known_class(
1676 char *name, /* Class name */
1677 int len, /* Name length */
1681 HV *hclass = cxt->hclass;
1683 TRACEME(("known_class (%s)", name));
1686 * Recall that we don't store pointers in this hash table, but tags.
1687 * Therefore, we need LOW_32BITS() to extract the relevant parts.
1690 svh = hv_fetch(hclass, name, len, FALSE);
1692 *classnum = LOW_32BITS(*svh);
1697 * Unknown classname, we need to record it.
1701 if (!hv_store(hclass, name, len, INT2PTR(SV*, cxt->classnum), 0))
1702 CROAK(("Unable to record new classname"));
1704 *classnum = cxt->classnum;
1709 *** Sepcific store routines.
1715 * Store a reference.
1716 * Layout is SX_REF <object> or SX_OVERLOAD <object>.
1718 static int store_ref(stcxt_t *cxt, SV *sv)
1720 TRACEME(("store_ref (0x%"UVxf")", PTR2UV(sv)));
1723 * Follow reference, and check if target is overloaded.
1729 HV *stash = (HV *) SvSTASH(sv);
1730 if (stash && Gv_AMG(stash)) {
1731 TRACEME(("ref (0x%"UVxf") is overloaded", PTR2UV(sv)));
1732 PUTMARK(SX_OVERLOAD);
1738 return store(cxt, sv);
1746 * Layout is SX_LSCALAR <length> <data>, SX_SCALAR <length> <data> or SX_UNDEF.
1747 * The <data> section is omitted if <length> is 0.
1749 * If integer or double, the layout is SX_INTEGER <data> or SX_DOUBLE <data>.
1750 * Small integers (within [-127, +127]) are stored as SX_BYTE <byte>.
1752 static int store_scalar(stcxt_t *cxt, SV *sv)
1757 U32 flags = SvFLAGS(sv); /* "cc -O" may put it in register */
1759 TRACEME(("store_scalar (0x%"UVxf")", PTR2UV(sv)));
1762 * For efficiency, break the SV encapsulation by peaking at the flags
1763 * directly without using the Perl macros to avoid dereferencing
1764 * sv->sv_flags each time we wish to check the flags.
1767 if (!(flags & SVf_OK)) { /* !SvOK(sv) */
1768 if (sv == &PL_sv_undef) {
1769 TRACEME(("immortal undef"));
1770 PUTMARK(SX_SV_UNDEF);
1772 TRACEME(("undef at 0x%"UVxf, PTR2UV(sv)));
1779 * Always store the string representation of a scalar if it exists.
1780 * Gisle Aas provided me with this test case, better than a long speach:
1782 * perl -MDevel::Peek -le '$a="abc"; $a+0; Dump($a)'
1783 * SV = PVNV(0x80c8520)
1785 * FLAGS = (NOK,POK,pNOK,pPOK)
1788 * PV = 0x80c83d0 "abc"\0
1792 * Write SX_SCALAR, length, followed by the actual data.
1794 * Otherwise, write an SX_BYTE, SX_INTEGER or an SX_DOUBLE as
1795 * appropriate, followed by the actual (binary) data. A double
1796 * is written as a string if network order, for portability.
1798 * NOTE: instead of using SvNOK(sv), we test for SvNOKp(sv).
1799 * The reason is that when the scalar value is tainted, the SvNOK(sv)
1802 * The test for a read-only scalar with both POK and NOK set is meant
1803 * to quickly detect &PL_sv_yes and &PL_sv_no without having to pay the
1804 * address comparison for each scalar we store.
1807 #define SV_MAYBE_IMMORTAL (SVf_READONLY|SVf_POK|SVf_NOK)
1809 if ((flags & SV_MAYBE_IMMORTAL) == SV_MAYBE_IMMORTAL) {
1810 if (sv == &PL_sv_yes) {
1811 TRACEME(("immortal yes"));
1813 } else if (sv == &PL_sv_no) {
1814 TRACEME(("immortal no"));
1817 pv = SvPV(sv, len); /* We know it's SvPOK */
1818 goto string; /* Share code below */
1820 } else if (flags & SVf_POK) {
1821 /* public string - go direct to string read. */
1822 goto string_readlen;
1824 #if (PATCHLEVEL <= 6)
1825 /* For 5.6 and earlier NV flag trumps IV flag, so only use integer
1826 direct if NV flag is off. */
1827 (flags & (SVf_NOK | SVf_IOK)) == SVf_IOK
1829 /* 5.7 rules are that if IV public flag is set, IV value is as
1830 good, if not better, than NV value. */
1836 * Will come here from below with iv set if double is an integer.
1840 /* Sorry. This isn't in 5.005_56 (IIRC) or earlier. */
1842 /* Need to do this out here, else 0xFFFFFFFF becomes iv of -1
1843 * (for example) and that ends up in the optimised small integer
1846 if ((flags & SVf_IVisUV) && SvUV(sv) > IV_MAX) {
1847 TRACEME(("large unsigned integer as string, value = %"UVuf, SvUV(sv)));
1848 goto string_readlen;
1852 * Optimize small integers into a single byte, otherwise store as
1853 * a real integer (converted into network order if they asked).
1856 if (iv >= -128 && iv <= 127) {
1857 unsigned char siv = (unsigned char) (iv + 128); /* [0,255] */
1860 TRACEME(("small integer stored as %d", siv));
1861 } else if (cxt->netorder) {
1863 TRACEME(("no htonl, fall back to string for integer"));
1864 goto string_readlen;
1872 /* Sorry. This isn't in 5.005_56 (IIRC) or earlier. */
1873 ((flags & SVf_IVisUV) && SvUV(sv) > 0x7FFFFFFF) ||
1875 (iv > 0x7FFFFFFF) || (iv < -0x80000000)) {
1876 /* Bigger than 32 bits. */
1877 TRACEME(("large network order integer as string, value = %"IVdf, iv));
1878 goto string_readlen;
1882 niv = (I32) htonl((I32) iv);
1883 TRACEME(("using network order"));
1888 PUTMARK(SX_INTEGER);
1889 WRITE(&iv, sizeof(iv));
1892 TRACEME(("ok (integer 0x%"UVxf", value = %"IVdf")", PTR2UV(sv), iv));
1893 } else if (flags & SVf_NOK) {
1895 #if (PATCHLEVEL <= 6)
1898 * Watch for number being an integer in disguise.
1900 if (nv == (NV) (iv = I_V(nv))) {
1901 TRACEME(("double %"NVff" is actually integer %"IVdf, nv, iv));
1902 goto integer; /* Share code above */
1909 goto integer; /* Share code above */
1914 if (cxt->netorder) {
1915 TRACEME(("double %"NVff" stored as string", nv));
1916 goto string_readlen; /* Share code below */
1920 WRITE(&nv, sizeof(nv));
1922 TRACEME(("ok (double 0x%"UVxf", value = %"NVff")", PTR2UV(sv), nv));
1924 } else if (flags & (SVp_POK | SVp_NOK | SVp_IOK)) {
1925 I32 wlen; /* For 64-bit machines */
1931 * Will come here from above if it was readonly, POK and NOK but
1932 * neither &PL_sv_yes nor &PL_sv_no.
1936 wlen = (I32) len; /* WLEN via STORE_SCALAR expects I32 */
1938 STORE_UTF8STR(pv, wlen);
1940 STORE_SCALAR(pv, wlen);
1941 TRACEME(("ok (scalar 0x%"UVxf" '%s', length = %"IVdf")",
1942 PTR2UV(sv), SvPVX(sv), (IV)len));
1944 CROAK(("Can't determine type of %s(0x%"UVxf")",
1945 sv_reftype(sv, FALSE),
1947 return 0; /* Ok, no recursion on scalars */
1955 * Layout is SX_ARRAY <size> followed by each item, in increading index order.
1956 * Each item is stored as <object>.
1958 static int store_array(stcxt_t *cxt, AV *av)
1961 I32 len = av_len(av) + 1;
1965 TRACEME(("store_array (0x%"UVxf")", PTR2UV(av)));
1968 * Signal array by emitting SX_ARRAY, followed by the array length.
1973 TRACEME(("size = %d", len));
1976 * Now store each item recursively.
1979 for (i = 0; i < len; i++) {
1980 sav = av_fetch(av, i, 0);
1982 TRACEME(("(#%d) undef item", i));
1986 TRACEME(("(#%d) item", i));
1987 if ((ret = store(cxt, *sav))) /* Extra () for -Wall, grr... */
1991 TRACEME(("ok (array)"));
2000 * Borrowed from perl source file pp_ctl.c, where it is used by pp_sort.
2003 sortcmp(const void *a, const void *b)
2005 return sv_cmp(*(SV * const *) a, *(SV * const *) b);
2012 * Store a hash table.
2014 * For a "normal" hash (not restricted, no utf8 keys):
2016 * Layout is SX_HASH <size> followed by each key/value pair, in random order.
2017 * Values are stored as <object>.
2018 * Keys are stored as <length> <data>, the <data> section being omitted
2021 * For a "fancy" hash (restricted or utf8 keys):
2023 * Layout is SX_FLAG_HASH <size> <hash flags> followed by each key/value pair,
2025 * Values are stored as <object>.
2026 * Keys are stored as <flags> <length> <data>, the <data> section being omitted
2028 * Currently the only hash flag is "restriced"
2029 * Key flags are as for hv.h
2031 static int store_hash(stcxt_t *cxt, HV *hv)
2034 #ifdef HAS_RESTRICTED_HASHES
2043 int flagged_hash = ((SvREADONLY(hv)
2044 #ifdef HAS_HASH_KEY_FLAGS
2048 unsigned char hash_flags = (SvREADONLY(hv) ? SHV_RESTRICTED : 0);
2051 /* needs int cast for C++ compilers, doesn't it? */
2052 TRACEME(("store_hash (0x%"UVxf") (flags %x)", PTR2UV(hv),
2055 TRACEME(("store_hash (0x%"UVxf")", PTR2UV(hv)));
2059 * Signal hash by emitting SX_HASH, followed by the table length.
2063 PUTMARK(SX_FLAG_HASH);
2064 PUTMARK(hash_flags);
2069 TRACEME(("size = %d", len));
2072 * Save possible iteration state via each() on that table.
2075 riter = HvRITER(hv);
2076 eiter = HvEITER(hv);
2080 * Now store each item recursively.
2082 * If canonical is defined to some true value then store each
2083 * key/value pair in sorted order otherwise the order is random.
2084 * Canonical order is irrelevant when a deep clone operation is performed.
2086 * Fetch the value from perl only once per store() operation, and only
2091 !(cxt->optype & ST_CLONE) && (cxt->canonical == 1 ||
2092 (cxt->canonical < 0 && (cxt->canonical =
2093 (SvTRUE(perl_get_sv("Storable::canonical", TRUE)) ? 1 : 0))))
2096 * Storing in order, sorted by key.
2097 * Run through the hash, building up an array of keys in a
2098 * mortal array, sort the array and then run through the
2104 /*av_extend (av, len);*/
2106 TRACEME(("using canonical order"));
2108 for (i = 0; i < len; i++) {
2109 #ifdef HAS_RESTRICTED_HASHES
2110 HE *he = hv_iternext_flags(hv, HV_ITERNEXT_WANTPLACEHOLDERS);
2112 HE *he = hv_iternext(hv);
2114 SV *key = hv_iterkeysv(he);
2115 av_store(av, AvFILLp(av)+1, key); /* av_push(), really */
2118 qsort((char *) AvARRAY(av), len, sizeof(SV *), sortcmp);
2120 for (i = 0; i < len; i++) {
2121 unsigned char flags;
2125 SV *key = av_shift(av);
2126 HE *he = hv_fetch_ent(hv, key, 0, 0);
2127 SV *val = HeVAL(he);
2129 return 1; /* Internal error, not I/O error */
2132 * Store value first.
2135 TRACEME(("(#%d) value 0x%"UVxf, i, PTR2UV(val)));
2137 if ((ret = store(cxt, val))) /* Extra () for -Wall, grr... */
2142 * Keys are written after values to make sure retrieval
2143 * can be optimal in terms of memory usage, where keys are
2144 * read into a fixed unique buffer called kbuf.
2145 * See retrieve_hash() for details.
2148 /* Implementation of restricted hashes isn't nicely
2151 = (((hash_flags & SHV_RESTRICTED)
2153 ? SHV_K_LOCKED : 0);
2154 if (val == &PL_sv_undef)
2155 flags |= SHV_K_PLACEHOLDER;
2157 keyval = SvPV(key, keylen_tmp);
2158 keylen = keylen_tmp;
2159 #ifdef HAS_UTF8_HASHES
2160 /* If you build without optimisation on pre 5.6
2161 then nothing spots that SvUTF8(key) is always 0,
2162 so the block isn't optimised away, at which point
2163 the linker dislikes the reference to
2166 const char *keysave = keyval;
2167 bool is_utf8 = TRUE;
2169 /* Just casting the &klen to (STRLEN) won't work
2170 well if STRLEN and I32 are of different widths.
2172 keyval = (char*)bytes_from_utf8((U8*)keyval,
2176 /* If we were able to downgrade here, then than
2177 means that we have a key which only had chars
2178 0-255, but was utf8 encoded. */
2180 if (keyval != keysave) {
2181 keylen = keylen_tmp;
2182 flags |= SHV_K_WASUTF8;
2184 /* keylen_tmp can't have changed, so no need
2185 to assign back to keylen. */
2186 flags |= SHV_K_UTF8;
2193 TRACEME(("(#%d) key '%s' flags %x %u", i, keyval, flags, *keyval));
2195 assert (flags == 0);
2196 TRACEME(("(#%d) key '%s'", i, keyval));
2200 WRITE(keyval, keylen);
2201 if (flags & SHV_K_WASUTF8)
2206 * Free up the temporary array
2215 * Storing in "random" order (in the order the keys are stored
2216 * within the the hash). This is the default and will be faster!
2219 for (i = 0; i < len; i++) {
2222 unsigned char flags;
2223 #ifdef HV_ITERNEXT_WANTPLACEHOLDERS
2224 HE *he = hv_iternext_flags(hv, HV_ITERNEXT_WANTPLACEHOLDERS);
2226 HE *he = hv_iternext(hv);
2228 SV *val = (he ? hv_iterval(hv, he) : 0);
2233 return 1; /* Internal error, not I/O error */
2236 * Store value first.
2239 TRACEME(("(#%d) value 0x%"UVxf, i, PTR2UV(val)));
2241 if ((ret = store(cxt, val))) /* Extra () for -Wall, grr... */
2244 /* Implementation of restricted hashes isn't nicely
2247 = (((hash_flags & SHV_RESTRICTED)
2249 ? SHV_K_LOCKED : 0);
2250 if (val == &PL_sv_undef)
2251 flags |= SHV_K_PLACEHOLDER;
2253 hek = HeKEY_hek(he);
2255 if (len == HEf_SVKEY) {
2256 /* This is somewhat sick, but the internal APIs are
2257 * such that XS code could put one of these in in
2259 * Maybe we should be capable of storing one if
2262 key_sv = HeKEY_sv(he);
2263 flags |= SHV_K_ISSV;
2265 /* Regular string key. */
2266 #ifdef HAS_HASH_KEY_FLAGS
2268 flags |= SHV_K_UTF8;
2269 if (HEK_WASUTF8(hek))
2270 flags |= SHV_K_WASUTF8;
2276 * Keys are written after values to make sure retrieval
2277 * can be optimal in terms of memory usage, where keys are
2278 * read into a fixed unique buffer called kbuf.
2279 * See retrieve_hash() for details.
2284 TRACEME(("(#%d) key '%s' flags %x", i, key, flags));
2286 assert (flags == 0);
2287 TRACEME(("(#%d) key '%s'", i, key));
2289 if (flags & SHV_K_ISSV) {
2299 TRACEME(("ok (hash 0x%"UVxf")", PTR2UV(hv)));
2302 HvRITER(hv) = riter; /* Restore hash iterator state */
2303 HvEITER(hv) = eiter;
2311 * When storing a tied object (be it a tied scalar, array or hash), we lay out
2312 * a special mark, followed by the underlying tied object. For instance, when
2313 * dealing with a tied hash, we store SX_TIED_HASH <hash object>, where
2314 * <hash object> stands for the serialization of the tied hash.
2316 static int store_tied(stcxt_t *cxt, SV *sv)
2320 int svt = SvTYPE(sv);
2323 TRACEME(("store_tied (0x%"UVxf")", PTR2UV(sv)));
2326 * We have a small run-time penalty here because we chose to factorise
2327 * all tieds objects into the same routine, and not have a store_tied_hash,
2328 * a store_tied_array, etc...
2330 * Don't use a switch() statement, as most compilers don't optimize that
2331 * well for 2/3 values. An if() else if() cascade is just fine. We put
2332 * tied hashes first, as they are the most likely beasts.
2335 if (svt == SVt_PVHV) {
2336 TRACEME(("tied hash"));
2337 PUTMARK(SX_TIED_HASH); /* Introduces tied hash */
2338 } else if (svt == SVt_PVAV) {
2339 TRACEME(("tied array"));
2340 PUTMARK(SX_TIED_ARRAY); /* Introduces tied array */
2342 TRACEME(("tied scalar"));
2343 PUTMARK(SX_TIED_SCALAR); /* Introduces tied scalar */
2347 if (!(mg = mg_find(sv, mtype)))
2348 CROAK(("No magic '%c' found while storing tied %s", mtype,
2349 (svt == SVt_PVHV) ? "hash" :
2350 (svt == SVt_PVAV) ? "array" : "scalar"));
2353 * The mg->mg_obj found by mg_find() above actually points to the
2354 * underlying tied Perl object implementation. For instance, if the
2355 * original SV was that of a tied array, then mg->mg_obj is an AV.
2357 * Note that we store the Perl object as-is. We don't call its FETCH
2358 * method along the way. At retrieval time, we won't call its STORE
2359 * method either, but the tieing magic will be re-installed. In itself,
2360 * that ensures that the tieing semantics are preserved since futher
2361 * accesses on the retrieved object will indeed call the magic methods...
2364 if ((ret = store(cxt, mg->mg_obj))) /* Extra () for -Wall, grr... */
2367 TRACEME(("ok (tied)"));
2375 * Stores a reference to an item within a tied structure:
2377 * . \$h{key}, stores both the (tied %h) object and 'key'.
2378 * . \$a[idx], stores both the (tied @a) object and 'idx'.
2380 * Layout is therefore either:
2381 * SX_TIED_KEY <object> <key>
2382 * SX_TIED_IDX <object> <index>
2384 static int store_tied_item(stcxt_t *cxt, SV *sv)
2389 TRACEME(("store_tied_item (0x%"UVxf")", PTR2UV(sv)));
2391 if (!(mg = mg_find(sv, 'p')))
2392 CROAK(("No magic 'p' found while storing reference to tied item"));
2395 * We discriminate between \$h{key} and \$a[idx] via mg_ptr.
2399 TRACEME(("store_tied_item: storing a ref to a tied hash item"));
2400 PUTMARK(SX_TIED_KEY);
2401 TRACEME(("store_tied_item: storing OBJ 0x%"UVxf, PTR2UV(mg->mg_obj)));
2403 if ((ret = store(cxt, mg->mg_obj))) /* Extra () for -Wall, grr... */
2406 TRACEME(("store_tied_item: storing PTR 0x%"UVxf, PTR2UV(mg->mg_ptr)));
2408 if ((ret = store(cxt, (SV *) mg->mg_ptr))) /* Idem, for -Wall */
2411 I32 idx = mg->mg_len;
2413 TRACEME(("store_tied_item: storing a ref to a tied array item "));
2414 PUTMARK(SX_TIED_IDX);
2415 TRACEME(("store_tied_item: storing OBJ 0x%"UVxf, PTR2UV(mg->mg_obj)));
2417 if ((ret = store(cxt, mg->mg_obj))) /* Idem, for -Wall */
2420 TRACEME(("store_tied_item: storing IDX %d", idx));
2425 TRACEME(("ok (tied item)"));
2431 * store_hook -- dispatched manually, not via sv_store[]
2433 * The blessed SV is serialized by a hook.
2437 * SX_HOOK <flags> <len> <classname> <len2> <str> [<len3> <object-IDs>]
2439 * where <flags> indicates how long <len>, <len2> and <len3> are, whether
2440 * the trailing part [] is present, the type of object (scalar, array or hash).
2441 * There is also a bit which says how the classname is stored between:
2446 * and when the <index> form is used (classname already seen), the "large
2447 * classname" bit in <flags> indicates how large the <index> is.
2449 * The serialized string returned by the hook is of length <len2> and comes
2450 * next. It is an opaque string for us.
2452 * Those <len3> object IDs which are listed last represent the extra references
2453 * not directly serialized by the hook, but which are linked to the object.
2455 * When recursion is mandated to resolve object-IDs not yet seen, we have
2456 * instead, with <header> being flags with bits set to indicate the object type
2457 * and that recursion was indeed needed:
2459 * SX_HOOK <header> <object> <header> <object> <flags>
2461 * that same header being repeated between serialized objects obtained through
2462 * recursion, until we reach flags indicating no recursion, at which point
2463 * we know we've resynchronized with a single layout, after <flags>.
2465 * When storing a blessed ref to a tied variable, the following format is
2468 * SX_HOOK <flags> <extra> ... [<len3> <object-IDs>] <magic object>
2470 * The first <flags> indication carries an object of type SHT_EXTRA, and the
2471 * real object type is held in the <extra> flag. At the very end of the
2472 * serialization stream, the underlying magic object is serialized, just like
2473 * any other tied variable.
2475 static int store_hook(
2488 int count; /* really len3 + 1 */
2489 unsigned char flags;
2492 int recursed = 0; /* counts recursion */
2493 int obj_type; /* object type, on 2 bits */
2496 int clone = cxt->optype & ST_CLONE;
2497 char mtype = '\0'; /* for blessed ref to tied structures */
2498 unsigned char eflags = '\0'; /* used when object type is SHT_EXTRA */
2500 TRACEME(("store_hook, class \"%s\", tagged #%d", HvNAME(pkg), cxt->tagnum));
2503 * Determine object type on 2 bits.
2508 obj_type = SHT_SCALAR;
2511 obj_type = SHT_ARRAY;
2514 obj_type = SHT_HASH;
2518 * Produced by a blessed ref to a tied data structure, $o in the
2519 * following Perl code.
2523 * my $o = bless \%h, 'BAR';
2525 * Signal the tie-ing magic by setting the object type as SHT_EXTRA
2526 * (since we have only 2 bits in <flags> to store the type), and an
2527 * <extra> byte flag will be emitted after the FIRST <flags> in the
2528 * stream, carrying what we put in `eflags'.
2530 obj_type = SHT_EXTRA;
2531 switch (SvTYPE(sv)) {
2533 eflags = (unsigned char) SHT_THASH;
2537 eflags = (unsigned char) SHT_TARRAY;
2541 eflags = (unsigned char) SHT_TSCALAR;
2547 CROAK(("Unexpected object type (%d) in store_hook()", type));
2549 flags = SHF_NEED_RECURSE | obj_type;
2551 class = HvNAME(pkg);
2552 len = strlen(class);
2555 * To call the hook, we need to fake a call like:
2557 * $object->STORABLE_freeze($cloning);
2559 * but we don't have the $object here. For instance, if $object is
2560 * a blessed array, what we have in `sv' is the array, and we can't
2561 * call a method on those.
2563 * Therefore, we need to create a temporary reference to the object and
2564 * make the call on that reference.
2567 TRACEME(("about to call STORABLE_freeze on class %s", class));
2569 ref = newRV_noinc(sv); /* Temporary reference */
2570 av = array_call(ref, hook, clone); /* @a = $object->STORABLE_freeze($c) */
2572 SvREFCNT_dec(ref); /* Reclaim temporary reference */
2574 count = AvFILLp(av) + 1;
2575 TRACEME(("store_hook, array holds %d items", count));
2578 * If they return an empty list, it means they wish to ignore the
2579 * hook for this class (and not just this instance -- that's for them
2580 * to handle if they so wish).
2582 * Simply disable the cached entry for the hook (it won't be recomputed
2583 * since it's present in the cache) and recurse to store_blessed().
2588 * They must not change their mind in the middle of a serialization.
2591 if (hv_fetch(cxt->hclass, class, len, FALSE))
2592 CROAK(("Too late to ignore hooks for %s class \"%s\"",
2593 (cxt->optype & ST_CLONE) ? "cloning" : "storing", class));
2595 pkg_hide(cxt->hook, pkg, "STORABLE_freeze");
2597 ASSERT(!pkg_can(cxt->hook, pkg, "STORABLE_freeze"), ("hook invisible"));
2598 TRACEME(("ignoring STORABLE_freeze in class \"%s\"", class));
2600 return store_blessed(cxt, sv, type, pkg);
2604 * Get frozen string.
2608 pv = SvPV(ary[0], len2);
2611 * If they returned more than one item, we need to serialize some
2612 * extra references if not already done.
2614 * Loop over the array, starting at postion #1, and for each item,
2615 * ensure it is a reference, serialize it if not already done, and
2616 * replace the entry with the tag ID of the corresponding serialized
2619 * We CHEAT by not calling av_fetch() and read directly within the
2623 for (i = 1; i < count; i++) {
2627 AV *av_hook = cxt->hook_seen;
2630 CROAK(("Item #%d returned by STORABLE_freeze "
2631 "for %s is not a reference", i, class));
2632 xsv = SvRV(rsv); /* Follow ref to know what to look for */
2635 * Look in hseen and see if we have a tag already.
2636 * Serialize entry if not done already, and get its tag.
2639 if ((svh = hv_fetch(cxt->hseen, (char *) &xsv, sizeof(xsv), FALSE)))
2640 goto sv_seen; /* Avoid moving code too far to the right */
2642 TRACEME(("listed object %d at 0x%"UVxf" is unknown", i-1, PTR2UV(xsv)));
2645 * We need to recurse to store that object and get it to be known
2646 * so that we can resolve the list of object-IDs at retrieve time.
2648 * The first time we do this, we need to emit the proper header
2649 * indicating that we recursed, and what the type of object is (the
2650 * object we're storing via a user-hook). Indeed, during retrieval,
2651 * we'll have to create the object before recursing to retrieve the
2652 * others, in case those would point back at that object.
2655 /* [SX_HOOK] <flags> [<extra>] <object>*/
2659 if (obj_type == SHT_EXTRA)
2664 if ((ret = store(cxt, xsv))) /* Given by hook for us to store */
2667 svh = hv_fetch(cxt->hseen, (char *) &xsv, sizeof(xsv), FALSE);
2669 CROAK(("Could not serialize item #%d from hook in %s", i, class));
2672 * It was the first time we serialized `xsv'.
2674 * Keep this SV alive until the end of the serialization: if we
2675 * disposed of it right now by decrementing its refcount, and it was
2676 * a temporary value, some next temporary value allocated during
2677 * another STORABLE_freeze might take its place, and we'd wrongly
2678 * assume that new SV was already serialized, based on its presence
2681 * Therefore, push it away in cxt->hook_seen.
2684 av_store(av_hook, AvFILLp(av_hook)+1, SvREFCNT_inc(xsv));
2688 * Dispose of the REF they returned. If we saved the `xsv' away
2689 * in the array of returned SVs, that will not cause the underlying
2690 * referenced SV to be reclaimed.
2693 ASSERT(SvREFCNT(xsv) > 1, ("SV will survive disposal of its REF"));
2694 SvREFCNT_dec(rsv); /* Dispose of reference */
2697 * Replace entry with its tag (not a real SV, so no refcnt increment)
2701 TRACEME(("listed object %d at 0x%"UVxf" is tag #%"UVuf,
2702 i-1, PTR2UV(xsv), PTR2UV(*svh)));
2706 * Allocate a class ID if not already done.
2708 * This needs to be done after the recursion above, since at retrieval
2709 * time, we'll see the inner objects first. Many thanks to
2710 * Salvador Ortiz Garcia <sog@msg.com.mx> who spot that bug and
2711 * proposed the right fix. -- RAM, 15/09/2000
2714 if (!known_class(cxt, class, len, &classnum)) {
2715 TRACEME(("first time we see class %s, ID = %d", class, classnum));
2716 classnum = -1; /* Mark: we must store classname */
2718 TRACEME(("already seen class %s, ID = %d", class, classnum));
2722 * Compute leading flags.
2726 if (((classnum == -1) ? len : classnum) > LG_SCALAR)
2727 flags |= SHF_LARGE_CLASSLEN;
2729 flags |= SHF_IDX_CLASSNAME;
2730 if (len2 > LG_SCALAR)
2731 flags |= SHF_LARGE_STRLEN;
2733 flags |= SHF_HAS_LIST;
2734 if (count > (LG_SCALAR + 1))
2735 flags |= SHF_LARGE_LISTLEN;
2738 * We're ready to emit either serialized form:
2740 * SX_HOOK <flags> <len> <classname> <len2> <str> [<len3> <object-IDs>]
2741 * SX_HOOK <flags> <index> <len2> <str> [<len3> <object-IDs>]
2743 * If we recursed, the SX_HOOK has already been emitted.
2746 TRACEME(("SX_HOOK (recursed=%d) flags=0x%x "
2747 "class=%"IVdf" len=%"IVdf" len2=%"IVdf" len3=%d",
2748 recursed, flags, (IV)classnum, (IV)len, (IV)len2, count-1));
2750 /* SX_HOOK <flags> [<extra>] */
2754 if (obj_type == SHT_EXTRA)
2759 /* <len> <classname> or <index> */
2760 if (flags & SHF_IDX_CLASSNAME) {
2761 if (flags & SHF_LARGE_CLASSLEN)
2764 unsigned char cnum = (unsigned char) classnum;
2768 if (flags & SHF_LARGE_CLASSLEN)
2771 unsigned char clen = (unsigned char) len;
2774 WRITE(class, len); /* Final \0 is omitted */
2777 /* <len2> <frozen-str> */
2778 if (flags & SHF_LARGE_STRLEN) {
2779 I32 wlen2 = len2; /* STRLEN might be 8 bytes */
2780 WLEN(wlen2); /* Must write an I32 for 64-bit machines */
2782 unsigned char clen = (unsigned char) len2;
2786 WRITE(pv, (SSize_t)len2); /* Final \0 is omitted */
2788 /* [<len3> <object-IDs>] */
2789 if (flags & SHF_HAS_LIST) {
2790 int len3 = count - 1;
2791 if (flags & SHF_LARGE_LISTLEN)
2794 unsigned char clen = (unsigned char) len3;
2799 * NOTA BENE, for 64-bit machines: the ary[i] below does not yield a
2800 * real pointer, rather a tag number, well under the 32-bit limit.
2803 for (i = 1; i < count; i++) {
2804 I32 tagval = htonl(LOW_32BITS(ary[i]));
2806 TRACEME(("object %d, tag #%d", i-1, ntohl(tagval)));
2811 * Free the array. We need extra care for indices after 0, since they
2812 * don't hold real SVs but integers cast.
2816 AvFILLp(av) = 0; /* Cheat, nothing after 0 interests us */
2821 * If object was tied, need to insert serialization of the magic object.
2824 if (obj_type == SHT_EXTRA) {
2827 if (!(mg = mg_find(sv, mtype))) {
2828 int svt = SvTYPE(sv);
2829 CROAK(("No magic '%c' found while storing ref to tied %s with hook",
2830 mtype, (svt == SVt_PVHV) ? "hash" :
2831 (svt == SVt_PVAV) ? "array" : "scalar"));
2834 TRACEME(("handling the magic object 0x%"UVxf" part of 0x%"UVxf,
2835 PTR2UV(mg->mg_obj), PTR2UV(sv)));
2841 if ((ret = store(cxt, mg->mg_obj))) /* Extra () for -Wall, grr... */
2849 * store_blessed -- dispatched manually, not via sv_store[]
2851 * Check whether there is a STORABLE_xxx hook defined in the class or in one
2852 * of its ancestors. If there is, then redispatch to store_hook();
2854 * Otherwise, the blessed SV is stored using the following layout:
2856 * SX_BLESS <flag> <len> <classname> <object>
2858 * where <flag> indicates whether <len> is stored on 0 or 4 bytes, depending
2859 * on the high-order bit in flag: if 1, then length follows on 4 bytes.
2860 * Otherwise, the low order bits give the length, thereby giving a compact
2861 * representation for class names less than 127 chars long.
2863 * Each <classname> seen is remembered and indexed, so that the next time
2864 * an object in the blessed in the same <classname> is stored, the following
2867 * SX_IX_BLESS <flag> <index> <object>
2869 * where <index> is the classname index, stored on 0 or 4 bytes depending
2870 * on the high-order bit in flag (same encoding as above for <len>).
2872 static int store_blessed(
2883 TRACEME(("store_blessed, type %d, class \"%s\"", type, HvNAME(pkg)));
2886 * Look for a hook for this blessed SV and redirect to store_hook()
2890 hook = pkg_can(cxt->hook, pkg, "STORABLE_freeze");
2892 return store_hook(cxt, sv, type, pkg, hook);
2895 * This is a blessed SV without any serialization hook.
2898 class = HvNAME(pkg);
2899 len = strlen(class);
2901 TRACEME(("blessed 0x%"UVxf" in %s, no hook: tagged #%d",
2902 PTR2UV(sv), class, cxt->tagnum));
2905 * Determine whether it is the first time we see that class name (in which
2906 * case it will be stored in the SX_BLESS form), or whether we already
2907 * saw that class name before (in which case the SX_IX_BLESS form will be
2911 if (known_class(cxt, class, len, &classnum)) {
2912 TRACEME(("already seen class %s, ID = %d", class, classnum));
2913 PUTMARK(SX_IX_BLESS);
2914 if (classnum <= LG_BLESS) {
2915 unsigned char cnum = (unsigned char) classnum;
2918 unsigned char flag = (unsigned char) 0x80;
2923 TRACEME(("first time we see class %s, ID = %d", class, classnum));
2925 if (len <= LG_BLESS) {
2926 unsigned char clen = (unsigned char) len;
2929 unsigned char flag = (unsigned char) 0x80;
2931 WLEN(len); /* Don't BER-encode, this should be rare */
2933 WRITE(class, len); /* Final \0 is omitted */
2937 * Now emit the <object> part.
2940 return SV_STORE(type)(cxt, sv);
2946 * We don't know how to store the item we reached, so return an error condition.
2947 * (it's probably a GLOB, some CODE reference, etc...)
2949 * If they defined the `forgive_me' variable at the Perl level to some
2950 * true value, then don't croak, just warn, and store a placeholder string
2953 static int store_other(stcxt_t *cxt, SV *sv)
2956 static char buf[80];
2958 TRACEME(("store_other"));
2961 * Fetch the value from perl only once per store() operation.
2965 cxt->forgive_me == 0 ||
2966 (cxt->forgive_me < 0 && !(cxt->forgive_me =
2967 SvTRUE(perl_get_sv("Storable::forgive_me", TRUE)) ? 1 : 0))
2969 CROAK(("Can't store %s items", sv_reftype(sv, FALSE)));
2971 warn("Can't store item %s(0x%"UVxf")",
2972 sv_reftype(sv, FALSE), PTR2UV(sv));
2975 * Store placeholder string as a scalar instead...
2978 (void) sprintf(buf, "You lost %s(0x%"UVxf")%c", sv_reftype(sv, FALSE),
2979 PTR2UV(sv), (char) 0);
2982 STORE_SCALAR(buf, len);
2983 TRACEME(("ok (dummy \"%s\", length = %"IVdf")", buf, (IV) len));
2989 *** Store driving routines
2995 * WARNING: partially duplicates Perl's sv_reftype for speed.
2997 * Returns the type of the SV, identified by an integer. That integer
2998 * may then be used to index the dynamic routine dispatch table.
3000 static int sv_type(SV *sv)
3002 switch (SvTYPE(sv)) {
3007 * No need to check for ROK, that can't be set here since there
3008 * is no field capable of hodling the xrv_rv reference.
3016 * Starting from SVt_PV, it is possible to have the ROK flag
3017 * set, the pointer to the other SV being either stored in
3018 * the xrv_rv (in the case of a pure SVt_RV), or as the
3019 * xpv_pv field of an SVt_PV and its heirs.
3021 * However, those SV cannot be magical or they would be an
3022 * SVt_PVMG at least.
3024 return SvROK(sv) ? svis_REF : svis_SCALAR;
3026 case SVt_PVLV: /* Workaround for perl5.004_04 "LVALUE" bug */
3027 if (SvRMAGICAL(sv) && (mg_find(sv, 'p')))
3028 return svis_TIED_ITEM;
3031 if (SvRMAGICAL(sv) && (mg_find(sv, 'q')))
3033 return SvROK(sv) ? svis_REF : svis_SCALAR;
3035 if (SvRMAGICAL(sv) && (mg_find(sv, 'P')))
3039 if (SvRMAGICAL(sv) && (mg_find(sv, 'P')))
3052 * Recursively store objects pointed to by the sv to the specified file.
3054 * Layout is <content> or SX_OBJECT <tagnum> if we reach an already stored
3055 * object (one for which storage has started -- it may not be over if we have
3056 * a self-referenced structure). This data set forms a stored <object>.
3058 static int store(stcxt_t *cxt, SV *sv)
3063 HV *hseen = cxt->hseen;
3065 TRACEME(("store (0x%"UVxf")", PTR2UV(sv)));
3068 * If object has already been stored, do not duplicate data.
3069 * Simply emit the SX_OBJECT marker followed by its tag data.
3070 * The tag is always written in network order.
3072 * NOTA BENE, for 64-bit machines: the "*svh" below does not yield a
3073 * real pointer, rather a tag number (watch the insertion code below).
3074 * That means it pobably safe to assume it is well under the 32-bit limit,
3075 * and makes the truncation safe.
3076 * -- RAM, 14/09/1999
3079 svh = hv_fetch(hseen, (char *) &sv, sizeof(sv), FALSE);
3081 I32 tagval = htonl(LOW_32BITS(*svh));
3083 TRACEME(("object 0x%"UVxf" seen as #%d", PTR2UV(sv), ntohl(tagval)));
3091 * Allocate a new tag and associate it with the address of the sv being
3092 * stored, before recursing...
3094 * In order to avoid creating new SvIVs to hold the tagnum we just
3095 * cast the tagnum to an SV pointer and store that in the hash. This
3096 * means that we must clean up the hash manually afterwards, but gives
3097 * us a 15% throughput increase.
3102 if (!hv_store(hseen,
3103 (char *) &sv, sizeof(sv), INT2PTR(SV*, cxt->tagnum), 0))
3107 * Store `sv' and everything beneath it, using appropriate routine.
3108 * Abort immediately if we get a non-zero status back.
3113 TRACEME(("storing 0x%"UVxf" tag #%d, type %d...",
3114 PTR2UV(sv), cxt->tagnum, type));
3117 HV *pkg = SvSTASH(sv);
3118 ret = store_blessed(cxt, sv, type, pkg);
3120 ret = SV_STORE(type)(cxt, sv);
3122 TRACEME(("%s (stored 0x%"UVxf", refcnt=%d, %s)",
3123 ret ? "FAILED" : "ok", PTR2UV(sv),
3124 SvREFCNT(sv), sv_reftype(sv, FALSE)));
3132 * Write magic number and system information into the file.
3133 * Layout is <magic> <network> [<len> <byteorder> <sizeof int> <sizeof long>
3134 * <sizeof ptr>] where <len> is the length of the byteorder hexa string.
3135 * All size and lenghts are written as single characters here.
3137 * Note that no byte ordering info is emitted when <network> is true, since
3138 * integers will be emitted in network order in that case.
3140 static int magic_write(stcxt_t *cxt)
3143 * Starting with 0.6, the "use_network_order" byte flag is also used to
3144 * indicate the version number of the binary image, encoded in the upper
3145 * bits. The bit 0 is always used to indicate network order.
3148 * Starting with 0.7, a full byte is dedicated to the minor version of
3149 * the binary format, which is incremented only when new markers are
3150 * introduced, for instance, but when backward compatibility is preserved.
3153 /* Make these at compile time. The WRITE() macro is sufficiently complex
3154 that it saves about 200 bytes doing it this way and only using it
3156 static const unsigned char network_file_header[] = {
3158 (STORABLE_BIN_MAJOR << 1) | 1,
3159 STORABLE_BIN_WRITE_MINOR
3161 static const unsigned char file_header[] = {
3163 (STORABLE_BIN_MAJOR << 1) | 0,
3164 STORABLE_BIN_WRITE_MINOR,
3165 /* sizeof the array includes the 0 byte at the end: */
3166 (char) sizeof (byteorderstr) - 1,
3168 (unsigned char) sizeof(int),
3169 (unsigned char) sizeof(long),
3170 (unsigned char) sizeof(char *),
3171 (unsigned char) sizeof(NV)
3173 const unsigned char *header;
3176 TRACEME(("magic_write on fd=%d", cxt->fio ? PerlIO_fileno(cxt->fio) : -1));
3178 if (cxt->netorder) {
3179 header = network_file_header;
3180 length = sizeof (network_file_header);
3182 header = file_header;
3183 length = sizeof (file_header);
3187 /* sizeof the array includes the 0 byte at the end. */
3188 header += sizeof (magicstr) - 1;
3189 length -= sizeof (magicstr) - 1;
3192 WRITE(header, length);
3194 if (!cxt->netorder) {
3195 TRACEME(("ok (magic_write byteorder = 0x%lx [%d], I%d L%d P%d D%d)",
3196 (unsigned long) BYTEORDER, (int) sizeof (byteorderstr) - 1,
3197 (int) sizeof(int), (int) sizeof(long),
3198 (int) sizeof(char *), (int) sizeof(NV)));
3206 * Common code for store operations.
3208 * When memory store is requested (f = NULL) and a non null SV* is given in
3209 * `res', it is filled with a new SV created out of the memory buffer.
3211 * It is required to provide a non-null `res' when the operation type is not
3212 * dclone() and store() is performed to memory.
3214 static int do_store(
3224 ASSERT(!(f == 0 && !(optype & ST_CLONE)) || res,
3225 ("must supply result SV pointer for real recursion to memory"));
3227 TRACEME(("do_store (optype=%d, netorder=%d)",
3228 optype, network_order));
3233 * Workaround for CROAK leak: if they enter with a "dirty" context,
3234 * free up memory for them now.
3241 * Now that STORABLE_xxx hooks exist, it is possible that they try to
3242 * re-enter store() via the hooks. We need to stack contexts.
3246 cxt = allocate_context(cxt);
3250 ASSERT(cxt->entry == 1, ("starting new recursion"));
3251 ASSERT(!cxt->s_dirty, ("clean context"));
3254 * Ensure sv is actually a reference. From perl, we called something
3256 * pstore(FILE, \@array);
3257 * so we must get the scalar value behing that reference.
3261 CROAK(("Not a reference"));
3262 sv = SvRV(sv); /* So follow it to know what to store */
3265 * If we're going to store to memory, reset the buffer.
3272 * Prepare context and emit headers.
3275 init_store_context(cxt, f, optype, network_order);
3277 if (-1 == magic_write(cxt)) /* Emit magic and ILP info */
3278 return 0; /* Error */
3281 * Recursively store object...
3284 ASSERT(is_storing(), ("within store operation"));
3286 status = store(cxt, sv); /* Just do it! */
3289 * If they asked for a memory store and they provided an SV pointer,
3290 * make an SV string out of the buffer and fill their pointer.
3292 * When asking for ST_REAL, it's MANDATORY for the caller to provide
3293 * an SV, since context cleanup might free the buffer if we did recurse.
3294 * (unless caller is dclone(), which is aware of that).
3297 if (!cxt->fio && res)
3303 * The "root" context is never freed, since it is meant to be always
3304 * handy for the common case where no recursion occurs at all (i.e.
3305 * we enter store() outside of any Storable code and leave it, period).
3306 * We know it's the "root" context because there's nothing stacked
3311 * When deep cloning, we don't free the context: doing so would force
3312 * us to copy the data in the memory buffer. Sicne we know we're
3313 * about to enter do_retrieve...
3316 clean_store_context(cxt);
3317 if (cxt->prev && !(cxt->optype & ST_CLONE))
3320 TRACEME(("do_store returns %d", status));
3328 * Store the transitive data closure of given object to disk.
3329 * Returns 0 on error, a true value otherwise.
3331 int pstore(PerlIO *f, SV *sv)
3333 TRACEME(("pstore"));
3334 return do_store(f, sv, 0, FALSE, (SV**) 0);
3341 * Same as pstore(), but network order is used for integers and doubles are
3342 * emitted as strings.
3344 int net_pstore(PerlIO *f, SV *sv)
3346 TRACEME(("net_pstore"));
3347 return do_store(f, sv, 0, TRUE, (SV**) 0);
3357 * Build a new SV out of the content of the internal memory buffer.
3359 static SV *mbuf2sv(void)
3363 return newSVpv(mbase, MBUF_SIZE());
3369 * Store the transitive data closure of given object to memory.
3370 * Returns undef on error, a scalar value containing the data otherwise.
3376 TRACEME(("mstore"));
3378 if (!do_store((PerlIO*) 0, sv, 0, FALSE, &out))
3379 return &PL_sv_undef;
3387 * Same as mstore(), but network order is used for integers and doubles are
3388 * emitted as strings.
3390 SV *net_mstore(SV *sv)
3394 TRACEME(("net_mstore"));
3396 if (!do_store((PerlIO*) 0, sv, 0, TRUE, &out))
3397 return &PL_sv_undef;
3403 *** Specific retrieve callbacks.
3409 * Return an error via croak, since it is not possible that we get here
3410 * under normal conditions, when facing a file produced via pstore().
3412 static SV *retrieve_other(stcxt_t *cxt, char *cname)
3415 cxt->ver_major != STORABLE_BIN_MAJOR &&
3416 cxt->ver_minor != STORABLE_BIN_MINOR
3418 CROAK(("Corrupted storable %s (binary v%d.%d), current is v%d.%d",
3419 cxt->fio ? "file" : "string",
3420 cxt->ver_major, cxt->ver_minor,
3421 STORABLE_BIN_MAJOR, STORABLE_BIN_MINOR));
3423 CROAK(("Corrupted storable %s (binary v%d.%d)",
3424 cxt->fio ? "file" : "string",
3425 cxt->ver_major, cxt->ver_minor));
3428 return (SV *) 0; /* Just in case */
3432 * retrieve_idx_blessed
3434 * Layout is SX_IX_BLESS <index> <object> with SX_IX_BLESS already read.
3435 * <index> can be coded on either 1 or 5 bytes.
3437 static SV *retrieve_idx_blessed(stcxt_t *cxt, char *cname)
3444 TRACEME(("retrieve_idx_blessed (#%d)", cxt->tagnum));
3445 ASSERT(!cname, ("no bless-into class given here, got %s", cname));
3447 GETMARK(idx); /* Index coded on a single char? */
3452 * Fetch classname in `aclass'
3455 sva = av_fetch(cxt->aclass, idx, FALSE);
3457 CROAK(("Class name #%"IVdf" should have been seen already", (IV) idx));
3459 class = SvPVX(*sva); /* We know it's a PV, by construction */
3461 TRACEME(("class ID %d => %s", idx, class));
3464 * Retrieve object and bless it.
3467 sv = retrieve(cxt, class); /* First SV which is SEEN will be blessed */
3475 * Layout is SX_BLESS <len> <classname> <object> with SX_BLESS already read.
3476 * <len> can be coded on either 1 or 5 bytes.
3478 static SV *retrieve_blessed(stcxt_t *cxt, char *cname)
3482 char buf[LG_BLESS + 1]; /* Avoid malloc() if possible */
3485 TRACEME(("retrieve_blessed (#%d)", cxt->tagnum));
3486 ASSERT(!cname, ("no bless-into class given here, got %s", cname));
3489 * Decode class name length and read that name.
3491 * Short classnames have two advantages: their length is stored on one
3492 * single byte, and the string can be read on the stack.
3495 GETMARK(len); /* Length coded on a single char? */
3498 TRACEME(("** allocating %d bytes for class name", len+1));
3499 New(10003, class, len+1, char);
3502 class[len] = '\0'; /* Mark string end */
3505 * It's a new classname, otherwise it would have been an SX_IX_BLESS.
3508 TRACEME(("new class name \"%s\" will bear ID = %d", class, cxt->classnum));
3510 if (!av_store(cxt->aclass, cxt->classnum++, newSVpvn(class, len)))
3514 * Retrieve object and bless it.
3517 sv = retrieve(cxt, class); /* First SV which is SEEN will be blessed */
3527 * Layout: SX_HOOK <flags> <len> <classname> <len2> <str> [<len3> <object-IDs>]
3528 * with leading mark already read, as usual.
3530 * When recursion was involved during serialization of the object, there
3531 * is an unknown amount of serialized objects after the SX_HOOK mark. Until
3532 * we reach a <flags> marker with the recursion bit cleared.
3534 * If the first <flags> byte contains a type of SHT_EXTRA, then the real type
3535 * is held in the <extra> byte, and if the object is tied, the serialized
3536 * magic object comes at the very end:
3538 * SX_HOOK <flags> <extra> ... [<len3> <object-IDs>] <magic object>
3540 * This means the STORABLE_thaw hook will NOT get a tied variable during its
3541 * processing (since we won't have seen the magic object by the time the hook
3542 * is called). See comments below for why it was done that way.
3544 static SV *retrieve_hook(stcxt_t *cxt, char *cname)
3547 char buf[LG_BLESS + 1]; /* Avoid malloc() if possible */
3558 int clone = cxt->optype & ST_CLONE;
3560 unsigned int extra_type = 0;
3562 TRACEME(("retrieve_hook (#%d)", cxt->tagnum));
3563 ASSERT(!cname, ("no bless-into class given here, got %s", cname));
3566 * Read flags, which tell us about the type, and whether we need to recurse.
3572 * Create the (empty) object, and mark it as seen.
3574 * This must be done now, because tags are incremented, and during
3575 * serialization, the object tag was affected before recursion could
3579 obj_type = flags & SHF_TYPE_MASK;
3585 sv = (SV *) newAV();
3588 sv = (SV *) newHV();
3592 * Read <extra> flag to know the type of the object.
3593 * Record associated magic type for later.
3595 GETMARK(extra_type);
3596 switch (extra_type) {
3602 sv = (SV *) newAV();
3606 sv = (SV *) newHV();
3610 return retrieve_other(cxt, 0); /* Let it croak */
3614 return retrieve_other(cxt, 0); /* Let it croak */
3616 SEEN(sv, 0); /* Don't bless yet */
3619 * Whilst flags tell us to recurse, do so.
3621 * We don't need to remember the addresses returned by retrieval, because
3622 * all the references will be obtained through indirection via the object
3623 * tags in the object-ID list.
3626 while (flags & SHF_NEED_RECURSE) {
3627 TRACEME(("retrieve_hook recursing..."));
3628 rv = retrieve(cxt, 0);
3631 TRACEME(("retrieve_hook back with rv=0x%"UVxf,
3636 if (flags & SHF_IDX_CLASSNAME) {
3641 * Fetch index from `aclass'
3644 if (flags & SHF_LARGE_CLASSLEN)
3649 sva = av_fetch(cxt->aclass, idx, FALSE);
3651 CROAK(("Class name #%"IVdf" should have been seen already",
3654 class = SvPVX(*sva); /* We know it's a PV, by construction */
3655 TRACEME(("class ID %d => %s", idx, class));
3659 * Decode class name length and read that name.
3661 * NOTA BENE: even if the length is stored on one byte, we don't read
3662 * on the stack. Just like retrieve_blessed(), we limit the name to
3663 * LG_BLESS bytes. This is an arbitrary decision.
3666 if (flags & SHF_LARGE_CLASSLEN)
3671 if (len > LG_BLESS) {
3672 TRACEME(("** allocating %d bytes for class name", len+1));
3673 New(10003, class, len+1, char);
3677 class[len] = '\0'; /* Mark string end */
3680 * Record new classname.
3683 if (!av_store(cxt->aclass, cxt->classnum++, newSVpvn(class, len)))
3687 TRACEME(("class name: %s", class));
3690 * Decode user-frozen string length and read it in an SV.
3692 * For efficiency reasons, we read data directly into the SV buffer.
3693 * To understand that code, read retrieve_scalar()
3696 if (flags & SHF_LARGE_STRLEN)
3701 frozen = NEWSV(10002, len2);
3703 SAFEREAD(SvPVX(frozen), len2, frozen);
3704 SvCUR_set(frozen, len2);
3705 *SvEND(frozen) = '\0';
3707 (void) SvPOK_only(frozen); /* Validates string pointer */
3708 if (cxt->s_tainted) /* Is input source tainted? */
3711 TRACEME(("frozen string: %d bytes", len2));
3714 * Decode object-ID list length, if present.
3717 if (flags & SHF_HAS_LIST) {
3718 if (flags & SHF_LARGE_LISTLEN)
3724 av_extend(av, len3 + 1); /* Leave room for [0] */
3725 AvFILLp(av) = len3; /* About to be filled anyway */
3729 TRACEME(("has %d object IDs to link", len3));
3732 * Read object-ID list into array.
3733 * Because we pre-extended it, we can cheat and fill it manually.
3735 * We read object tags and we can convert them into SV* on the fly
3736 * because we know all the references listed in there (as tags)
3737 * have been already serialized, hence we have a valid correspondance
3738 * between each of those tags and the recreated SV.
3742 SV **ary = AvARRAY(av);
3744 for (i = 1; i <= len3; i++) { /* We leave [0] alone */
3751 svh = av_fetch(cxt->aseen, tag, FALSE);
3753 CROAK(("Object #%"IVdf" should have been retrieved already",
3756 ary[i] = SvREFCNT_inc(xsv);
3761 * Bless the object and look up the STORABLE_thaw hook.
3765 hook = pkg_can(cxt->hook, SvSTASH(sv), "STORABLE_thaw");
3768 * Hook not found. Maybe they did not require the module where this
3769 * hook is defined yet?
3771 * If the require below succeeds, we'll be able to find the hook.
3772 * Still, it only works reliably when each class is defined in a
3776 SV *psv = newSVpvn("require ", 8);
3777 sv_catpv(psv, class);
3779 TRACEME(("No STORABLE_thaw defined for objects of class %s", class));
3780 TRACEME(("Going to require module '%s' with '%s'", class, SvPVX(psv)));
3782 perl_eval_sv(psv, G_DISCARD);
3786 * We cache results of pkg_can, so we need to uncache before attempting
3790 pkg_uncache(cxt->hook, SvSTASH(sv), "STORABLE_thaw");
3791 hook = pkg_can(cxt->hook, SvSTASH(sv), "STORABLE_thaw");
3794 CROAK(("No STORABLE_thaw defined for objects of class %s "
3795 "(even after a \"require %s;\")", class, class));
3799 * If we don't have an `av' yet, prepare one.
3800 * Then insert the frozen string as item [0].
3808 AvARRAY(av)[0] = SvREFCNT_inc(frozen);
3813 * $object->STORABLE_thaw($cloning, $frozen, @refs);
3815 * where $object is our blessed (empty) object, $cloning is a boolean
3816 * telling whether we're running a deep clone, $frozen is the frozen
3817 * string the user gave us in his serializing hook, and @refs, which may
3818 * be empty, is the list of extra references he returned along for us
3821 * In effect, the hook is an alternate creation routine for the class,
3822 * the object itself being already created by the runtime.
3825 TRACEME(("calling STORABLE_thaw on %s at 0x%"UVxf" (%"IVdf" args)",
3826 class, PTR2UV(sv), (IV) AvFILLp(av) + 1));
3829 (void) scalar_call(rv, hook, clone, av, G_SCALAR|G_DISCARD);
3836 SvREFCNT_dec(frozen);
3839 if (!(flags & SHF_IDX_CLASSNAME) && class != buf)
3843 * If we had an <extra> type, then the object was not as simple, and
3844 * we need to restore extra magic now.
3850 TRACEME(("retrieving magic object for 0x%"UVxf"...", PTR2UV(sv)));
3852 rv = retrieve(cxt, 0); /* Retrieve <magic object> */
3854 TRACEME(("restoring the magic object 0x%"UVxf" part of 0x%"UVxf,
3855 PTR2UV(rv), PTR2UV(sv)));
3857 switch (extra_type) {
3859 sv_upgrade(sv, SVt_PVMG);
3862 sv_upgrade(sv, SVt_PVAV);
3863 AvREAL_off((AV *)sv);
3866 sv_upgrade(sv, SVt_PVHV);
3869 CROAK(("Forgot to deal with extra type %d", extra_type));
3874 * Adding the magic only now, well after the STORABLE_thaw hook was called
3875 * means the hook cannot know it deals with an object whose variable is
3876 * tied. But this is happening when retrieving $o in the following case:
3880 * my $o = bless \%h, 'BAR';
3882 * The 'BAR' class is NOT the one where %h is tied into. Therefore, as
3883 * far as the 'BAR' class is concerned, the fact that %h is not a REAL
3884 * hash but a tied one should not matter at all, and remain transparent.
3885 * This means the magic must be restored by Storable AFTER the hook is
3888 * That looks very reasonable to me, but then I've come up with this
3889 * after a bug report from David Nesting, who was trying to store such
3890 * an object and caused Storable to fail. And unfortunately, it was
3891 * also the easiest way to retrofit support for blessed ref to tied objects
3892 * into the existing design. -- RAM, 17/02/2001
3895 sv_magic(sv, rv, mtype, Nullch, 0);
3896 SvREFCNT_dec(rv); /* Undo refcnt inc from sv_magic() */
3904 * Retrieve reference to some other scalar.
3905 * Layout is SX_REF <object>, with SX_REF already read.
3907 static SV *retrieve_ref(stcxt_t *cxt, char *cname)
3912 TRACEME(("retrieve_ref (#%d)", cxt->tagnum));
3915 * We need to create the SV that holds the reference to the yet-to-retrieve
3916 * object now, so that we may record the address in the seen table.
3917 * Otherwise, if the object to retrieve references us, we won't be able
3918 * to resolve the SX_OBJECT we'll see at that point! Hence we cannot
3919 * do the retrieve first and use rv = newRV(sv) since it will be too late
3920 * for SEEN() recording.
3923 rv = NEWSV(10002, 0);
3924 SEEN(rv, cname); /* Will return if rv is null */
3925 sv = retrieve(cxt, 0); /* Retrieve <object> */
3927 return (SV *) 0; /* Failed */
3930 * WARNING: breaks RV encapsulation.
3932 * Now for the tricky part. We have to upgrade our existing SV, so that
3933 * it is now an RV on sv... Again, we cheat by duplicating the code
3934 * held in newSVrv(), since we already got our SV from retrieve().
3938 * SvRV(rv) = SvREFCNT_inc(sv);
3940 * here because the reference count we got from retrieve() above is
3941 * already correct: if the object was retrieved from the file, then
3942 * its reference count is one. Otherwise, if it was retrieved via
3943 * an SX_OBJECT indication, a ref count increment was done.
3946 sv_upgrade(rv, SVt_RV);
3947 SvRV(rv) = sv; /* $rv = \$sv */
3950 TRACEME(("ok (retrieve_ref at 0x%"UVxf")", PTR2UV(rv)));
3956 * retrieve_overloaded
3958 * Retrieve reference to some other scalar with overloading.
3959 * Layout is SX_OVERLOAD <object>, with SX_OVERLOAD already read.
3961 static SV *retrieve_overloaded(stcxt_t *cxt, char *cname)
3967 TRACEME(("retrieve_overloaded (#%d)", cxt->tagnum));
3970 * Same code as retrieve_ref(), duplicated to avoid extra call.
3973 rv = NEWSV(10002, 0);
3974 SEEN(rv, cname); /* Will return if rv is null */
3975 sv = retrieve(cxt, 0); /* Retrieve <object> */
3977 return (SV *) 0; /* Failed */
3980 * WARNING: breaks RV encapsulation.
3983 sv_upgrade(rv, SVt_RV);
3984 SvRV(rv) = sv; /* $rv = \$sv */
3988 * Restore overloading magic.
3991 stash = (HV *) SvSTASH (sv);
3992 if (!stash || !Gv_AMG(stash))
3993 CROAK(("Cannot restore overloading on %s(0x%"UVxf") (package %s)",
3994 sv_reftype(sv, FALSE),
3996 stash ? HvNAME(stash) : "<unknown>"));
4000 TRACEME(("ok (retrieve_overloaded at 0x%"UVxf")", PTR2UV(rv)));
4006 * retrieve_tied_array
4008 * Retrieve tied array
4009 * Layout is SX_TIED_ARRAY <object>, with SX_TIED_ARRAY already read.
4011 static SV *retrieve_tied_array(stcxt_t *cxt, char *cname)
4016 TRACEME(("retrieve_tied_array (#%d)", cxt->tagnum));
4018 tv = NEWSV(10002, 0);
4019 SEEN(tv, cname); /* Will return if tv is null */
4020 sv = retrieve(cxt, 0); /* Retrieve <object> */
4022 return (SV *) 0; /* Failed */
4024 sv_upgrade(tv, SVt_PVAV);
4025 AvREAL_off((AV *)tv);
4026 sv_magic(tv, sv, 'P', Nullch, 0);
4027 SvREFCNT_dec(sv); /* Undo refcnt inc from sv_magic() */
4029 TRACEME(("ok (retrieve_tied_array at 0x%"UVxf")", PTR2UV(tv)));
4035 * retrieve_tied_hash
4037 * Retrieve tied hash
4038 * Layout is SX_TIED_HASH <object>, with SX_TIED_HASH already read.
4040 static SV *retrieve_tied_hash(stcxt_t *cxt, char *cname)
4045 TRACEME(("retrieve_tied_hash (#%d)", cxt->tagnum));
4047 tv = NEWSV(10002, 0);
4048 SEEN(tv, cname); /* Will return if tv is null */
4049 sv = retrieve(cxt, 0); /* Retrieve <object> */
4051 return (SV *) 0; /* Failed */
4053 sv_upgrade(tv, SVt_PVHV);
4054 sv_magic(tv, sv, 'P', Nullch, 0);
4055 SvREFCNT_dec(sv); /* Undo refcnt inc from sv_magic() */
4057 TRACEME(("ok (retrieve_tied_hash at 0x%"UVxf")", PTR2UV(tv)));
4063 * retrieve_tied_scalar
4065 * Retrieve tied scalar
4066 * Layout is SX_TIED_SCALAR <object>, with SX_TIED_SCALAR already read.
4068 static SV *retrieve_tied_scalar(stcxt_t *cxt, char *cname)
4073 TRACEME(("retrieve_tied_scalar (#%d)", cxt->tagnum));
4075 tv = NEWSV(10002, 0);
4076 SEEN(tv, cname); /* Will return if rv is null */
4077 sv = retrieve(cxt, 0); /* Retrieve <object> */
4079 return (SV *) 0; /* Failed */
4081 sv_upgrade(tv, SVt_PVMG);
4082 sv_magic(tv, sv, 'q', Nullch, 0);
4083 SvREFCNT_dec(sv); /* Undo refcnt inc from sv_magic() */
4085 TRACEME(("ok (retrieve_tied_scalar at 0x%"UVxf")", PTR2UV(tv)));
4093 * Retrieve reference to value in a tied hash.
4094 * Layout is SX_TIED_KEY <object> <key>, with SX_TIED_KEY already read.
4096 static SV *retrieve_tied_key(stcxt_t *cxt, char *cname)
4102 TRACEME(("retrieve_tied_key (#%d)", cxt->tagnum));
4104 tv = NEWSV(10002, 0);
4105 SEEN(tv, cname); /* Will return if tv is null */
4106 sv = retrieve(cxt, 0); /* Retrieve <object> */
4108 return (SV *) 0; /* Failed */
4110 key = retrieve(cxt, 0); /* Retrieve <key> */
4112 return (SV *) 0; /* Failed */
4114 sv_upgrade(tv, SVt_PVMG);
4115 sv_magic(tv, sv, 'p', (char *)key, HEf_SVKEY);
4116 SvREFCNT_dec(key); /* Undo refcnt inc from sv_magic() */
4117 SvREFCNT_dec(sv); /* Undo refcnt inc from sv_magic() */
4125 * Retrieve reference to value in a tied array.
4126 * Layout is SX_TIED_IDX <object> <idx>, with SX_TIED_IDX already read.
4128 static SV *retrieve_tied_idx(stcxt_t *cxt, char *cname)
4134 TRACEME(("retrieve_tied_idx (#%d)", cxt->tagnum));
4136 tv = NEWSV(10002, 0);
4137 SEEN(tv, cname); /* Will return if tv is null */
4138 sv = retrieve(cxt, 0); /* Retrieve <object> */
4140 return (SV *) 0; /* Failed */
4142 RLEN(idx); /* Retrieve <idx> */
4144 sv_upgrade(tv, SVt_PVMG);
4145 sv_magic(tv, sv, 'p', Nullch, idx);
4146 SvREFCNT_dec(sv); /* Undo refcnt inc from sv_magic() */
4155 * Retrieve defined long (string) scalar.
4157 * Layout is SX_LSCALAR <length> <data>, with SX_LSCALAR already read.
4158 * The scalar is "long" in that <length> is larger than LG_SCALAR so it
4159 * was not stored on a single byte.
4161 static SV *retrieve_lscalar(stcxt_t *cxt, char *cname)
4167 TRACEME(("retrieve_lscalar (#%d), len = %"IVdf, cxt->tagnum, (IV) len));
4170 * Allocate an empty scalar of the suitable length.
4173 sv = NEWSV(10002, len);
4174 SEEN(sv, cname); /* Associate this new scalar with tag "tagnum" */
4177 * WARNING: duplicates parts of sv_setpv and breaks SV data encapsulation.
4179 * Now, for efficiency reasons, read data directly inside the SV buffer,
4180 * and perform the SV final settings directly by duplicating the final
4181 * work done by sv_setpv. Since we're going to allocate lots of scalars
4182 * this way, it's worth the hassle and risk.
4185 SAFEREAD(SvPVX(sv), len, sv);
4186 SvCUR_set(sv, len); /* Record C string length */
4187 *SvEND(sv) = '\0'; /* Ensure it's null terminated anyway */
4188 (void) SvPOK_only(sv); /* Validate string pointer */
4189 if (cxt->s_tainted) /* Is input source tainted? */
4190 SvTAINT(sv); /* External data cannot be trusted */
4192 TRACEME(("large scalar len %"IVdf" '%s'", (IV) len, SvPVX(sv)));
4193 TRACEME(("ok (retrieve_lscalar at 0x%"UVxf")", PTR2UV(sv)));
4201 * Retrieve defined short (string) scalar.
4203 * Layout is SX_SCALAR <length> <data>, with SX_SCALAR already read.
4204 * The scalar is "short" so <length> is single byte. If it is 0, there
4205 * is no <data> section.
4207 static SV *retrieve_scalar(stcxt_t *cxt, char *cname)
4213 TRACEME(("retrieve_scalar (#%d), len = %d", cxt->tagnum, len));
4216 * Allocate an empty scalar of the suitable length.
4219 sv = NEWSV(10002, len);
4220 SEEN(sv, cname); /* Associate this new scalar with tag "tagnum" */
4223 * WARNING: duplicates parts of sv_setpv and breaks SV data encapsulation.
4228 * newSV did not upgrade to SVt_PV so the scalar is undefined.
4229 * To make it defined with an empty length, upgrade it now...
4230 * Don't upgrade to a PV if the original type contains more
4231 * information than a scalar.
4233 if (SvTYPE(sv) <= SVt_PV) {
4234 sv_upgrade(sv, SVt_PV);
4237 *SvEND(sv) = '\0'; /* Ensure it's null terminated anyway */
4238 TRACEME(("ok (retrieve_scalar empty at 0x%"UVxf")", PTR2UV(sv)));
4241 * Now, for efficiency reasons, read data directly inside the SV buffer,
4242 * and perform the SV final settings directly by duplicating the final
4243 * work done by sv_setpv. Since we're going to allocate lots of scalars
4244 * this way, it's worth the hassle and risk.
4246 SAFEREAD(SvPVX(sv), len, sv);
4247 SvCUR_set(sv, len); /* Record C string length */
4248 *SvEND(sv) = '\0'; /* Ensure it's null terminated anyway */
4249 TRACEME(("small scalar len %d '%s'", len, SvPVX(sv)));
4252 (void) SvPOK_only(sv); /* Validate string pointer */
4253 if (cxt->s_tainted) /* Is input source tainted? */
4254 SvTAINT(sv); /* External data cannot be trusted */
4256 TRACEME(("ok (retrieve_scalar at 0x%"UVxf")", PTR2UV(sv)));
4263 * Like retrieve_scalar(), but tag result as utf8.
4264 * If we're retrieving UTF8 data in a non-UTF8 perl, croaks.
4266 static SV *retrieve_utf8str(stcxt_t *cxt, char *cname)
4270 TRACEME(("retrieve_utf8str"));
4272 sv = retrieve_scalar(cxt, cname);
4274 #ifdef HAS_UTF8_SCALARS
4277 if (cxt->use_bytes < 0)
4279 = (SvTRUE(perl_get_sv("Storable::drop_utf8", TRUE))
4281 if (cxt->use_bytes == 0)
4292 * Like retrieve_lscalar(), but tag result as utf8.
4293 * If we're retrieving UTF8 data in a non-UTF8 perl, croaks.
4295 static SV *retrieve_lutf8str(stcxt_t *cxt, char *cname)
4299 TRACEME(("retrieve_lutf8str"));
4301 sv = retrieve_lscalar(cxt, cname);
4303 #ifdef HAS_UTF8_SCALARS
4306 if (cxt->use_bytes < 0)
4308 = (SvTRUE(perl_get_sv("Storable::drop_utf8", TRUE))
4310 if (cxt->use_bytes == 0)
4320 * Retrieve defined integer.
4321 * Layout is SX_INTEGER <data>, whith SX_INTEGER already read.
4323 static SV *retrieve_integer(stcxt_t *cxt, char *cname)
4328 TRACEME(("retrieve_integer (#%d)", cxt->tagnum));
4330 READ(&iv, sizeof(iv));
4332 SEEN(sv, cname); /* Associate this new scalar with tag "tagnum" */
4334 TRACEME(("integer %"IVdf, iv));
4335 TRACEME(("ok (retrieve_integer at 0x%"UVxf")", PTR2UV(sv)));
4343 * Retrieve defined integer in network order.
4344 * Layout is SX_NETINT <data>, whith SX_NETINT already read.
4346 static SV *retrieve_netint(stcxt_t *cxt, char *cname)
4351 TRACEME(("retrieve_netint (#%d)", cxt->tagnum));
4355 sv = newSViv((int) ntohl(iv));
4356 TRACEME(("network integer %d", (int) ntohl(iv)));
4359 TRACEME(("network integer (as-is) %d", iv));
4361 SEEN(sv, cname); /* Associate this new scalar with tag "tagnum" */
4363 TRACEME(("ok (retrieve_netint at 0x%"UVxf")", PTR2UV(sv)));
4371 * Retrieve defined double.
4372 * Layout is SX_DOUBLE <data>, whith SX_DOUBLE already read.
4374 static SV *retrieve_double(stcxt_t *cxt, char *cname)
4379 TRACEME(("retrieve_double (#%d)", cxt->tagnum));
4381 READ(&nv, sizeof(nv));
4383 SEEN(sv, cname); /* Associate this new scalar with tag "tagnum" */
4385 TRACEME(("double %"NVff, nv));
4386 TRACEME(("ok (retrieve_double at 0x%"UVxf")", PTR2UV(sv)));
4394 * Retrieve defined byte (small integer within the [-128, +127] range).
4395 * Layout is SX_BYTE <data>, whith SX_BYTE already read.
4397 static SV *retrieve_byte(stcxt_t *cxt, char *cname)
4401 signed char tmp; /* Workaround for AIX cc bug --H.Merijn Brand */
4403 TRACEME(("retrieve_byte (#%d)", cxt->tagnum));
4406 TRACEME(("small integer read as %d", (unsigned char) siv));
4407 tmp = (unsigned char) siv - 128;
4409 SEEN(sv, cname); /* Associate this new scalar with tag "tagnum" */
4411 TRACEME(("byte %d", tmp));
4412 TRACEME(("ok (retrieve_byte at 0x%"UVxf")", PTR2UV(sv)));
4420 * Return the undefined value.
4422 static SV *retrieve_undef(stcxt_t *cxt, char *cname)
4426 TRACEME(("retrieve_undef"));
4437 * Return the immortal undefined value.
4439 static SV *retrieve_sv_undef(stcxt_t *cxt, char *cname)
4441 SV *sv = &PL_sv_undef;
4443 TRACEME(("retrieve_sv_undef"));
4452 * Return the immortal yes value.
4454 static SV *retrieve_sv_yes(stcxt_t *cxt, char *cname)
4456 SV *sv = &PL_sv_yes;
4458 TRACEME(("retrieve_sv_yes"));
4467 * Return the immortal no value.
4469 static SV *retrieve_sv_no(stcxt_t *cxt, char *cname)
4473 TRACEME(("retrieve_sv_no"));
4482 * Retrieve a whole array.
4483 * Layout is SX_ARRAY <size> followed by each item, in increading index order.
4484 * Each item is stored as <object>.
4486 * When we come here, SX_ARRAY has been read already.
4488 static SV *retrieve_array(stcxt_t *cxt, char *cname)
4495 TRACEME(("retrieve_array (#%d)", cxt->tagnum));
4498 * Read length, and allocate array, then pre-extend it.
4502 TRACEME(("size = %d", len));
4504 SEEN(av, cname); /* Will return if array not allocated nicely */
4508 return (SV *) av; /* No data follow if array is empty */
4511 * Now get each item in turn...
4514 for (i = 0; i < len; i++) {
4515 TRACEME(("(#%d) item", i));
4516 sv = retrieve(cxt, 0); /* Retrieve item */
4519 if (av_store(av, i, sv) == 0)
4523 TRACEME(("ok (retrieve_array at 0x%"UVxf")", PTR2UV(av)));
4531 * Retrieve a whole hash table.
4532 * Layout is SX_HASH <size> followed by each key/value pair, in random order.
4533 * Keys are stored as <length> <data>, the <data> section being omitted
4535 * Values are stored as <object>.
4537 * When we come here, SX_HASH has been read already.
4539 static SV *retrieve_hash(stcxt_t *cxt, char *cname)
4547 TRACEME(("retrieve_hash (#%d)", cxt->tagnum));
4550 * Read length, allocate table.
4554 TRACEME(("size = %d", len));
4556 SEEN(hv, cname); /* Will return if table not allocated properly */
4558 return (SV *) hv; /* No data follow if table empty */
4559 hv_ksplit(hv, len); /* pre-extend hash to save multiple splits */
4562 * Now get each key/value pair in turn...
4565 for (i = 0; i < len; i++) {
4570 TRACEME(("(#%d) value", i));
4571 sv = retrieve(cxt, 0);
4577 * Since we're reading into kbuf, we must ensure we're not
4578 * recursing between the read and the hv_store() where it's used.
4579 * Hence the key comes after the value.
4582 RLEN(size); /* Get key size */
4583 KBUFCHK((STRLEN)size); /* Grow hash key read pool if needed */
4586 kbuf[size] = '\0'; /* Mark string end, just in case */
4587 TRACEME(("(#%d) key '%s'", i, kbuf));
4590 * Enter key/value pair into hash table.
4593 if (hv_store(hv, kbuf, (U32) size, sv, 0) == 0)
4597 TRACEME(("ok (retrieve_hash at 0x%"UVxf")", PTR2UV(hv)));
4605 * Retrieve a whole hash table.
4606 * Layout is SX_HASH <size> followed by each key/value pair, in random order.
4607 * Keys are stored as <length> <data>, the <data> section being omitted
4609 * Values are stored as <object>.
4611 * When we come here, SX_HASH has been read already.
4613 static SV *retrieve_flag_hash(stcxt_t *cxt, char *cname)
4622 GETMARK(hash_flags);
4623 TRACEME(("retrieve_flag_hash (#%d)", cxt->tagnum));
4625 * Read length, allocate table.
4628 #ifndef HAS_RESTRICTED_HASHES
4629 if (hash_flags & SHV_RESTRICTED) {
4630 if (cxt->derestrict < 0)
4632 = (SvTRUE(perl_get_sv("Storable::downgrade_restricted", TRUE))
4634 if (cxt->derestrict == 0)
4635 RESTRICTED_HASH_CROAK();
4640 TRACEME(("size = %d, flags = %d", len, hash_flags));
4642 SEEN(hv, cname); /* Will return if table not allocated properly */
4644 return (SV *) hv; /* No data follow if table empty */
4645 hv_ksplit(hv, len); /* pre-extend hash to save multiple splits */
4648 * Now get each key/value pair in turn...
4651 for (i = 0; i < len; i++) {
4653 int store_flags = 0;
4658 TRACEME(("(#%d) value", i));
4659 sv = retrieve(cxt, 0);
4664 #ifdef HAS_RESTRICTED_HASHES
4665 if ((hash_flags & SHV_RESTRICTED) && (flags & SHV_K_LOCKED))
4669 if (flags & SHV_K_ISSV) {
4670 /* XXX you can't set a placeholder with an SV key.
4671 Then again, you can't get an SV key.
4672 Without messing around beyond what the API is supposed to do.
4675 TRACEME(("(#%d) keysv, flags=%d", i, flags));
4676 keysv = retrieve(cxt, 0);
4680 if (!hv_store_ent(hv, keysv, sv, 0))
4685 * Since we're reading into kbuf, we must ensure we're not
4686 * recursing between the read and the hv_store() where it's used.
4687 * Hence the key comes after the value.
4690 if (flags & SHV_K_PLACEHOLDER) {
4693 store_flags |= HVhek_PLACEHOLD;
4695 if (flags & SHV_K_UTF8) {
4696 #ifdef HAS_UTF8_HASHES
4697 store_flags |= HVhek_UTF8;
4699 if (cxt->use_bytes < 0)
4701 = (SvTRUE(perl_get_sv("Storable::drop_utf8", TRUE))
4703 if (cxt->use_bytes == 0)
4707 #ifdef HAS_UTF8_HASHES
4708 if (flags & SHV_K_WASUTF8)
4709 store_flags |= HVhek_WASUTF8;
4712 RLEN(size); /* Get key size */
4713 KBUFCHK((STRLEN)size); /* Grow hash key read pool if needed */
4716 kbuf[size] = '\0'; /* Mark string end, just in case */
4717 TRACEME(("(#%d) key '%s' flags %X store_flags %X", i, kbuf,
4718 flags, store_flags));
4721 * Enter key/value pair into hash table.
4724 #ifdef HAS_RESTRICTED_HASHES
4725 if (hv_store_flags(hv, kbuf, size, sv, 0, flags) == 0)
4728 if (!(store_flags & HVhek_PLACEHOLD))
4729 if (hv_store(hv, kbuf, size, sv, 0) == 0)
4734 #ifdef HAS_RESTRICTED_HASHES
4735 if (hash_flags & SHV_RESTRICTED)
4739 TRACEME(("ok (retrieve_hash at 0x%"UVxf")", PTR2UV(hv)));
4745 * old_retrieve_array
4747 * Retrieve a whole array in pre-0.6 binary format.
4749 * Layout is SX_ARRAY <size> followed by each item, in increading index order.
4750 * Each item is stored as SX_ITEM <object> or SX_IT_UNDEF for "holes".
4752 * When we come here, SX_ARRAY has been read already.
4754 static SV *old_retrieve_array(stcxt_t *cxt, char *cname)
4762 TRACEME(("old_retrieve_array (#%d)", cxt->tagnum));
4765 * Read length, and allocate array, then pre-extend it.
4769 TRACEME(("size = %d", len));
4771 SEEN(av, 0); /* Will return if array not allocated nicely */
4775 return (SV *) av; /* No data follow if array is empty */
4778 * Now get each item in turn...
4781 for (i = 0; i < len; i++) {
4783 if (c == SX_IT_UNDEF) {
4784 TRACEME(("(#%d) undef item", i));
4785 continue; /* av_extend() already filled us with undef */
4788 (void) retrieve_other((stcxt_t *) 0, 0); /* Will croak out */
4789 TRACEME(("(#%d) item", i));
4790 sv = retrieve(cxt, 0); /* Retrieve item */
4793 if (av_store(av, i, sv) == 0)
4797 TRACEME(("ok (old_retrieve_array at 0x%"UVxf")", PTR2UV(av)));
4805 * Retrieve a whole hash table in pre-0.6 binary format.
4807 * Layout is SX_HASH <size> followed by each key/value pair, in random order.
4808 * Keys are stored as SX_KEY <length> <data>, the <data> section being omitted
4810 * Values are stored as SX_VALUE <object> or SX_VL_UNDEF for "holes".
4812 * When we come here, SX_HASH has been read already.
4814 static SV *old_retrieve_hash(stcxt_t *cxt, char *cname)
4822 static SV *sv_h_undef = (SV *) 0; /* hv_store() bug */
4824 TRACEME(("old_retrieve_hash (#%d)", cxt->tagnum));
4827 * Read length, allocate table.
4831 TRACEME(("size = %d", len));
4833 SEEN(hv, 0); /* Will return if table not allocated properly */
4835 return (SV *) hv; /* No data follow if table empty */
4836 hv_ksplit(hv, len); /* pre-extend hash to save multiple splits */
4839 * Now get each key/value pair in turn...
4842 for (i = 0; i < len; i++) {
4848 if (c == SX_VL_UNDEF) {
4849 TRACEME(("(#%d) undef value", i));
4851 * Due to a bug in hv_store(), it's not possible to pass
4852 * &PL_sv_undef to hv_store() as a value, otherwise the
4853 * associated key will not be creatable any more. -- RAM, 14/01/97
4856 sv_h_undef = newSVsv(&PL_sv_undef);
4857 sv = SvREFCNT_inc(sv_h_undef);
4858 } else if (c == SX_VALUE) {
4859 TRACEME(("(#%d) value", i));
4860 sv = retrieve(cxt, 0);
4864 (void) retrieve_other((stcxt_t *) 0, 0); /* Will croak out */
4868 * Since we're reading into kbuf, we must ensure we're not
4869 * recursing between the read and the hv_store() where it's used.
4870 * Hence the key comes after the value.
4875 (void) retrieve_other((stcxt_t *) 0, 0); /* Will croak out */
4876 RLEN(size); /* Get key size */
4877 KBUFCHK((STRLEN)size); /* Grow hash key read pool if needed */
4880 kbuf[size] = '\0'; /* Mark string end, just in case */
4881 TRACEME(("(#%d) key '%s'", i, kbuf));
4884 * Enter key/value pair into hash table.
4887 if (hv_store(hv, kbuf, (U32) size, sv, 0) == 0)
4891 TRACEME(("ok (retrieve_hash at 0x%"UVxf")", PTR2UV(hv)));
4897 *** Retrieval engine.
4903 * Make sure the stored data we're trying to retrieve has been produced
4904 * on an ILP compatible system with the same byteorder. It croaks out in
4905 * case an error is detected. [ILP = integer-long-pointer sizes]
4906 * Returns null if error is detected, &PL_sv_undef otherwise.
4908 * Note that there's no byte ordering info emitted when network order was
4909 * used at store time.
4911 static SV *magic_check(stcxt_t *cxt)
4913 /* The worst case for a malicious header would be old magic (which is
4914 longer), major, minor, byteorder length byte of 255, 255 bytes of
4915 garbage, sizeof int, long, pointer, NV.
4916 So the worse of that we can read is 255 bytes of garbage plus 4.
4917 Err, I am assuming 8 bit bytes here. Please file a bug report if you're
4918 compiling perl on a system with chars that are larger than 8 bits.
4919 (Even Crays aren't *that* perverse).
4921 unsigned char buf[4 + 255];
4922 unsigned char *current;
4925 int use_network_order;
4928 int version_minor = 0;
4930 TRACEME(("magic_check"));
4933 * The "magic number" is only for files, not when freezing in memory.
4937 /* This includes the '\0' at the end. I want to read the extra byte,
4938 which is usually going to be the major version number. */
4939 STRLEN len = sizeof(magicstr);
4942 READ(buf, (SSize_t)(len)); /* Not null-terminated */
4944 /* Point at the byte after the byte we read. */
4945 current = buf + --len; /* Do the -- outside of macros. */
4947 if (memNE(buf, magicstr, len)) {
4949 * Try to read more bytes to check for the old magic number, which
4953 TRACEME(("trying for old magic number"));
4955 old_len = sizeof(old_magicstr) - 1;
4956 READ(current + 1, (SSize_t)(old_len - len));
4958 if (memNE(buf, old_magicstr, old_len))
4959 CROAK(("File is not a perl storable"));
4960 current = buf + old_len;
4962 use_network_order = *current;
4964 GETMARK(use_network_order);
4967 * Starting with 0.6, the "use_network_order" byte flag is also used to
4968 * indicate the version number of the binary, and therefore governs the
4969 * setting of sv_retrieve_vtbl. See magic_write().
4972 version_major = use_network_order >> 1;
4973 cxt->retrieve_vtbl = version_major ? sv_retrieve : sv_old_retrieve;
4975 TRACEME(("magic_check: netorder = 0x%x", use_network_order));
4979 * Starting with 0.7 (binary major 2), a full byte is dedicated to the
4980 * minor version of the protocol. See magic_write().
4983 if (version_major > 1)
4984 GETMARK(version_minor);
4986 cxt->ver_major = version_major;
4987 cxt->ver_minor = version_minor;
4989 TRACEME(("binary image version is %d.%d", version_major, version_minor));
4992 * Inter-operability sanity check: we can't retrieve something stored
4993 * using a format more recent than ours, because we have no way to
4994 * know what has changed, and letting retrieval go would mean a probable
4995 * failure reporting a "corrupted" storable file.
4999 version_major > STORABLE_BIN_MAJOR ||
5000 (version_major == STORABLE_BIN_MAJOR &&
5001 version_minor > STORABLE_BIN_MINOR)
5004 TRACEME(("but I am version is %d.%d", STORABLE_BIN_MAJOR,
5005 STORABLE_BIN_MINOR));
5007 if (version_major == STORABLE_BIN_MAJOR) {
5008 TRACEME(("cxt->accept_future_minor is %d",
5009 cxt->accept_future_minor));
5010 if (cxt->accept_future_minor < 0)
5011 cxt->accept_future_minor
5012 = (SvTRUE(perl_get_sv("Storable::accept_future_minor",
5015 if (cxt->accept_future_minor == 1)
5016 croak_now = 0; /* Don't croak yet. */
5019 CROAK(("Storable binary image v%d.%d more recent than I am (v%d.%d)",
5020 version_major, version_minor,
5021 STORABLE_BIN_MAJOR, STORABLE_BIN_MINOR));
5026 * If they stored using network order, there's no byte ordering
5027 * information to check.
5030 if ((cxt->netorder = (use_network_order & 0x1))) /* Extra () for -Wall */
5031 return &PL_sv_undef; /* No byte ordering info */
5033 /* In C truth is 1, falsehood is 0. Very convienient. */
5034 use_NV_size = version_major >= 2 && version_minor >= 2;
5037 length = c + 3 + use_NV_size;
5038 READ(buf, length); /* Not null-terminated */
5040 TRACEME(("byte order '%.*s' %d", c, buf, c));
5042 if ((c != (sizeof (byteorderstr) - 1)) || memNE(buf, byteorderstr, c))
5043 CROAK(("Byte order is not compatible"));
5048 if ((int) *current++ != sizeof(int))
5049 CROAK(("Integer size is not compatible"));
5052 if ((int) *current++ != sizeof(long))
5053 CROAK(("Long integer size is not compatible"));
5055 /* sizeof(char *) */
5056 if ((int) *current != sizeof(char *))
5057 CROAK(("Pointer integer size is not compatible"));
5061 if ((int) *++current != sizeof(NV))
5062 CROAK(("Double size is not compatible"));
5065 return &PL_sv_undef; /* OK */
5071 * Recursively retrieve objects from the specified file and return their
5072 * root SV (which may be an AV or an HV for what we care).
5073 * Returns null if there is a problem.
5075 static SV *retrieve(stcxt_t *cxt, char *cname)
5081 TRACEME(("retrieve"));
5084 * Grab address tag which identifies the object if we are retrieving
5085 * an older format. Since the new binary format counts objects and no
5086 * longer explicitely tags them, we must keep track of the correspondance
5089 * The following section will disappear one day when the old format is
5090 * no longer supported, hence the final "goto" in the "if" block.
5093 if (cxt->hseen) { /* Retrieving old binary */
5095 if (cxt->netorder) {
5097 READ(&nettag, sizeof(I32)); /* Ordered sequence of I32 */
5098 tag = (stag_t) nettag;
5100 READ(&tag, sizeof(stag_t)); /* Original address of the SV */
5103 if (type == SX_OBJECT) {
5105 svh = hv_fetch(cxt->hseen, (char *) &tag, sizeof(tag), FALSE);
5107 CROAK(("Old tag 0x%"UVxf" should have been mapped already",
5109 tagn = SvIV(*svh); /* Mapped tag number computed earlier below */
5112 * The following code is common with the SX_OBJECT case below.
5115 svh = av_fetch(cxt->aseen, tagn, FALSE);
5117 CROAK(("Object #%"IVdf" should have been retrieved already",
5120 TRACEME(("has retrieved #%d at 0x%"UVxf, tagn, PTR2UV(sv)));
5121 SvREFCNT_inc(sv); /* One more reference to this same sv */
5122 return sv; /* The SV pointer where object was retrieved */
5126 * Map new object, but don't increase tagnum. This will be done
5127 * by each of the retrieve_* functions when they call SEEN().
5129 * The mapping associates the "tag" initially present with a unique
5130 * tag number. See test for SX_OBJECT above to see how this is perused.
5133 if (!hv_store(cxt->hseen, (char *) &tag, sizeof(tag),
5134 newSViv(cxt->tagnum), 0))
5141 * Regular post-0.6 binary format.
5146 TRACEME(("retrieve type = %d", type));
5149 * Are we dealing with an object we should have already retrieved?
5152 if (type == SX_OBJECT) {
5156 svh = av_fetch(cxt->aseen, tag, FALSE);
5158 CROAK(("Object #%"IVdf" should have been retrieved already",
5161 TRACEME(("had retrieved #%d at 0x%"UVxf, tag, PTR2UV(sv)));
5162 SvREFCNT_inc(sv); /* One more reference to this same sv */
5163 return sv; /* The SV pointer where object was retrieved */
5164 } else if (type >= SX_ERROR && cxt->ver_minor > STORABLE_BIN_MINOR) {
5165 if (cxt->accept_future_minor < 0)
5166 cxt->accept_future_minor
5167 = (SvTRUE(perl_get_sv("Storable::accept_future_minor",
5170 if (cxt->accept_future_minor == 1) {
5171 CROAK(("Storable binary image v%d.%d contains data of type %d. "
5172 "This Storable is v%d.%d and can only handle data types up to %d",
5173 cxt->ver_major, cxt->ver_minor, type,
5174 STORABLE_BIN_MAJOR, STORABLE_BIN_MINOR, SX_ERROR - 1));
5178 first_time: /* Will disappear when support for old format is dropped */
5181 * Okay, first time through for this one.
5184 sv = RETRIEVE(cxt, type)(cxt, cname);
5186 return (SV *) 0; /* Failed */
5189 * Old binary formats (pre-0.7).
5191 * Final notifications, ended by SX_STORED may now follow.
5192 * Currently, the only pertinent notification to apply on the
5193 * freshly retrieved object is either:
5194 * SX_CLASS <char-len> <classname> for short classnames.
5195 * SX_LG_CLASS <int-len> <classname> for larger one (rare!).
5196 * Class name is then read into the key buffer pool used by
5197 * hash table key retrieval.
5200 if (cxt->ver_major < 2) {
5201 while ((type = GETCHAR()) != SX_STORED) {
5205 GETMARK(len); /* Length coded on a single char */
5207 case SX_LG_CLASS: /* Length coded on a regular integer */
5212 return (SV *) 0; /* Failed */
5214 KBUFCHK((STRLEN)len); /* Grow buffer as necessary */
5217 kbuf[len] = '\0'; /* Mark string end */
5222 TRACEME(("ok (retrieved 0x%"UVxf", refcnt=%d, %s)", PTR2UV(sv),
5223 SvREFCNT(sv) - 1, sv_reftype(sv, FALSE)));
5231 * Retrieve data held in file and return the root object.
5232 * Common routine for pretrieve and mretrieve.
5234 static SV *do_retrieve(
5241 int is_tainted; /* Is input source tainted? */
5242 int pre_06_fmt = 0; /* True with pre Storable 0.6 formats */
5244 TRACEME(("do_retrieve (optype = 0x%x)", optype));
5246 optype |= ST_RETRIEVE;
5249 * Sanity assertions for retrieve dispatch tables.
5252 ASSERT(sizeof(sv_old_retrieve) == sizeof(sv_retrieve),
5253 ("old and new retrieve dispatch table have same size"));
5254 ASSERT(sv_old_retrieve[SX_ERROR] == retrieve_other,
5255 ("SX_ERROR entry correctly initialized in old dispatch table"));
5256 ASSERT(sv_retrieve[SX_ERROR] == retrieve_other,
5257 ("SX_ERROR entry correctly initialized in new dispatch table"));
5260 * Workaround for CROAK leak: if they enter with a "dirty" context,
5261 * free up memory for them now.
5268 * Now that STORABLE_xxx hooks exist, it is possible that they try to
5269 * re-enter retrieve() via the hooks.
5273 cxt = allocate_context(cxt);
5277 ASSERT(cxt->entry == 1, ("starting new recursion"));
5278 ASSERT(!cxt->s_dirty, ("clean context"));
5283 * Data is loaded into the memory buffer when f is NULL, unless `in' is
5284 * also NULL, in which case we're expecting the data to already lie
5285 * in the buffer (dclone case).
5288 KBUFINIT(); /* Allocate hash key reading pool once */
5291 MBUF_SAVE_AND_LOAD(in);
5294 * Magic number verifications.
5296 * This needs to be done before calling init_retrieve_context()
5297 * since the format indication in the file are necessary to conduct
5298 * some of the initializations.
5301 cxt->fio = f; /* Where I/O are performed */
5303 if (!magic_check(cxt))
5304 CROAK(("Magic number checking on storable %s failed",
5305 cxt->fio ? "file" : "string"));
5307 TRACEME(("data stored in %s format",
5308 cxt->netorder ? "net order" : "native"));
5311 * Check whether input source is tainted, so that we don't wrongly
5312 * taint perfectly good values...
5314 * We assume file input is always tainted. If both `f' and `in' are
5315 * NULL, then we come from dclone, and tainted is already filled in
5316 * the context. That's a kludge, but the whole dclone() thing is
5317 * already quite a kludge anyway! -- RAM, 15/09/2000.
5320 is_tainted = f ? 1 : (in ? SvTAINTED(in) : cxt->s_tainted);
5321 TRACEME(("input source is %s", is_tainted ? "tainted" : "trusted"));
5322 init_retrieve_context(cxt, optype, is_tainted);
5324 ASSERT(is_retrieving(), ("within retrieve operation"));
5326 sv = retrieve(cxt, 0); /* Recursively retrieve object, get root SV */
5335 pre_06_fmt = cxt->hseen != NULL; /* Before we clean context */
5338 * The "root" context is never freed.
5341 clean_retrieve_context(cxt);
5342 if (cxt->prev) /* This context was stacked */
5343 free_context(cxt); /* It was not the "root" context */
5346 * Prepare returned value.
5350 TRACEME(("retrieve ERROR"));
5351 return &PL_sv_undef; /* Something went wrong, return undef */
5354 TRACEME(("retrieve got %s(0x%"UVxf")",
5355 sv_reftype(sv, FALSE), PTR2UV(sv)));
5358 * Backward compatibility with Storable-0.5@9 (which we know we
5359 * are retrieving if hseen is non-null): don't create an extra RV
5360 * for objects since we special-cased it at store time.
5362 * Build a reference to the SV returned by pretrieve even if it is
5363 * already one and not a scalar, for consistency reasons.
5366 if (pre_06_fmt) { /* Was not handling overloading by then */
5368 TRACEME(("fixing for old formats -- pre 0.6"));
5369 if (sv_type(sv) == svis_REF && (rv = SvRV(sv)) && SvOBJECT(rv)) {
5370 TRACEME(("ended do_retrieve() with an object -- pre 0.6"));
5376 * If reference is overloaded, restore behaviour.
5378 * NB: minor glitch here: normally, overloaded refs are stored specially
5379 * so that we can croak when behaviour cannot be re-installed, and also
5380 * avoid testing for overloading magic at each reference retrieval.
5382 * Unfortunately, the root reference is implicitely stored, so we must
5383 * check for possible overloading now. Furthermore, if we don't restore
5384 * overloading, we cannot croak as if the original ref was, because we
5385 * have no way to determine whether it was an overloaded ref or not in
5388 * It's a pity that overloading magic is attached to the rv, and not to
5389 * the underlying sv as blessing is.
5393 HV *stash = (HV *) SvSTASH(sv);
5394 SV *rv = newRV_noinc(sv);
5395 if (stash && Gv_AMG(stash)) {
5397 TRACEME(("restored overloading on root reference"));
5399 TRACEME(("ended do_retrieve() with an object"));
5403 TRACEME(("regular do_retrieve() end"));
5405 return newRV_noinc(sv);
5411 * Retrieve data held in file and return the root object, undef on error.
5413 SV *pretrieve(PerlIO *f)
5415 TRACEME(("pretrieve"));
5416 return do_retrieve(f, Nullsv, 0);
5422 * Retrieve data held in scalar and return the root object, undef on error.
5424 SV *mretrieve(SV *sv)
5426 TRACEME(("mretrieve"));
5427 return do_retrieve((PerlIO*) 0, sv, 0);
5437 * Deep clone: returns a fresh copy of the original referenced SV tree.
5439 * This is achieved by storing the object in memory and restoring from
5440 * there. Not that efficient, but it should be faster than doing it from
5447 stcxt_t *real_context;
5450 TRACEME(("dclone"));
5453 * Workaround for CROAK leak: if they enter with a "dirty" context,
5454 * free up memory for them now.
5461 * do_store() optimizes for dclone by not freeing its context, should
5462 * we need to allocate one because we're deep cloning from a hook.
5465 if (!do_store((PerlIO*) 0, sv, ST_CLONE, FALSE, (SV**) 0))
5466 return &PL_sv_undef; /* Error during store */
5469 * Because of the above optimization, we have to refresh the context,
5470 * since a new one could have been allocated and stacked by do_store().
5473 { dSTCXT; real_context = cxt; } /* Sub-block needed for macro */
5474 cxt = real_context; /* And we need this temporary... */
5477 * Now, `cxt' may refer to a new context.
5480 ASSERT(!cxt->s_dirty, ("clean context"));
5481 ASSERT(!cxt->entry, ("entry will not cause new context allocation"));
5484 TRACEME(("dclone stored %d bytes", size));
5488 * Since we're passing do_retrieve() both a NULL file and sv, we need
5489 * to pre-compute the taintedness of the input by setting cxt->tainted
5490 * to whatever state our own input string was. -- RAM, 15/09/2000
5492 * do_retrieve() will free non-root context.
5495 cxt->s_tainted = SvTAINTED(sv);
5496 out = do_retrieve((PerlIO*) 0, Nullsv, ST_CLONE);
5498 TRACEME(("dclone returns 0x%"UVxf, PTR2UV(out)));
5508 * The Perl IO GV object distinguishes between input and output for sockets
5509 * but not for plain files. To allow Storable to transparently work on
5510 * plain files and sockets transparently, we have to ask xsubpp to fetch the
5511 * right object for us. Hence the OutputStream and InputStream declarations.
5513 * Before perl 5.004_05, those entries in the standard typemap are not
5514 * defined in perl include files, so we do that here.
5517 #ifndef OutputStream
5518 #define OutputStream PerlIO *
5519 #define InputStream PerlIO *
5520 #endif /* !OutputStream */
5522 MODULE = Storable PACKAGE = Storable::Cxt
5528 stcxt_t *cxt = (stcxt_t *)SvPVX(SvRV(self));
5532 if (!cxt->membuf_ro && mbase)
5534 if (cxt->membuf_ro && (cxt->msaved).arena)
5535 Safefree((cxt->msaved).arena);
5538 MODULE = Storable PACKAGE = Storable
5545 /* Only disable the used only once warning if we are in debugging mode. */
5546 gv_fetchpv("Storable::DEBUGME", GV_ADDMULTI, SVt_PV);
5580 last_op_in_netorder()