1 /* -*- c-basic-offset: 4 -*-
3 * Fast store and retrieve mechanism.
5 * Copyright (c) 1995-2000, Raphael Manfredi
6 * Copyright (c) 2016, 2017 cPanel Inc
7 * Copyright (c) 2017 Reini Urban
9 * You may redistribute only under the same terms as Perl 5, as specified
10 * in the README file that comes with the distribution.
14 #define PERL_NO_GET_CONTEXT /* we want efficiency */
19 #ifndef PERL_VERSION_LT
20 # if !defined(PERL_VERSION) || !defined(PERL_REVISION) || ( PERL_REVISION == 5 && ( PERL_VERSION < 10 || (PERL_VERSION == 10 && PERL_SUBVERSION < 1) ) )
21 # define NEED_PL_parser
22 # define NEED_sv_2pv_flags
23 # define NEED_load_module
24 # define NEED_vload_module
25 # define NEED_newCONSTSUB
26 # define NEED_newSVpvn_flags
27 # define NEED_newRV_noinc
29 #include "ppport.h" /* handle old perls */
33 #define DEBUGME /* Debug mode, turns assertions on as well */
34 #define DASSERT /* Assertion mode */
38 * Earlier versions of perl might be used, we can't assume they have the latest!
41 /* perl <= 5.8.2 needs this */
43 # define SvIsCOW(sv) 0
47 # define HvRITER_set(hv,r) (HvRITER(hv) = r)
50 # define HvEITER_set(hv,r) (HvEITER(hv) = r)
54 # define HvRITER_get HvRITER
57 # define HvEITER_get HvEITER
60 #ifndef HvPLACEHOLDERS_get
61 # define HvPLACEHOLDERS_get HvPLACEHOLDERS
65 # define HvTOTALKEYS(hv) HvKEYS(hv)
69 # define HvUSEDKEYS(hv) HvKEYS(hv)
73 # define SvTRULYREADONLY(sv) SvREADONLY(sv)
75 # define SvTRULYREADONLY(sv) (SvREADONLY(sv) && !SvIsCOW(sv))
79 # define strEQc(s,c) memEQ(s, ("" c ""), sizeof(c))
82 #if defined(HAS_FLOCK) || defined(FCNTL_CAN_LOCK) && defined(HAS_LOCKF)
83 #define CAN_FLOCK &PL_sv_yes
85 #define CAN_FLOCK &PL_sv_no
95 * TRACEME() will only output things when the $Storable::DEBUGME is true,
96 * using the value traceme cached in the context.
99 * TRACEMED() directly looks at the variable, for use before traceme has been
106 { PerlIO_stdoutf x; PerlIO_stdoutf("\n"); } \
109 #define TRACEMED(x) \
111 if (SvTRUE(get_sv("Storable::DEBUGME", GV_ADD))) \
112 { PerlIO_stdoutf x; PerlIO_stdoutf("\n"); } \
115 #define INIT_TRACEME \
117 cxt->traceme = SvTRUE(get_sv("Storable::DEBUGME", GV_ADD)); \
127 #define ASSERT(x,y) \
130 PerlIO_stdoutf("ASSERT FAILED (\"%s\", line %d): ", \
131 __FILE__, (int)__LINE__); \
132 PerlIO_stdoutf y; PerlIO_stdoutf("\n"); \
143 #define C(x) ((char) (x)) /* For markers with dynamic retrieval handling */
145 #define SX_OBJECT C(0) /* Already stored object */
146 #define SX_LSCALAR C(1) /* Scalar (large binary) follows (length, data) */
147 #define SX_ARRAY C(2) /* Array forthcoming (size, item list) */
148 #define SX_HASH C(3) /* Hash forthcoming (size, key/value pair list) */
149 #define SX_REF C(4) /* Reference to object forthcoming */
150 #define SX_UNDEF C(5) /* Undefined scalar */
151 #define SX_INTEGER C(6) /* Integer forthcoming */
152 #define SX_DOUBLE C(7) /* Double forthcoming */
153 #define SX_BYTE C(8) /* (signed) byte forthcoming */
154 #define SX_NETINT C(9) /* Integer in network order forthcoming */
155 #define SX_SCALAR C(10) /* Scalar (binary, small) follows (length, data) */
156 #define SX_TIED_ARRAY C(11) /* Tied array forthcoming */
157 #define SX_TIED_HASH C(12) /* Tied hash forthcoming */
158 #define SX_TIED_SCALAR C(13) /* Tied scalar forthcoming */
159 #define SX_SV_UNDEF C(14) /* Perl's immortal PL_sv_undef */
160 #define SX_SV_YES C(15) /* Perl's immortal PL_sv_yes */
161 #define SX_SV_NO C(16) /* Perl's immortal PL_sv_no */
162 #define SX_BLESS C(17) /* Object is blessed */
163 #define SX_IX_BLESS C(18) /* Object is blessed, classname given by index */
164 #define SX_HOOK C(19) /* Stored via hook, user-defined */
165 #define SX_OVERLOAD C(20) /* Overloaded reference */
166 #define SX_TIED_KEY C(21) /* Tied magic key forthcoming */
167 #define SX_TIED_IDX C(22) /* Tied magic index forthcoming */
168 #define SX_UTF8STR C(23) /* UTF-8 string forthcoming (small) */
169 #define SX_LUTF8STR C(24) /* UTF-8 string forthcoming (large) */
170 #define SX_FLAG_HASH C(25) /* Hash with flags forthcoming (size, flags, key/flags/value triplet list) */
171 #define SX_CODE C(26) /* Code references as perl source code */
172 #define SX_WEAKREF C(27) /* Weak reference to object forthcoming */
173 #define SX_WEAKOVERLOAD C(28) /* Overloaded weak reference */
174 #define SX_VSTRING C(29) /* vstring forthcoming (small) */
175 #define SX_LVSTRING C(30) /* vstring forthcoming (large) */
176 #define SX_SVUNDEF_ELEM C(31) /* array element set to &PL_sv_undef */
177 #define SX_REGEXP C(32) /* Regexp */
178 #define SX_LOBJECT C(33) /* Large object: string, array or hash (size >2G) */
179 #define SX_LAST C(34) /* invalid. marker only */
182 * Those are only used to retrieve "old" pre-0.6 binary images.
184 #define SX_ITEM 'i' /* An array item introducer */
185 #define SX_IT_UNDEF 'I' /* Undefined array item */
186 #define SX_KEY 'k' /* A hash key introducer */
187 #define SX_VALUE 'v' /* A hash value introducer */
188 #define SX_VL_UNDEF 'V' /* Undefined hash value */
191 * Those are only used to retrieve "old" pre-0.7 binary images
194 #define SX_CLASS 'b' /* Object is blessed, class name length <255 */
195 #define SX_LG_CLASS 'B' /* Object is blessed, class name length >255 */
196 #define SX_STORED 'X' /* End of object */
199 * Limits between short/long length representation.
202 #define LG_SCALAR 255 /* Large scalar length limit */
203 #define LG_BLESS 127 /* Large classname bless limit */
209 #define ST_STORE 0x1 /* Store operation */
210 #define ST_RETRIEVE 0x2 /* Retrieval operation */
211 #define ST_CLONE 0x4 /* Deep cloning operation */
214 * The following structure is used for hash table key retrieval. Since, when
215 * retrieving objects, we'll be facing blessed hash references, it's best
216 * to pre-allocate that buffer once and resize it as the need arises, never
217 * freeing it (keys will be saved away someplace else anyway, so even large
218 * keys are not enough a motivation to reclaim that space).
220 * This structure is also used for memory store/retrieve operations which
221 * happen in a fixed place before being malloc'ed elsewhere if persistence
222 * is required. Hence the aptr pointer.
225 char *arena; /* Will hold hash key strings, resized as needed */
226 STRLEN asiz; /* Size of aforementioned buffer */
227 char *aptr; /* Arena pointer, for in-place read/write ops */
228 char *aend; /* First invalid address */
233 * A hash table records the objects which have already been stored.
234 * Those are referred to as SX_OBJECT in the file, and their "tag" (i.e.
235 * an arbitrary sequence number) is used to identify them.
238 * An array table records the objects which have already been retrieved,
239 * as seen by the tag determined by counting the objects themselves. The
240 * reference to that retrieved object is kept in the table, and is returned
241 * when an SX_OBJECT is found bearing that same tag.
243 * The same processing is used to record "classname" for blessed objects:
244 * indexing by a hash at store time, and via an array at retrieve time.
247 typedef unsigned long stag_t; /* Used by pre-0.6 binary format */
250 * Make the tag type 64-bit on 64-bit platforms.
252 * If the tag number is low enough it's stored as a 32-bit value, but
253 * with very large arrays and hashes it's possible to go over 2**32
257 typedef STRLEN ntag_t;
259 /* used for where_is_undef - marks an unset value */
260 #define UNSET_NTAG_T (~(ntag_t)0)
263 * The following "thread-safe" related defines were contributed by
264 * Murray Nesbitt <murray@activestate.com> and integrated by RAM, who
265 * only renamed things a little bit to ensure consistency with surrounding
266 * code. -- RAM, 14/09/1999
268 * The original patch suffered from the fact that the stcxt_t structure
269 * was global. Murray tried to minimize the impact on the code as much as
272 * Starting with 0.7, Storable can be re-entrant, via the STORABLE_xxx hooks
273 * on objects. Therefore, the notion of context needs to be generalized,
277 #define MY_VERSION "Storable(" XS_VERSION ")"
281 * Conditional UTF8 support.
284 #define STORE_UTF8STR(pv, len) STORE_PV_LEN(pv, len, SX_UTF8STR, SX_LUTF8STR)
285 #define HAS_UTF8_SCALARS
287 #define HAS_UTF8_HASHES
290 /* 5.6 perl has utf8 scalars but not hashes */
293 #define UTF8_CROAK() CROAK(("Cannot retrieve UTF8 data in non-UTF8 perl"))
296 #define WEAKREF_CROAK() CROAK(("Cannot retrieve weak references in this perl"))
299 #define VSTRING_CROAK() CROAK(("Cannot retrieve vstring in this perl"))
302 #ifdef HvPLACEHOLDERS
303 #define HAS_RESTRICTED_HASHES
305 #define HVhek_PLACEHOLD 0x200
306 #define RESTRICTED_HASH_CROAK() CROAK(("Cannot retrieve restricted hash"))
310 #define HAS_HASH_KEY_FLAGS
314 #define USE_PTR_TABLE
317 /* do we need/want to clear padding on NVs? */
318 #if defined(LONG_DOUBLEKIND) && defined(USE_LONG_DOUBLE)
319 # if LONG_DOUBLEKIND == LONG_DOUBLE_IS_X86_80_BIT_LITTLE_ENDIAN || \
320 LONG_DOUBLEKIND == LONG_DOUBLE_IS_X86_80_BIT_BIG_ENDIAN
321 # define NV_PADDING (NVSIZE - 10)
323 # define NV_PADDING 0
326 /* This is kind of a guess - it means we'll get an unneeded clear on 128-bit NV
327 but an upgraded perl will fix that
332 # define NV_PADDING 0
337 U8 bytes[sizeof(NV)];
340 /* Needed for 32bit with lengths > 2G - 4G, and 64bit */
346 * Fields s_tainted and s_dirty are prefixed with s_ because Perl's include
347 * files remap tainted and dirty when threading is enabled. That's bad for
348 * perl to remap such common words. -- RAM, 29/09/00
352 typedef struct stcxt {
353 int entry; /* flags recursion */
354 int optype; /* type of traversal operation */
355 /* which objects have been seen, store time.
356 tags are numbers, which are cast to (SV *) and stored directly */
358 /* use pseen if we have ptr_tables. We have to store tag+1, because
359 tag numbers start at 0, and we can't store (SV *) 0 in a ptr_table
360 without it being confused for a fetch lookup failure. */
361 struct ptr_tbl *pseen;
362 /* Still need hseen for the 0.6 file format code. */
365 AV *hook_seen; /* which SVs were returned by STORABLE_freeze() */
366 AV *aseen; /* which objects have been seen, retrieve time */
367 ntag_t where_is_undef; /* index in aseen of PL_sv_undef */
368 HV *hclass; /* which classnames have been seen, store time */
369 AV *aclass; /* which classnames have been seen, retrieve time */
370 HV *hook; /* cache for hook methods per class name */
371 IV tagnum; /* incremented at store time for each seen object */
372 IV classnum; /* incremented at store time for each seen classname */
373 int netorder; /* true if network order used */
374 int s_tainted; /* true if input source is tainted, at retrieve time */
375 int forgive_me; /* whether to be forgiving... */
376 int deparse; /* whether to deparse code refs */
377 SV *eval; /* whether to eval source code */
378 int canonical; /* whether to store hashes sorted by key */
379 #ifndef HAS_RESTRICTED_HASHES
380 int derestrict; /* whether to downgrade restricted hashes */
383 int use_bytes; /* whether to bytes-ify utf8 */
385 int accept_future_minor; /* croak immediately on future minor versions? */
386 int s_dirty; /* context is dirty due to CROAK() -- can be cleaned */
387 int membuf_ro; /* true means membuf is read-only and msaved is rw */
388 struct extendable keybuf; /* for hash key retrieval */
389 struct extendable membuf; /* for memory store/retrieve operations */
390 struct extendable msaved; /* where potentially valid mbuf is saved */
391 PerlIO *fio; /* where I/O are performed, NULL for memory */
392 int ver_major; /* major of version for retrieved object */
393 int ver_minor; /* minor of version for retrieved object */
394 SV *(**retrieve_vtbl)(pTHX_ struct stcxt *, const char *); /* retrieve dispatch table */
395 SV *prev; /* contexts chained backwards in real recursion */
396 SV *my_sv; /* the blessed scalar who's SvPVX() I am */
400 A hashref of hashrefs or arrayref of arrayrefs is actually a
401 chain of four SVs, eg for an array ref containing an array ref:
403 RV -> AV (element) -> RV -> AV
405 To make this depth appear natural from a perl level we only
406 want to count this as two levels, so store_ref() stores it's RV
407 into recur_sv and store_array()/store_hash() will only count
408 that level if the AV/HV *isn't* recur_sv.
410 We can't just have store_hash()/store_array() not count that
411 level, since it's possible for XS code to store an AV or HV
412 directly as an element (though perl code trying to access such
413 an object will generally croak.)
415 SV *recur_sv; /* check only one recursive SV */
416 int in_retrieve_overloaded; /* performance hack for retrieving overloaded objects */
417 int flags; /* controls whether to bless or tie objects */
418 IV recur_depth; /* avoid stack overflows RT #97526 */
419 IV max_recur_depth; /* limit for recur_depth */
420 IV max_recur_depth_hash; /* limit for recur_depth for hashes */
422 int traceme; /* TRACEME() produces output */
426 #define RECURSION_TOO_DEEP() \
427 (cxt->max_recur_depth != -1 && ++cxt->recur_depth > cxt->max_recur_depth)
429 /* There's cases where we need to check whether the hash recursion
430 limit has been reached without bumping the recursion levels, so the
431 hash check doesn't bump the depth.
433 #define RECURSION_TOO_DEEP_HASH() \
434 (cxt->max_recur_depth_hash != -1 && cxt->recur_depth > cxt->max_recur_depth_hash)
435 #define MAX_DEPTH_ERROR "Max. recursion depth with nested structures exceeded"
437 static int storable_free(pTHX_ SV *sv, MAGIC* mg);
439 static MGVTBL vtbl_storable = {
456 /* From Digest::MD5. */
458 # define sv_magicext(sv, obj, type, vtbl, name, namlen) \
459 THX_sv_magicext(aTHX_ sv, obj, type, vtbl, name, namlen)
460 static MAGIC *THX_sv_magicext(pTHX_
461 SV *sv, SV *obj, int type,
462 MGVTBL const *vtbl, char const *name, I32 namlen)
466 /* exceeded intended usage of this reserve implementation */
469 mg->mg_virtual = (MGVTBL*)vtbl;
471 mg->mg_ptr = (char *)name;
473 (void) SvUPGRADE(sv, SVt_PVMG);
474 mg->mg_moremagic = SvMAGIC(sv);
482 #define NEW_STORABLE_CXT_OBJ(cxt) \
484 SV *self = newSV(sizeof(stcxt_t) - 1); \
485 SV *my_sv = newRV_noinc(self); \
486 sv_magicext(self, NULL, PERL_MAGIC_ext, &vtbl_storable, NULL, 0); \
487 cxt = (stcxt_t *)SvPVX(self); \
488 Zero(cxt, 1, stcxt_t); \
489 cxt->my_sv = my_sv; \
492 #if defined(MULTIPLICITY) || defined(PERL_OBJECT) || defined(PERL_CAPI)
495 SV *perinterp_sv = *hv_fetch(PL_modglobal, \
496 MY_VERSION, sizeof(MY_VERSION)-1, TRUE)
498 #define dSTCXT_PTR(T,name) \
499 T name = ((perinterp_sv \
500 && SvIOK(perinterp_sv) && SvIVX(perinterp_sv) \
501 ? (T)SvPVX(SvRV(INT2PTR(SV*,SvIVX(perinterp_sv)))) : (T) 0))
504 dSTCXT_PTR(stcxt_t *, cxt)
508 NEW_STORABLE_CXT_OBJ(cxt); \
509 assert(perinterp_sv); \
510 sv_setiv(perinterp_sv, PTR2IV(cxt->my_sv))
512 #define SET_STCXT(x) \
515 sv_setiv(perinterp_sv, PTR2IV(x->my_sv)); \
518 #else /* !MULTIPLICITY && !PERL_OBJECT && !PERL_CAPI */
520 static stcxt_t *Context_ptr = NULL;
521 #define dSTCXT stcxt_t *cxt = Context_ptr
522 #define SET_STCXT(x) Context_ptr = x
525 NEW_STORABLE_CXT_OBJ(cxt); \
529 #endif /* MULTIPLICITY || PERL_OBJECT || PERL_CAPI */
533 * Croaking implies a memory leak, since we don't use setjmp/longjmp
534 * to catch the exit and free memory used during store or retrieve
535 * operations. This is not too difficult to fix, but I need to understand
536 * how Perl does it, and croaking is exceptional anyway, so I lack the
537 * motivation to do it.
539 * The current workaround is to mark the context as dirty when croaking,
540 * so that data structures can be freed whenever we renter Storable code
541 * (but only *then*: it's a workaround, not a fix).
543 * This is also imperfect, because we don't really know how far they trapped
544 * the croak(), and when we were recursing, we won't be able to clean anything
545 * but the topmost context stacked.
548 #define CROAK(x) STMT_START { cxt->s_dirty = 1; croak x; } STMT_END
551 * End of "thread-safe" related definitions.
557 * Keep only the low 32 bits of a pointer (used for tags, which are not
562 #define LOW_32BITS(x) ((I32) (x))
564 #define LOW_32BITS(x) ((I32) ((STRLEN) (x) & 0xffffffffUL))
570 * Convert a pointer into an ntag_t.
573 #define PTR2TAG(x) ((ntag_t)(x))
575 #define TAG2PTR(x, type) ((y)(x))
580 * Hack for Crays, where sizeof(I32) == 8, and which are big-endians.
581 * Used in the WLEN and RLEN macros.
585 #define oI(x) ((I32 *) ((char *) (x) + 4))
586 #define oS(x) ((x) - 4)
588 #define oC(x) (x = 0)
598 * key buffer handling
600 #define kbuf (cxt->keybuf).arena
601 #define ksiz (cxt->keybuf).asiz
605 TRACEME(("** allocating kbuf of 128 bytes")); \
606 New(10003, kbuf, 128, char); \
614 CROAK(("Too large size > I32_MAX")); \
615 TRACEME(("** extending kbuf to %d bytes (had %d)", \
616 (int)(x+1), (int)ksiz)); \
617 Renew(kbuf, x+1, char); \
623 * memory buffer handling
625 #define mbase (cxt->membuf).arena
626 #define msiz (cxt->membuf).asiz
627 #define mptr (cxt->membuf).aptr
628 #define mend (cxt->membuf).aend
630 #define MGROW (1 << 13)
631 #define MMASK (MGROW - 1)
633 #define round_mgrow(x) \
634 ((STRLEN) (((STRLEN) (x) + MMASK) & ~MMASK))
635 #define trunc_int(x) \
636 ((STRLEN) ((STRLEN) (x) & ~(sizeof(int)-1)))
637 #define int_aligned(x) \
638 ((STRLEN)(x) == trunc_int(x))
640 #define MBUF_INIT(x) \
643 TRACEME(("** allocating mbase of %d bytes", MGROW)); \
644 New(10003, mbase, (int)MGROW, char); \
645 msiz = (STRLEN)MGROW; \
651 mend = mbase + msiz; \
654 #define MBUF_TRUNC(x) mptr = mbase + x
655 #define MBUF_SIZE() (mptr - mbase)
661 * Those macros are used in do_retrieve() to save the current memory
662 * buffer into cxt->msaved, before MBUF_LOAD() can be used to retrieve
663 * data from a string.
665 #define MBUF_SAVE_AND_LOAD(in) \
667 ASSERT(!cxt->membuf_ro, ("mbase not already saved")); \
668 cxt->membuf_ro = 1; \
669 TRACEME(("saving mbuf")); \
670 StructCopy(&cxt->membuf, &cxt->msaved, struct extendable); \
674 #define MBUF_RESTORE() \
676 ASSERT(cxt->membuf_ro, ("mbase is read-only")); \
677 cxt->membuf_ro = 0; \
678 TRACEME(("restoring mbuf")); \
679 StructCopy(&cxt->msaved, &cxt->membuf, struct extendable); \
683 * Use SvPOKp(), because SvPOK() fails on tainted scalars.
684 * See store_scalar() for other usage of this workaround.
686 #define MBUF_LOAD(v) \
688 ASSERT(cxt->membuf_ro, ("mbase is read-only")); \
690 CROAK(("Not a scalar string")); \
691 mptr = mbase = SvPV(v, msiz); \
692 mend = mbase + msiz; \
695 #define MBUF_XTEND(x) \
697 STRLEN nsz = (STRLEN) round_mgrow((x)+msiz); \
698 STRLEN offset = mptr - mbase; \
699 ASSERT(!cxt->membuf_ro, ("mbase is not read-only")); \
700 TRACEME(("** extending mbase from %lu to %lu bytes (wants %lu new)", \
701 (unsigned long)msiz, (unsigned long)nsz, (unsigned long)(x))); \
702 Renew(mbase, nsz, char); \
704 mptr = mbase + offset; \
705 mend = mbase + nsz; \
708 #define MBUF_CHK(x) \
710 if ((mptr + (x)) > mend) \
714 #define MBUF_GETC(x) \
717 x = (int) (unsigned char) *mptr++; \
723 #define MBUF_GETINT(x) \
726 if ((mptr + 4) <= mend) { \
727 memcpy(oI(&x), mptr, 4); \
733 #define MBUF_GETINT(x) \
735 if ((mptr + sizeof(int)) <= mend) { \
736 if (int_aligned(mptr)) \
739 memcpy(&x, mptr, sizeof(int)); \
740 mptr += sizeof(int); \
746 #define MBUF_READ(x,s) \
748 if ((mptr + (s)) <= mend) { \
749 memcpy(x, mptr, s); \
755 #define MBUF_SAFEREAD(x,s,z) \
757 if ((mptr + (s)) <= mend) { \
758 memcpy(x, mptr, s); \
766 #define MBUF_SAFEPVREAD(x,s,z) \
768 if ((mptr + (s)) <= mend) { \
769 memcpy(x, mptr, s); \
777 #define MBUF_PUTC(c) \
780 *mptr++ = (char) c; \
783 *mptr++ = (char) c; \
788 #define MBUF_PUTINT(i) \
791 memcpy(mptr, oI(&i), 4); \
795 #define MBUF_PUTINT(i) \
797 MBUF_CHK(sizeof(int)); \
798 if (int_aligned(mptr)) \
801 memcpy(mptr, &i, sizeof(int)); \
802 mptr += sizeof(int); \
806 #define MBUF_PUTLONG(l) \
809 memcpy(mptr, &l, 8); \
812 #define MBUF_WRITE(x,s) \
815 memcpy(mptr, x, s); \
820 * Possible return values for sv_type().
824 #define svis_SCALAR 1
828 #define svis_TIED_ITEM 5
830 #define svis_REGEXP 7
837 #define SHF_TYPE_MASK 0x03
838 #define SHF_LARGE_CLASSLEN 0x04
839 #define SHF_LARGE_STRLEN 0x08
840 #define SHF_LARGE_LISTLEN 0x10
841 #define SHF_IDX_CLASSNAME 0x20
842 #define SHF_NEED_RECURSE 0x40
843 #define SHF_HAS_LIST 0x80
846 * Types for SX_HOOK (last 2 bits in flags).
852 #define SHT_EXTRA 3 /* Read extra byte for type */
855 * The following are held in the "extra byte"...
858 #define SHT_TSCALAR 4 /* 4 + 0 -- tied scalar */
859 #define SHT_TARRAY 5 /* 4 + 1 -- tied array */
860 #define SHT_THASH 6 /* 4 + 2 -- tied hash */
863 * per hash flags for flagged hashes
866 #define SHV_RESTRICTED 0x01
869 * per key flags for flagged hashes
872 #define SHV_K_UTF8 0x01
873 #define SHV_K_WASUTF8 0x02
874 #define SHV_K_LOCKED 0x04
875 #define SHV_K_ISSV 0x08
876 #define SHV_K_PLACEHOLDER 0x10
879 * flags to allow blessing and/or tieing data the data we load
881 #define FLAG_BLESS_OK 2
882 #define FLAG_TIE_OK 4
885 * Flags for SX_REGEXP.
888 #define SHR_U32_RE_LEN 0x01
891 * Before 0.6, the magic string was "perl-store" (binary version number 0).
893 * Since 0.6 introduced many binary incompatibilities, the magic string has
894 * been changed to "pst0" to allow an old image to be properly retrieved by
895 * a newer Storable, but ensure a newer image cannot be retrieved with an
898 * At 0.7, objects are given the ability to serialize themselves, and the
899 * set of markers is extended, backward compatibility is not jeopardized,
900 * so the binary version number could have remained unchanged. To correctly
901 * spot errors if a file making use of 0.7-specific extensions is given to
902 * 0.6 for retrieval, the binary version was moved to "2". And I'm introducing
903 * a "minor" version, to better track this kind of evolution from now on.
906 static const char old_magicstr[] = "perl-store"; /* Magic number before 0.6 */
907 static const char magicstr[] = "pst0"; /* Used as a magic number */
909 #define MAGICSTR_BYTES 'p','s','t','0'
910 #define OLDMAGICSTR_BYTES 'p','e','r','l','-','s','t','o','r','e'
912 /* 5.6.x introduced the ability to have IVs as long long.
913 However, Configure still defined BYTEORDER based on the size of a long.
914 Storable uses the BYTEORDER value as part of the header, but doesn't
915 explicitly store sizeof(IV) anywhere in the header. Hence on 5.6.x built
916 with IV as long long on a platform that uses Configure (ie most things
917 except VMS and Windows) headers are identical for the different IV sizes,
918 despite the files containing some fields based on sizeof(IV)
920 5.8 is consistent - the following redefinition kludge is only needed on
921 5.6.x, but the interwork is needed on 5.8 while data survives in files
926 #if defined (IVSIZE) && (IVSIZE == 8) && (LONGSIZE == 4)
927 #ifndef NO_56_INTERWORK_KLUDGE
928 #define USE_56_INTERWORK_KLUDGE
930 #if BYTEORDER == 0x1234
932 #define BYTEORDER 0x12345678
934 #if BYTEORDER == 0x4321
936 #define BYTEORDER 0x87654321
941 #if BYTEORDER == 0x1234
942 #define BYTEORDER_BYTES '1','2','3','4'
944 #if BYTEORDER == 0x12345678
945 #define BYTEORDER_BYTES '1','2','3','4','5','6','7','8'
946 #ifdef USE_56_INTERWORK_KLUDGE
947 #define BYTEORDER_BYTES_56 '1','2','3','4'
950 #if BYTEORDER == 0x87654321
951 #define BYTEORDER_BYTES '8','7','6','5','4','3','2','1'
952 #ifdef USE_56_INTERWORK_KLUDGE
953 #define BYTEORDER_BYTES_56 '4','3','2','1'
956 #if BYTEORDER == 0x4321
957 #define BYTEORDER_BYTES '4','3','2','1'
959 #error Unknown byteorder. Please append your byteorder to Storable.xs
966 # define INT32_MAX 2147483647
968 #if IVSIZE > 4 && !defined(INT64_MAX)
969 # define INT64_MAX 9223372036854775807LL
972 static const char byteorderstr[] = {BYTEORDER_BYTES, 0};
973 #ifdef USE_56_INTERWORK_KLUDGE
974 static const char byteorderstr_56[] = {BYTEORDER_BYTES_56, 0};
977 #define STORABLE_BIN_MAJOR 2 /* Binary major "version" */
978 #define STORABLE_BIN_MINOR 11 /* Binary minor "version" */
982 * Perl 5.6.0-5.8.0 can do weak references, but not vstring magic.
984 #define STORABLE_BIN_WRITE_MINOR 8
985 #elif PERL_VERSION_GE(5,19,0)
986 /* Perl 5.19 takes away the special meaning of PL_sv_undef in arrays. */
987 /* With 3.x we added LOBJECT */
988 #define STORABLE_BIN_WRITE_MINOR 11
990 #define STORABLE_BIN_WRITE_MINOR 9
993 #if PERL_VERSION_LT(5,8,1)
994 #define PL_sv_placeholder PL_sv_undef
998 * Useful store shortcuts...
1002 * Note that if you put more than one mark for storing a particular
1003 * type of thing, *and* in the retrieve_foo() function you mark both
1004 * the thingy's you get off with SEEN(), you *must* increase the
1005 * tagnum with cxt->tagnum++ along with this macro!
1008 #define PUTMARK(x) \
1012 else if (PerlIO_putc(cxt->fio, x) == EOF) \
1016 #define WRITE_I32(x) \
1018 ASSERT(sizeof(x) == sizeof(I32), ("writing an I32")); \
1021 else if (PerlIO_write(cxt->fio, oI(&x), \
1022 oS(sizeof(x))) != oS(sizeof(x))) \
1026 #define WRITE_U64(x) \
1028 ASSERT(sizeof(x) == sizeof(UV), ("writing an UV")); \
1031 else if (PerlIO_write(cxt->fio, oL(&x), \
1032 oS(sizeof(x))) != oS(sizeof(x))) \
1039 ASSERT(sizeof(x) == sizeof(int), ("WLEN writing an int")); \
1040 if (cxt->netorder) { \
1041 int y = (int) htonl(x); \
1044 else if (PerlIO_write(cxt->fio,oI(&y),oS(sizeof(y))) != oS(sizeof(y))) \
1049 else if (PerlIO_write(cxt->fio,oI(&x), \
1050 oS(sizeof(x))) != oS(sizeof(x))) \
1059 ASSERT(sizeof(x) == 8, ("W64LEN writing a U64")); \
1060 if (cxt->netorder) { \
1062 buf[1] = htonl(x & 0xffffffffUL); \
1063 buf[0] = htonl(x >> 32); \
1065 MBUF_PUTLONG(buf); \
1066 else if (PerlIO_write(cxt->fio, buf, \
1067 sizeof(buf)) != sizeof(buf)) \
1072 else if (PerlIO_write(cxt->fio,oI(&x), \
1073 oS(sizeof(x))) != oS(sizeof(x))) \
1080 #define W64LEN(x) CROAK(("No 64bit UVs"))
1085 #define WLEN(x) WRITE_I32(x)
1087 #define W64LEN(x) WRITE_U64(x)
1089 #define W64LEN(x) CROAK(("no 64bit UVs"))
1093 #define WRITE(x,y) \
1097 else if (PerlIO_write(cxt->fio, x, y) != (SSize_t)y) \
1101 #define STORE_PV_LEN(pv, len, small, large) \
1103 if (len <= LG_SCALAR) { \
1104 int ilen = (int) len; \
1105 unsigned char clen = (unsigned char) len; \
1110 } else if (sizeof(len) > 4 && len > INT32_MAX) { \
1111 PUTMARK(SX_LOBJECT); \
1116 int ilen = (int) len; \
1123 #define STORE_SCALAR(pv, len) STORE_PV_LEN(pv, len, SX_SCALAR, SX_LSCALAR)
1126 * Store &PL_sv_undef in arrays without recursing through store(). We
1127 * actually use this to represent nonexistent elements, for historical
1130 #define STORE_SV_UNDEF() \
1133 PUTMARK(SX_SV_UNDEF); \
1137 * Useful retrieve shortcuts...
1141 (cxt->fio ? PerlIO_getc(cxt->fio) \
1142 : (mptr >= mend ? EOF : (int) *mptr++))
1144 #define GETMARK(x) \
1148 else if ((int) (x = PerlIO_getc(cxt->fio)) == EOF) \
1152 #define READ_I32(x) \
1154 ASSERT(sizeof(x) == sizeof(I32), ("reading an I32")); \
1158 else if (PerlIO_read(cxt->fio, oI(&x), \
1159 oS(sizeof(x))) != oS(sizeof(x))) \
1169 else if (PerlIO_read(cxt->fio, oI(&x), \
1170 oS(sizeof(x))) != oS(sizeof(x))) \
1172 if (cxt->netorder) \
1173 x = (int) ntohl(x); \
1176 #define RLEN(x) READ_I32(x)
1183 else if (PerlIO_read(cxt->fio, x, y) != (SSize_t)y) \
1187 #define SAFEREAD(x,y,z) \
1190 MBUF_SAFEREAD(x,y,z); \
1191 else if (PerlIO_read(cxt->fio, x, y) != (SSize_t)y) { \
1197 #define SAFEPVREAD(x,y,z) \
1200 MBUF_SAFEPVREAD(x,y,z); \
1201 else if (PerlIO_read(cxt->fio, x, y) != y) { \
1209 # if defined(HAS_NTOHL)
1210 # define Sntohl(x) ntohl(x)
1211 # elif BYTEORDER == 0x87654321 || BYTEORDER == 0x4321
1212 # define Sntohl(x) (x)
1214 static U32 Sntohl(U32 x) {
1215 return (((U8) x) << 24) + ((x & 0xFF00) << 8)
1216 + ((x & 0xFF0000) >> 8) + ((x & 0xFF000000) >> 24);
1220 # define READ_U64(x) \
1222 ASSERT(sizeof(x) == 8, ("R64LEN reading a U64")); \
1223 if (cxt->netorder) { \
1225 READ((void *)buf, sizeof(buf)); \
1226 (x) = ((UV)Sntohl(buf[0]) << 32) + Sntohl(buf[1]); \
1229 READ(&(x), sizeof(x)); \
1236 * SEEN() is used at retrieve time, to remember where object 'y', bearing a
1237 * given tag 'tagnum', has been retrieved. Next time we see an SX_OBJECT marker,
1238 * we'll therefore know where it has been retrieved and will be able to
1239 * share the same reference, as in the original stored memory image.
1241 * We also need to bless objects ASAP for hooks (which may compute "ref $x"
1242 * on the objects given to STORABLE_thaw and expect that to be defined), and
1243 * also for overloaded objects (for which we might not find the stash if the
1244 * object is not blessed yet--this might occur for overloaded objects that
1245 * refer to themselves indirectly: if we blessed upon return from a sub
1246 * retrieve(), the SX_OBJECT marker we'd found could not have overloading
1247 * restored on it because the underlying object would not be blessed yet!).
1249 * To achieve that, the class name of the last retrieved object is passed down
1250 * recursively, and the first SEEN() call for which the class name is not NULL
1251 * will bless the object.
1253 * i should be true iff sv is immortal (ie PL_sv_yes, PL_sv_no or PL_sv_undef)
1255 * SEEN0() is a short-cut where stash is always NULL.
1257 * The _NN variants dont check for y being null
1259 #define SEEN0_NN(y,i) \
1261 if (av_store(cxt->aseen, cxt->tagnum++, i ? (SV*)(y) \
1262 : SvREFCNT_inc(y)) == 0) \
1264 TRACEME(("aseen(#%d) = 0x%" UVxf " (refcnt=%d)", \
1265 (int)cxt->tagnum-1, \
1266 PTR2UV(y), (int)SvREFCNT(y)-1)); \
1269 #define SEEN0(y,i) \
1276 #define SEEN_NN(y,stash,i) \
1280 BLESS((SV *)(y), (HV *)(stash)); \
1283 #define SEEN(y,stash,i) \
1287 SEEN_NN(y,stash, i); \
1291 * Bless 's' in 'p', via a temporary reference, required by sv_bless().
1292 * "A" magic is added before the sv_bless for overloaded classes, this avoids
1293 * an expensive call to S_reset_amagic in sv_bless.
1295 #define BLESS(s,stash) \
1298 if (cxt->flags & FLAG_BLESS_OK) { \
1299 TRACEME(("blessing 0x%" UVxf " in %s", PTR2UV(s), \
1300 HvNAME_get(stash))); \
1301 ref = newRV_noinc(s); \
1302 if (cxt->in_retrieve_overloaded && Gv_AMG(stash)) { \
1303 cxt->in_retrieve_overloaded = 0; \
1306 (void) sv_bless(ref, stash); \
1307 SvRV_set(ref, NULL); \
1308 SvREFCNT_dec(ref); \
1311 TRACEME(("not blessing 0x%" UVxf " in %s", PTR2UV(s), \
1312 (HvNAME_get(stash)))); \
1316 * sort (used in store_hash) - conditionally use qsort when
1317 * sortsv is not available ( <= 5.6.1 ).
1320 #if PERL_VERSION_LT(5,7,0)
1322 #if defined(USE_ITHREADS)
1324 #define STORE_HASH_SORT \
1326 PerlInterpreter *orig_perl = PERL_GET_CONTEXT; \
1327 SAVESPTR(orig_perl); \
1328 PERL_SET_CONTEXT(aTHX); \
1329 qsort((char *) AvARRAY(av), len, sizeof(SV *), sortcmp);\
1332 #else /* ! USE_ITHREADS */
1334 #define STORE_HASH_SORT \
1335 qsort((char *) AvARRAY(av), len, sizeof(SV *), sortcmp);
1337 #endif /* USE_ITHREADS */
1339 #else /* PERL >= 5.7.0 */
1341 #define STORE_HASH_SORT \
1342 sortsv(AvARRAY(av), len, Perl_sv_cmp);
1344 #endif /* PERL_VERSION_LT(5,7,0) */
1346 static int store(pTHX_ stcxt_t *cxt, SV *sv);
1347 static SV *retrieve(pTHX_ stcxt_t *cxt, const char *cname);
1351 av_pop(cxt->aseen); \
1356 * Dynamic dispatching table for SV store.
1359 static int store_ref(pTHX_ stcxt_t *cxt, SV *sv);
1360 static int store_scalar(pTHX_ stcxt_t *cxt, SV *sv);
1361 static int store_array(pTHX_ stcxt_t *cxt, AV *av);
1362 static int store_hash(pTHX_ stcxt_t *cxt, HV *hv);
1363 static int store_tied(pTHX_ stcxt_t *cxt, SV *sv);
1364 static int store_tied_item(pTHX_ stcxt_t *cxt, SV *sv);
1365 static int store_code(pTHX_ stcxt_t *cxt, CV *cv);
1366 static int store_regexp(pTHX_ stcxt_t *cxt, SV *sv);
1367 static int store_other(pTHX_ stcxt_t *cxt, SV *sv);
1368 static int store_blessed(pTHX_ stcxt_t *cxt, SV *sv, int type, HV *pkg);
1370 typedef int (*sv_store_t)(pTHX_ stcxt_t *cxt, SV *sv);
1372 static const sv_store_t sv_store[] = {
1373 (sv_store_t)store_ref, /* svis_REF */
1374 (sv_store_t)store_scalar, /* svis_SCALAR */
1375 (sv_store_t)store_array, /* svis_ARRAY */
1376 (sv_store_t)store_hash, /* svis_HASH */
1377 (sv_store_t)store_tied, /* svis_TIED */
1378 (sv_store_t)store_tied_item,/* svis_TIED_ITEM */
1379 (sv_store_t)store_code, /* svis_CODE */
1380 (sv_store_t)store_regexp, /* svis_REGEXP */
1381 (sv_store_t)store_other, /* svis_OTHER */
1384 #define SV_STORE(x) (*sv_store[x])
1387 * Dynamic dispatching tables for SV retrieval.
1390 static SV *retrieve_lscalar(pTHX_ stcxt_t *cxt, const char *cname);
1391 static SV *retrieve_lutf8str(pTHX_ stcxt_t *cxt, const char *cname);
1392 static SV *old_retrieve_array(pTHX_ stcxt_t *cxt, const char *cname);
1393 static SV *old_retrieve_hash(pTHX_ stcxt_t *cxt, const char *cname);
1394 static SV *retrieve_ref(pTHX_ stcxt_t *cxt, const char *cname);
1395 static SV *retrieve_undef(pTHX_ stcxt_t *cxt, const char *cname);
1396 static SV *retrieve_integer(pTHX_ stcxt_t *cxt, const char *cname);
1397 static SV *retrieve_double(pTHX_ stcxt_t *cxt, const char *cname);
1398 static SV *retrieve_byte(pTHX_ stcxt_t *cxt, const char *cname);
1399 static SV *retrieve_netint(pTHX_ stcxt_t *cxt, const char *cname);
1400 static SV *retrieve_scalar(pTHX_ stcxt_t *cxt, const char *cname);
1401 static SV *retrieve_utf8str(pTHX_ stcxt_t *cxt, const char *cname);
1402 static SV *retrieve_tied_array(pTHX_ stcxt_t *cxt, const char *cname);
1403 static SV *retrieve_tied_hash(pTHX_ stcxt_t *cxt, const char *cname);
1404 static SV *retrieve_tied_scalar(pTHX_ stcxt_t *cxt, const char *cname);
1405 static SV *retrieve_other(pTHX_ stcxt_t *cxt, const char *cname);
1406 static SV *retrieve_lobject(pTHX_ stcxt_t *cxt, const char *cname);
1407 static SV *retrieve_regexp(pTHX_ stcxt_t *cxt, const char *cname);
1409 /* helpers for U64 lobjects */
1411 static SV *get_lstring(pTHX_ stcxt_t *cxt, UV len, int isutf8, const char *cname);
1413 static SV *get_larray(pTHX_ stcxt_t *cxt, UV len, const char *cname);
1414 static SV *get_lhash(pTHX_ stcxt_t *cxt, UV len, int hash_flags, const char *cname);
1415 static int store_lhash(pTHX_ stcxt_t *cxt, HV *hv, unsigned char hash_flags);
1417 static int store_hentry(pTHX_ stcxt_t *cxt, HV* hv, UV i, HE *he, SV *val,
1418 unsigned char hash_flags);
1420 typedef SV* (*sv_retrieve_t)(pTHX_ stcxt_t *cxt, const char *name);
1422 static const sv_retrieve_t sv_old_retrieve[] = {
1423 0, /* SX_OBJECT -- entry unused dynamically */
1424 (sv_retrieve_t)retrieve_lscalar, /* SX_LSCALAR */
1425 (sv_retrieve_t)old_retrieve_array, /* SX_ARRAY -- for pre-0.6 binaries */
1426 (sv_retrieve_t)old_retrieve_hash, /* SX_HASH -- for pre-0.6 binaries */
1427 (sv_retrieve_t)retrieve_ref, /* SX_REF */
1428 (sv_retrieve_t)retrieve_undef, /* SX_UNDEF */
1429 (sv_retrieve_t)retrieve_integer, /* SX_INTEGER */
1430 (sv_retrieve_t)retrieve_double, /* SX_DOUBLE */
1431 (sv_retrieve_t)retrieve_byte, /* SX_BYTE */
1432 (sv_retrieve_t)retrieve_netint, /* SX_NETINT */
1433 (sv_retrieve_t)retrieve_scalar, /* SX_SCALAR */
1434 (sv_retrieve_t)retrieve_tied_array, /* SX_TIED_ARRAY */
1435 (sv_retrieve_t)retrieve_tied_hash, /* SX_TIED_HASH */
1436 (sv_retrieve_t)retrieve_tied_scalar,/* SX_TIED_SCALAR */
1437 (sv_retrieve_t)retrieve_other, /* SX_SV_UNDEF not supported */
1438 (sv_retrieve_t)retrieve_other, /* SX_SV_YES not supported */
1439 (sv_retrieve_t)retrieve_other, /* SX_SV_NO not supported */
1440 (sv_retrieve_t)retrieve_other, /* SX_BLESS not supported */
1441 (sv_retrieve_t)retrieve_other, /* SX_IX_BLESS not supported */
1442 (sv_retrieve_t)retrieve_other, /* SX_HOOK not supported */
1443 (sv_retrieve_t)retrieve_other, /* SX_OVERLOADED not supported */
1444 (sv_retrieve_t)retrieve_other, /* SX_TIED_KEY not supported */
1445 (sv_retrieve_t)retrieve_other, /* SX_TIED_IDX not supported */
1446 (sv_retrieve_t)retrieve_other, /* SX_UTF8STR not supported */
1447 (sv_retrieve_t)retrieve_other, /* SX_LUTF8STR not supported */
1448 (sv_retrieve_t)retrieve_other, /* SX_FLAG_HASH not supported */
1449 (sv_retrieve_t)retrieve_other, /* SX_CODE not supported */
1450 (sv_retrieve_t)retrieve_other, /* SX_WEAKREF not supported */
1451 (sv_retrieve_t)retrieve_other, /* SX_WEAKOVERLOAD not supported */
1452 (sv_retrieve_t)retrieve_other, /* SX_VSTRING not supported */
1453 (sv_retrieve_t)retrieve_other, /* SX_LVSTRING not supported */
1454 (sv_retrieve_t)retrieve_other, /* SX_SVUNDEF_ELEM not supported */
1455 (sv_retrieve_t)retrieve_other, /* SX_REGEXP */
1456 (sv_retrieve_t)retrieve_other, /* SX_LOBJECT not supported */
1457 (sv_retrieve_t)retrieve_other, /* SX_LAST */
1460 static SV *retrieve_hook_common(pTHX_ stcxt_t *cxt, const char *cname, int large);
1462 static SV *retrieve_array(pTHX_ stcxt_t *cxt, const char *cname);
1463 static SV *retrieve_hash(pTHX_ stcxt_t *cxt, const char *cname);
1464 static SV *retrieve_sv_undef(pTHX_ stcxt_t *cxt, const char *cname);
1465 static SV *retrieve_sv_yes(pTHX_ stcxt_t *cxt, const char *cname);
1466 static SV *retrieve_sv_no(pTHX_ stcxt_t *cxt, const char *cname);
1467 static SV *retrieve_blessed(pTHX_ stcxt_t *cxt, const char *cname);
1468 static SV *retrieve_idx_blessed(pTHX_ stcxt_t *cxt, const char *cname);
1469 static SV *retrieve_hook(pTHX_ stcxt_t *cxt, const char *cname);
1470 static SV *retrieve_overloaded(pTHX_ stcxt_t *cxt, const char *cname);
1471 static SV *retrieve_tied_key(pTHX_ stcxt_t *cxt, const char *cname);
1472 static SV *retrieve_tied_idx(pTHX_ stcxt_t *cxt, const char *cname);
1473 static SV *retrieve_flag_hash(pTHX_ stcxt_t *cxt, const char *cname);
1474 static SV *retrieve_code(pTHX_ stcxt_t *cxt, const char *cname);
1475 static SV *retrieve_weakref(pTHX_ stcxt_t *cxt, const char *cname);
1476 static SV *retrieve_weakoverloaded(pTHX_ stcxt_t *cxt, const char *cname);
1477 static SV *retrieve_vstring(pTHX_ stcxt_t *cxt, const char *cname);
1478 static SV *retrieve_lvstring(pTHX_ stcxt_t *cxt, const char *cname);
1479 static SV *retrieve_svundef_elem(pTHX_ stcxt_t *cxt, const char *cname);
1481 static const sv_retrieve_t sv_retrieve[] = {
1482 0, /* SX_OBJECT -- entry unused dynamically */
1483 (sv_retrieve_t)retrieve_lscalar, /* SX_LSCALAR */
1484 (sv_retrieve_t)retrieve_array, /* SX_ARRAY */
1485 (sv_retrieve_t)retrieve_hash, /* SX_HASH */
1486 (sv_retrieve_t)retrieve_ref, /* SX_REF */
1487 (sv_retrieve_t)retrieve_undef, /* SX_UNDEF */
1488 (sv_retrieve_t)retrieve_integer, /* SX_INTEGER */
1489 (sv_retrieve_t)retrieve_double, /* SX_DOUBLE */
1490 (sv_retrieve_t)retrieve_byte, /* SX_BYTE */
1491 (sv_retrieve_t)retrieve_netint, /* SX_NETINT */
1492 (sv_retrieve_t)retrieve_scalar, /* SX_SCALAR */
1493 (sv_retrieve_t)retrieve_tied_array, /* SX_TIED_ARRAY */
1494 (sv_retrieve_t)retrieve_tied_hash, /* SX_TIED_HASH */
1495 (sv_retrieve_t)retrieve_tied_scalar,/* SX_TIED_SCALAR */
1496 (sv_retrieve_t)retrieve_sv_undef, /* SX_SV_UNDEF */
1497 (sv_retrieve_t)retrieve_sv_yes, /* SX_SV_YES */
1498 (sv_retrieve_t)retrieve_sv_no, /* SX_SV_NO */
1499 (sv_retrieve_t)retrieve_blessed, /* SX_BLESS */
1500 (sv_retrieve_t)retrieve_idx_blessed,/* SX_IX_BLESS */
1501 (sv_retrieve_t)retrieve_hook, /* SX_HOOK */
1502 (sv_retrieve_t)retrieve_overloaded, /* SX_OVERLOAD */
1503 (sv_retrieve_t)retrieve_tied_key, /* SX_TIED_KEY */
1504 (sv_retrieve_t)retrieve_tied_idx, /* SX_TIED_IDX */
1505 (sv_retrieve_t)retrieve_utf8str, /* SX_UTF8STR */
1506 (sv_retrieve_t)retrieve_lutf8str, /* SX_LUTF8STR */
1507 (sv_retrieve_t)retrieve_flag_hash, /* SX_HASH */
1508 (sv_retrieve_t)retrieve_code, /* SX_CODE */
1509 (sv_retrieve_t)retrieve_weakref, /* SX_WEAKREF */
1510 (sv_retrieve_t)retrieve_weakoverloaded,/* SX_WEAKOVERLOAD */
1511 (sv_retrieve_t)retrieve_vstring, /* SX_VSTRING */
1512 (sv_retrieve_t)retrieve_lvstring, /* SX_LVSTRING */
1513 (sv_retrieve_t)retrieve_svundef_elem,/* SX_SVUNDEF_ELEM */
1514 (sv_retrieve_t)retrieve_regexp, /* SX_REGEXP */
1515 (sv_retrieve_t)retrieve_lobject, /* SX_LOBJECT */
1516 (sv_retrieve_t)retrieve_other, /* SX_LAST */
1519 #define RETRIEVE(c,x) ((x) >= SX_LAST ? retrieve_other : *(c)->retrieve_vtbl[x])
1521 static SV *mbuf2sv(pTHX);
1524 *** Context management.
1530 * Called once per "thread" (interpreter) to initialize some global context.
1532 static void init_perinterp(pTHX)
1536 cxt->netorder = 0; /* true if network order used */
1537 cxt->forgive_me = -1; /* whether to be forgiving... */
1538 cxt->accept_future_minor = -1; /* would otherwise occur too late */
1544 * Called at the end of every context cleaning, to perform common reset
1547 static void reset_context(stcxt_t *cxt)
1551 cxt->recur_sv = NULL;
1552 cxt->recur_depth = 0;
1553 cxt->optype &= ~(ST_STORE|ST_RETRIEVE); /* Leave ST_CLONE alone */
1557 * init_store_context
1559 * Initialize a new store context for real recursion.
1561 static void init_store_context(pTHX_
1569 TRACEME(("init_store_context"));
1571 cxt->netorder = network_order;
1572 cxt->forgive_me = -1; /* Fetched from perl if needed */
1573 cxt->deparse = -1; /* Idem */
1574 cxt->eval = NULL; /* Idem */
1575 cxt->canonical = -1; /* Idem */
1576 cxt->tagnum = -1; /* Reset tag numbers */
1577 cxt->classnum = -1; /* Reset class numbers */
1578 cxt->fio = f; /* Where I/O are performed */
1579 cxt->optype = optype; /* A store, or a deep clone */
1580 cxt->entry = 1; /* No recursion yet */
1583 * The 'hseen' table is used to keep track of each SV stored and their
1584 * associated tag numbers is special. It is "abused" because the
1585 * values stored are not real SV, just integers cast to (SV *),
1586 * which explains the freeing below.
1588 * It is also one possible bottleneck to achieve good storing speed,
1589 * so the "shared keys" optimization is turned off (unlikely to be
1590 * of any use here), and the hash table is "pre-extended". Together,
1591 * those optimizations increase the throughput by 12%.
1594 #ifdef USE_PTR_TABLE
1595 cxt->pseen = ptr_table_new();
1598 cxt->hseen = newHV(); /* Table where seen objects are stored */
1599 HvSHAREKEYS_off(cxt->hseen);
1602 * The following does not work well with perl5.004_04, and causes
1603 * a core dump later on, in a completely unrelated spot, which
1604 * makes me think there is a memory corruption going on.
1606 * Calling hv_ksplit(hseen, HBUCKETS) instead of manually hacking
1607 * it below does not make any difference. It seems to work fine
1608 * with perl5.004_68 but given the probable nature of the bug,
1609 * that does not prove anything.
1611 * It's a shame because increasing the amount of buckets raises
1612 * store() throughput by 5%, but until I figure this out, I can't
1613 * allow for this to go into production.
1615 * It is reported fixed in 5.005, hence the #if.
1617 #define HBUCKETS 4096 /* Buckets for %hseen */
1618 #ifndef USE_PTR_TABLE
1619 HvMAX(cxt->hseen) = HBUCKETS - 1; /* keys %hseen = $HBUCKETS; */
1623 * The 'hclass' hash uses the same settings as 'hseen' above, but it is
1624 * used to assign sequential tags (numbers) to class names for blessed
1627 * We turn the shared key optimization on.
1630 cxt->hclass = newHV(); /* Where seen classnames are stored */
1632 HvMAX(cxt->hclass) = HBUCKETS - 1; /* keys %hclass = $HBUCKETS; */
1635 * The 'hook' hash table is used to keep track of the references on
1636 * the STORABLE_freeze hook routines, when found in some class name.
1638 * It is assumed that the inheritance tree will not be changed during
1639 * storing, and that no new method will be dynamically created by the
1643 cxt->hook = newHV(); /* Table where hooks are cached */
1646 * The 'hook_seen' array keeps track of all the SVs returned by
1647 * STORABLE_freeze hooks for us to serialize, so that they are not
1648 * reclaimed until the end of the serialization process. Each SV is
1649 * only stored once, the first time it is seen.
1652 cxt->hook_seen = newAV(); /* Lists SVs returned by STORABLE_freeze */
1654 cxt->max_recur_depth = SvIV(get_sv("Storable::recursion_limit", GV_ADD));
1655 cxt->max_recur_depth_hash = SvIV(get_sv("Storable::recursion_limit_hash", GV_ADD));
1659 * clean_store_context
1661 * Clean store context by
1663 static void clean_store_context(pTHX_ stcxt_t *cxt)
1667 TRACEMED(("clean_store_context"));
1669 ASSERT(cxt->optype & ST_STORE, ("was performing a store()"));
1672 * Insert real values into hashes where we stored faked pointers.
1675 #ifndef USE_PTR_TABLE
1677 hv_iterinit(cxt->hseen);
1678 while ((he = hv_iternext(cxt->hseen))) /* Extra () for -Wall */
1679 HeVAL(he) = &PL_sv_undef;
1684 hv_iterinit(cxt->hclass);
1685 while ((he = hv_iternext(cxt->hclass))) /* Extra () for -Wall */
1686 HeVAL(he) = &PL_sv_undef;
1690 * And now dispose of them...
1692 * The surrounding if() protection has been added because there might be
1693 * some cases where this routine is called more than once, during
1694 * exceptional events. This was reported by Marc Lehmann when Storable
1695 * is executed from mod_perl, and the fix was suggested by him.
1696 * -- RAM, 20/12/2000
1699 #ifdef USE_PTR_TABLE
1701 struct ptr_tbl *pseen = cxt->pseen;
1703 ptr_table_free(pseen);
1705 assert(!cxt->hseen);
1708 HV *hseen = cxt->hseen;
1711 sv_free((SV *) hseen);
1716 HV *hclass = cxt->hclass;
1719 sv_free((SV *) hclass);
1723 HV *hook = cxt->hook;
1726 sv_free((SV *) hook);
1729 if (cxt->hook_seen) {
1730 AV *hook_seen = cxt->hook_seen;
1732 av_undef(hook_seen);
1733 sv_free((SV *) hook_seen);
1736 cxt->forgive_me = -1; /* Fetched from perl if needed */
1737 cxt->deparse = -1; /* Idem */
1739 SvREFCNT_dec(cxt->eval);
1741 cxt->eval = NULL; /* Idem */
1742 cxt->canonical = -1; /* Idem */
1748 * init_retrieve_context
1750 * Initialize a new retrieve context for real recursion.
1752 static void init_retrieve_context(pTHX_
1753 stcxt_t *cxt, int optype, int is_tainted)
1757 TRACEME(("init_retrieve_context"));
1760 * The hook hash table is used to keep track of the references on
1761 * the STORABLE_thaw hook routines, when found in some class name.
1763 * It is assumed that the inheritance tree will not be changed during
1764 * storing, and that no new method will be dynamically created by the
1768 cxt->hook = newHV(); /* Caches STORABLE_thaw */
1770 #ifdef USE_PTR_TABLE
1775 * If retrieving an old binary version, the cxt->retrieve_vtbl variable
1776 * was set to sv_old_retrieve. We'll need a hash table to keep track of
1777 * the correspondence between the tags and the tag number used by the
1778 * new retrieve routines.
1781 cxt->hseen = (((void*)cxt->retrieve_vtbl == (void*)sv_old_retrieve)
1784 cxt->aseen = newAV(); /* Where retrieved objects are kept */
1785 cxt->where_is_undef = UNSET_NTAG_T; /* Special case for PL_sv_undef */
1786 cxt->aclass = newAV(); /* Where seen classnames are kept */
1787 cxt->tagnum = 0; /* Have to count objects... */
1788 cxt->classnum = 0; /* ...and class names as well */
1789 cxt->optype = optype;
1790 cxt->s_tainted = is_tainted;
1791 cxt->entry = 1; /* No recursion yet */
1792 #ifndef HAS_RESTRICTED_HASHES
1793 cxt->derestrict = -1; /* Fetched from perl if needed */
1795 #ifndef HAS_UTF8_ALL
1796 cxt->use_bytes = -1; /* Fetched from perl if needed */
1798 cxt->accept_future_minor = -1;/* Fetched from perl if needed */
1799 cxt->in_retrieve_overloaded = 0;
1801 cxt->max_recur_depth = SvIV(get_sv("Storable::recursion_limit", GV_ADD));
1802 cxt->max_recur_depth_hash = SvIV(get_sv("Storable::recursion_limit_hash", GV_ADD));
1806 * clean_retrieve_context
1808 * Clean retrieve context by
1810 static void clean_retrieve_context(pTHX_ stcxt_t *cxt)
1812 TRACEMED(("clean_retrieve_context"));
1814 ASSERT(cxt->optype & ST_RETRIEVE, ("was performing a retrieve()"));
1817 AV *aseen = cxt->aseen;
1820 sv_free((SV *) aseen);
1822 cxt->where_is_undef = UNSET_NTAG_T;
1825 AV *aclass = cxt->aclass;
1828 sv_free((SV *) aclass);
1832 HV *hook = cxt->hook;
1835 sv_free((SV *) hook);
1839 HV *hseen = cxt->hseen;
1842 sv_free((SV *) hseen); /* optional HV, for backward compat. */
1845 #ifndef HAS_RESTRICTED_HASHES
1846 cxt->derestrict = -1; /* Fetched from perl if needed */
1848 #ifndef HAS_UTF8_ALL
1849 cxt->use_bytes = -1; /* Fetched from perl if needed */
1851 cxt->accept_future_minor = -1; /* Fetched from perl if needed */
1853 cxt->in_retrieve_overloaded = 0;
1860 * A workaround for the CROAK bug: cleanup the last context.
1862 static void clean_context(pTHX_ stcxt_t *cxt)
1864 TRACEMED(("clean_context"));
1866 ASSERT(cxt->s_dirty, ("dirty context"));
1871 ASSERT(!cxt->membuf_ro, ("mbase is not read-only"));
1873 if (cxt->optype & ST_RETRIEVE)
1874 clean_retrieve_context(aTHX_ cxt);
1875 else if (cxt->optype & ST_STORE)
1876 clean_store_context(aTHX_ cxt);
1880 ASSERT(!cxt->s_dirty, ("context is clean"));
1881 ASSERT(cxt->entry == 0, ("context is reset"));
1887 * Allocate a new context and push it on top of the parent one.
1888 * This new context is made globally visible via SET_STCXT().
1890 static stcxt_t *allocate_context(pTHX_ stcxt_t *parent_cxt)
1894 ASSERT(!parent_cxt->s_dirty, ("parent context clean"));
1896 NEW_STORABLE_CXT_OBJ(cxt);
1897 TRACEMED(("allocate_context"));
1899 cxt->prev = parent_cxt->my_sv;
1902 ASSERT(!cxt->s_dirty, ("clean context"));
1910 * Free current context, which cannot be the "root" one.
1911 * Make the context underneath globally visible via SET_STCXT().
1913 static void free_context(pTHX_ stcxt_t *cxt)
1915 stcxt_t *prev = (stcxt_t *)(cxt->prev ? SvPVX(SvRV(cxt->prev)) : 0);
1917 TRACEMED(("free_context"));
1919 ASSERT(!cxt->s_dirty, ("clean context"));
1920 ASSERT(prev, ("not freeing root context"));
1923 SvREFCNT_dec(cxt->my_sv);
1926 ASSERT(cxt, ("context not void"));
1933 /* these two functions are currently only used within asserts */
1938 * Tells whether we're in the middle of a store operation.
1940 static int is_storing(pTHX)
1944 return cxt->entry && (cxt->optype & ST_STORE);
1950 * Tells whether we're in the middle of a retrieve operation.
1952 static int is_retrieving(pTHX)
1956 return cxt->entry && (cxt->optype & ST_RETRIEVE);
1961 * last_op_in_netorder
1963 * Returns whether last operation was made using network order.
1965 * This is typically out-of-band information that might prove useful
1966 * to people wishing to convert native to network order data when used.
1968 static int last_op_in_netorder(pTHX)
1973 return cxt->netorder;
1977 *** Hook lookup and calling routines.
1983 * A wrapper on gv_fetchmethod_autoload() which caches results.
1985 * Returns the routine reference as an SV*, or null if neither the package
1986 * nor its ancestors know about the method.
1988 static SV *pkg_fetchmeth(pTHX_
1995 const char *hvname = HvNAME_get(pkg);
2001 * The following code is the same as the one performed by UNIVERSAL::can
2005 gv = gv_fetchmethod_autoload(pkg, method, FALSE);
2006 if (gv && isGV(gv)) {
2007 sv = newRV_inc((SV*) GvCV(gv));
2008 TRACEME(("%s->%s: 0x%" UVxf, hvname, method, PTR2UV(sv)));
2010 sv = newSVsv(&PL_sv_undef);
2011 TRACEME(("%s->%s: not found", hvname, method));
2015 * Cache the result, ignoring failure: if we can't store the value,
2016 * it just won't be cached.
2019 (void) hv_store(cache, hvname, strlen(hvname), sv, 0);
2021 return SvOK(sv) ? sv : (SV *) 0;
2027 * Force cached value to be undef: hook ignored even if present.
2029 static void pkg_hide(pTHX_
2034 const char *hvname = HvNAME_get(pkg);
2035 PERL_UNUSED_ARG(method);
2036 (void) hv_store(cache,
2037 hvname, strlen(hvname), newSVsv(&PL_sv_undef), 0);
2043 * Discard cached value: a whole fetch loop will be retried at next lookup.
2045 static void pkg_uncache(pTHX_
2050 const char *hvname = HvNAME_get(pkg);
2051 PERL_UNUSED_ARG(method);
2052 (void) hv_delete(cache, hvname, strlen(hvname), G_DISCARD);
2058 * Our own "UNIVERSAL::can", which caches results.
2060 * Returns the routine reference as an SV*, or null if the object does not
2061 * know about the method.
2063 static SV *pkg_can(pTHX_
2070 const char *hvname = HvNAME_get(pkg);
2075 TRACEME(("pkg_can for %s->%s", hvname, method));
2078 * Look into the cache to see whether we already have determined
2079 * where the routine was, if any.
2081 * NOTA BENE: we don't use 'method' at all in our lookup, since we know
2082 * that only one hook (i.e. always the same) is cached in a given cache.
2085 svh = hv_fetch(cache, hvname, strlen(hvname), FALSE);
2089 TRACEME(("cached %s->%s: not found", hvname, method));
2092 TRACEME(("cached %s->%s: 0x%" UVxf,
2093 hvname, method, PTR2UV(sv)));
2098 TRACEME(("not cached yet"));
2099 return pkg_fetchmeth(aTHX_ cache, pkg, method); /* Fetch and cache */
2105 * Call routine as obj->hook(av) in scalar context.
2106 * Propagates the single returned value if not called in void context.
2108 static SV *scalar_call(pTHX_
2122 TRACEME(("scalar_call (cloning=%d)", cloning));
2129 XPUSHs(sv_2mortal(newSViv(cloning))); /* Cloning flag */
2131 SV **ary = AvARRAY(av);
2132 SSize_t cnt = AvFILLp(av) + 1;
2134 XPUSHs(ary[0]); /* Frozen string */
2135 for (i = 1; i < cnt; i++) {
2136 TRACEME(("pushing arg #%d (0x%" UVxf ")...",
2137 (int)i, PTR2UV(ary[i])));
2138 XPUSHs(sv_2mortal(newRV_inc(ary[i])));
2143 TRACEME(("calling..."));
2144 count = call_sv(hook, flags); /* Go back to Perl code */
2145 TRACEME(("count = %d", count));
2151 SvREFCNT_inc(sv); /* We're returning it, must stay alive! */
2164 * Call routine obj->hook(cloning) in list context.
2165 * Returns the list of returned values in an array.
2167 static AV *array_call(pTHX_
2180 TRACEME(("array_call (cloning=%d)", cloning));
2186 XPUSHs(obj); /* Target object */
2187 XPUSHs(sv_2mortal(newSViv(cloning))); /* Cloning flag */
2190 count = call_sv(hook, G_ARRAY); /* Go back to Perl code */
2195 for (i = count - 1; i >= 0; i--) {
2197 av_store(av, i, SvREFCNT_inc(sv));
2207 #if PERL_VERSION_LT(5,15,0)
2209 cleanup_recursive_av(pTHX_ AV* av) {
2210 SSize_t i = AvFILLp(av);
2211 SV** arr = AvARRAY(av);
2212 if (SvMAGICAL(av)) return;
2215 #if PERL_VERSION_LT(5,14,0)
2218 SvREFCNT_dec(arr[i]);
2225 #ifndef SvREFCNT_IMMORTAL
2227 /* exercise the immortal resurrection code in sv_free2() */
2228 # define SvREFCNT_IMMORTAL 1000
2230 # define SvREFCNT_IMMORTAL ((~(U32)0)/2)
2235 cleanup_recursive_hv(pTHX_ HV* hv) {
2236 SSize_t i = HvTOTALKEYS(hv);
2237 HE** arr = HvARRAY(hv);
2238 if (SvMAGICAL(hv)) return;
2241 SvREFCNT(HeVAL(arr[i])) = SvREFCNT_IMMORTAL;
2242 arr[i] = NULL; /* let it leak. too dangerous to clean it up here */
2246 #if PERL_VERSION_LT(5,8,0)
2247 ((XPVHV*)SvANY(hv))->xhv_array = NULL;
2251 HvTOTALKEYS(hv) = 0;
2254 cleanup_recursive_rv(pTHX_ SV* sv) {
2255 if (sv && SvROK(sv))
2256 SvREFCNT_dec(SvRV(sv));
2259 cleanup_recursive_data(pTHX_ SV* sv) {
2260 if (SvTYPE(sv) == SVt_PVAV) {
2261 cleanup_recursive_av(aTHX_ (AV*)sv);
2263 else if (SvTYPE(sv) == SVt_PVHV) {
2264 cleanup_recursive_hv(aTHX_ (HV*)sv);
2267 cleanup_recursive_rv(aTHX_ sv);
2275 * Lookup the class name in the 'hclass' table and either assign it a new ID
2276 * or return the existing one, by filling in 'classnum'.
2278 * Return true if the class was known, false if the ID was just generated.
2280 static int known_class(pTHX_
2282 char *name, /* Class name */
2283 int len, /* Name length */
2287 HV *hclass = cxt->hclass;
2289 TRACEME(("known_class (%s)", name));
2292 * Recall that we don't store pointers in this hash table, but tags.
2293 * Therefore, we need LOW_32BITS() to extract the relevant parts.
2296 svh = hv_fetch(hclass, name, len, FALSE);
2298 *classnum = LOW_32BITS(*svh);
2303 * Unknown classname, we need to record it.
2307 if (!hv_store(hclass, name, len, INT2PTR(SV*, cxt->classnum), 0))
2308 CROAK(("Unable to record new classname"));
2310 *classnum = cxt->classnum;
2315 *** Specific store routines.
2321 * Store a reference.
2322 * Layout is SX_REF <object> or SX_OVERLOAD <object>.
2324 static int store_ref(pTHX_ stcxt_t *cxt, SV *sv)
2328 TRACEME(("store_ref (0x%" UVxf ")", PTR2UV(sv)));
2331 * Follow reference, and check if target is overloaded.
2337 TRACEME(("ref (0x%" UVxf ") is%s weak", PTR2UV(sv),
2338 is_weak ? "" : "n't"));
2343 HV *stash = (HV *) SvSTASH(sv);
2344 if (stash && Gv_AMG(stash)) {
2345 TRACEME(("ref (0x%" UVxf ") is overloaded", PTR2UV(sv)));
2346 PUTMARK(is_weak ? SX_WEAKOVERLOAD : SX_OVERLOAD);
2348 PUTMARK(is_weak ? SX_WEAKREF : SX_REF);
2350 PUTMARK(is_weak ? SX_WEAKREF : SX_REF);
2354 TRACEME((">ref recur_depth %" IVdf ", recur_sv (0x%" UVxf ") max %" IVdf, cxt->recur_depth,
2355 PTR2UV(cxt->recur_sv), cxt->max_recur_depth));
2356 if (RECURSION_TOO_DEEP()) {
2357 #if PERL_VERSION_LT(5,15,0)
2358 cleanup_recursive_data(aTHX_ (SV*)sv);
2360 CROAK((MAX_DEPTH_ERROR));
2363 retval = store(aTHX_ cxt, sv);
2364 if (cxt->max_recur_depth != -1 && cxt->recur_depth > 0) {
2365 TRACEME(("<ref recur_depth --%" IVdf, cxt->recur_depth));
2376 * Layout is SX_LSCALAR <length> <data>, SX_SCALAR <length> <data> or SX_UNDEF.
2377 * SX_LUTF8STR and SX_UTF8STR are used for UTF-8 strings.
2378 * The <data> section is omitted if <length> is 0.
2380 * For vstrings, the vstring portion is stored first with
2381 * SX_LVSTRING <length> <data> or SX_VSTRING <length> <data>, followed by
2382 * SX_(L)SCALAR or SX_(L)UTF8STR with the actual PV.
2384 * If integer or double, the layout is SX_INTEGER <data> or SX_DOUBLE <data>.
2385 * Small integers (within [-127, +127]) are stored as SX_BYTE <byte>.
2387 * For huge strings use SX_LOBJECT SX_type SX_U64 <type> <data>
2389 static int store_scalar(pTHX_ stcxt_t *cxt, SV *sv)
2394 U32 flags = SvFLAGS(sv); /* "cc -O" may put it in register */
2396 TRACEME(("store_scalar (0x%" UVxf ")", PTR2UV(sv)));
2399 * For efficiency, break the SV encapsulation by peaking at the flags
2400 * directly without using the Perl macros to avoid dereferencing
2401 * sv->sv_flags each time we wish to check the flags.
2404 if (!(flags & SVf_OK)) { /* !SvOK(sv) */
2405 if (sv == &PL_sv_undef) {
2406 TRACEME(("immortal undef"));
2407 PUTMARK(SX_SV_UNDEF);
2409 TRACEME(("undef at 0x%" UVxf, PTR2UV(sv)));
2416 * Always store the string representation of a scalar if it exists.
2417 * Gisle Aas provided me with this test case, better than a long speach:
2419 * perl -MDevel::Peek -le '$a="abc"; $a+0; Dump($a)'
2420 * SV = PVNV(0x80c8520)
2422 * FLAGS = (NOK,POK,pNOK,pPOK)
2425 * PV = 0x80c83d0 "abc"\0
2429 * Write SX_SCALAR, length, followed by the actual data.
2431 * Otherwise, write an SX_BYTE, SX_INTEGER or an SX_DOUBLE as
2432 * appropriate, followed by the actual (binary) data. A double
2433 * is written as a string if network order, for portability.
2435 * NOTE: instead of using SvNOK(sv), we test for SvNOKp(sv).
2436 * The reason is that when the scalar value is tainted, the SvNOK(sv)
2439 * The test for a read-only scalar with both POK and NOK set is meant
2440 * to quickly detect &PL_sv_yes and &PL_sv_no without having to pay the
2441 * address comparison for each scalar we store.
2444 #define SV_MAYBE_IMMORTAL (SVf_READONLY|SVf_POK|SVf_NOK)
2446 if ((flags & SV_MAYBE_IMMORTAL) == SV_MAYBE_IMMORTAL) {
2447 if (sv == &PL_sv_yes) {
2448 TRACEME(("immortal yes"));
2450 } else if (sv == &PL_sv_no) {
2451 TRACEME(("immortal no"));
2454 pv = SvPV(sv, len); /* We know it's SvPOK */
2455 goto string; /* Share code below */
2457 } else if (flags & SVf_POK) {
2458 /* public string - go direct to string read. */
2459 goto string_readlen;
2461 #if PERL_VERSION_LT(5,7,0)
2462 /* For 5.6 and earlier NV flag trumps IV flag, so only use integer
2463 direct if NV flag is off. */
2464 (flags & (SVf_NOK | SVf_IOK)) == SVf_IOK
2466 /* 5.7 rules are that if IV public flag is set, IV value is as
2467 good, if not better, than NV value. */
2473 * Will come here from below with iv set if double is an integer.
2477 /* Sorry. This isn't in 5.005_56 (IIRC) or earlier. */
2479 /* Need to do this out here, else 0xFFFFFFFF becomes iv of -1
2480 * (for example) and that ends up in the optimised small integer
2483 if ((flags & SVf_IVisUV) && SvUV(sv) > IV_MAX) {
2484 TRACEME(("large unsigned integer as string, value = %" UVuf,
2486 goto string_readlen;
2490 * Optimize small integers into a single byte, otherwise store as
2491 * a real integer (converted into network order if they asked).
2494 if (iv >= -128 && iv <= 127) {
2495 unsigned char siv = (unsigned char) (iv + 128); /* [0,255] */
2498 TRACEME(("small integer stored as %d", (int)siv));
2499 } else if (cxt->netorder) {
2501 TRACEME(("no htonl, fall back to string for integer"));
2502 goto string_readlen;
2510 /* Sorry. This isn't in 5.005_56 (IIRC) or earlier. */
2511 ((flags & SVf_IVisUV) && SvUV(sv) > (UV)0x7FFFFFFF) ||
2513 (iv > (IV)0x7FFFFFFF) || (iv < -(IV)0x80000000)) {
2514 /* Bigger than 32 bits. */
2515 TRACEME(("large network order integer as string, value = %" IVdf, iv));
2516 goto string_readlen;
2520 niv = (I32) htonl((I32) iv);
2521 TRACEME(("using network order"));
2526 PUTMARK(SX_INTEGER);
2527 WRITE(&iv, sizeof(iv));
2530 TRACEME(("ok (integer 0x%" UVxf ", value = %" IVdf ")", PTR2UV(sv), iv));
2531 } else if (flags & SVf_NOK) {
2534 /* if we can't tell if there's padding, clear the whole NV and hope the
2535 compiler leaves the padding alone
2537 Zero(&nv, 1, NV_bytes);
2539 #if PERL_VERSION_LT(5,7,0)
2542 * Watch for number being an integer in disguise.
2544 if (nv.nv == (NV) (iv = I_V(nv.nv))) {
2545 TRACEME(("double %" NVff " is actually integer %" IVdf, nv, iv));
2546 goto integer; /* Share code above */
2551 if (SvIOK_notUV(sv)) {
2553 goto integer; /* Share code above */
2558 if (cxt->netorder) {
2559 TRACEME(("double %" NVff " stored as string", nv.nv));
2560 goto string_readlen; /* Share code below */
2563 Zero(nv.bytes + NVSIZE - NV_PADDING, NV_PADDING, char);
2567 WRITE(&nv, sizeof(nv));
2569 TRACEME(("ok (double 0x%" UVxf ", value = %" NVff ")", PTR2UV(sv), nv.nv));
2571 } else if (flags & (SVp_POK | SVp_NOK | SVp_IOK)) {
2575 UV wlen; /* For 64-bit machines */
2581 * Will come here from above if it was readonly, POK and NOK but
2582 * neither &PL_sv_yes nor &PL_sv_no.
2587 if (SvMAGICAL(sv) && (mg = mg_find(sv, 'V'))) {
2588 /* The macro passes this by address, not value, and a lot of
2589 called code assumes that it's 32 bits without checking. */
2590 const SSize_t len = mg->mg_len;
2591 /* we no longer accept vstrings over I32_SIZE-1, so don't emit
2592 them, also, older Storables handle them badly.
2594 if (len >= I32_MAX) {
2595 CROAK(("vstring too large to freeze"));
2597 STORE_PV_LEN((const char *)mg->mg_ptr,
2598 len, SX_VSTRING, SX_LVSTRING);
2604 STORE_UTF8STR(pv, wlen);
2606 STORE_SCALAR(pv, wlen);
2607 TRACEME(("ok (scalar 0x%" UVxf " '%s', length = %" UVuf ")",
2608 PTR2UV(sv), len >= 2048 ? "<string too long>" : SvPVX(sv),
2611 CROAK(("Can't determine type of %s(0x%" UVxf ")",
2612 sv_reftype(sv, FALSE),
2615 return 0; /* Ok, no recursion on scalars */
2623 * Layout is SX_ARRAY <size> followed by each item, in increasing index order.
2624 * Each item is stored as <object>.
2626 static int store_array(pTHX_ stcxt_t *cxt, AV *av)
2629 UV len = av_len(av) + 1;
2632 SV *const recur_sv = cxt->recur_sv;
2634 TRACEME(("store_array (0x%" UVxf ")", PTR2UV(av)));
2637 if (len > 0x7fffffffu) {
2639 * Large array by emitting SX_LOBJECT 1 U64 data
2641 PUTMARK(SX_LOBJECT);
2644 TRACEME(("lobject size = %lu", (unsigned long)len));
2649 * Normal array by emitting SX_ARRAY, followed by the array length.
2654 TRACEME(("size = %d", (int)l));
2657 TRACEME((">array recur_depth %" IVdf ", recur_sv (0x%" UVxf ") max %" IVdf, cxt->recur_depth,
2658 PTR2UV(cxt->recur_sv), cxt->max_recur_depth));
2659 if (recur_sv != (SV*)av) {
2660 if (RECURSION_TOO_DEEP()) {
2661 /* with <= 5.14 it recurses in the cleanup also, needing 2x stack size */
2662 #if PERL_VERSION_LT(5,15,0)
2663 cleanup_recursive_data(aTHX_ (SV*)av);
2665 CROAK((MAX_DEPTH_ERROR));
2670 * Now store each item recursively.
2673 for (i = 0; i < len; i++) {
2674 sav = av_fetch(av, i, 0);
2676 TRACEME(("(#%d) nonexistent item", (int)i));
2680 #if PERL_VERSION_GE(5,19,0)
2681 /* In 5.19.3 and up, &PL_sv_undef can actually be stored in
2682 * an array; it no longer represents nonexistent elements.
2683 * Historically, we have used SX_SV_UNDEF in arrays for
2684 * nonexistent elements, so we use SX_SVUNDEF_ELEM for
2685 * &PL_sv_undef itself. */
2686 if (*sav == &PL_sv_undef) {
2687 TRACEME(("(#%d) undef item", (int)i));
2689 PUTMARK(SX_SVUNDEF_ELEM);
2693 TRACEME(("(#%d) item", (int)i));
2694 if ((ret = store(aTHX_ cxt, *sav))) /* Extra () for -Wall */
2698 if (recur_sv != (SV*)av) {
2699 assert(cxt->max_recur_depth == -1 || cxt->recur_depth > 0);
2700 if (cxt->max_recur_depth != -1 && cxt->recur_depth > 0) {
2701 TRACEME(("<array recur_depth --%" IVdf, cxt->recur_depth));
2705 TRACEME(("ok (array)"));
2711 #if PERL_VERSION_LT(5,7,0)
2717 * Borrowed from perl source file pp_ctl.c, where it is used by pp_sort.
2720 sortcmp(const void *a, const void *b)
2722 #if defined(USE_ITHREADS)
2724 #endif /* USE_ITHREADS */
2725 return sv_cmp(*(SV * const *) a, *(SV * const *) b);
2728 #endif /* PERL_VERSION_LT(5,7,0) */
2733 * Store a hash table.
2735 * For a "normal" hash (not restricted, no utf8 keys):
2737 * Layout is SX_HASH <size> followed by each key/value pair, in random order.
2738 * Values are stored as <object>.
2739 * Keys are stored as <length> <data>, the <data> section being omitted
2742 * For a "fancy" hash (restricted or utf8 keys):
2744 * Layout is SX_FLAG_HASH <size> <hash flags> followed by each key/value pair,
2746 * Values are stored as <object>.
2747 * Keys are stored as <flags> <length> <data>, the <data> section being omitted
2749 * Currently the only hash flag is "restricted"
2750 * Key flags are as for hv.h
2752 static int store_hash(pTHX_ stcxt_t *cxt, HV *hv)
2755 UV len = (UV)HvTOTALKEYS(hv);
2760 int flagged_hash = ((SvREADONLY(hv)
2761 #ifdef HAS_HASH_KEY_FLAGS
2765 unsigned char hash_flags = (SvREADONLY(hv) ? SHV_RESTRICTED : 0);
2766 SV * const recur_sv = cxt->recur_sv;
2769 * Signal hash by emitting SX_HASH, followed by the table length.
2770 * Max number of keys per perl version:
2772 * STRLEN 5.14 - 5.24 (size_t: U32/U64)
2773 * SSize_t 5.22c - 5.24c (I32/I64)
2777 if (len > 0x7fffffffu) { /* keys > I32_MAX */
2779 * Large hash: SX_LOBJECT type hashflags? U64 data
2781 * Stupid limitation:
2782 * Note that perl5 can store more than 2G keys, but only iterate
2783 * over 2G max. (cperl can)
2784 * We need to manually iterate over it then, unsorted.
2785 * But until perl itself cannot do that, skip that.
2787 TRACEME(("lobject size = %lu", (unsigned long)len));
2789 PUTMARK(SX_LOBJECT);
2791 PUTMARK(SX_FLAG_HASH);
2792 PUTMARK(hash_flags);
2797 return store_lhash(aTHX_ cxt, hv, hash_flags);
2799 /* <5.12 you could store larger hashes, but cannot iterate over them.
2800 So we reject them, it's a bug. */
2801 CROAK(("Cannot store large objects on a 32bit system"));
2806 TRACEME(("store_hash (0x%" UVxf ") (flags %x)", PTR2UV(hv),
2807 (unsigned int)hash_flags));
2808 PUTMARK(SX_FLAG_HASH);
2809 PUTMARK(hash_flags);
2811 TRACEME(("store_hash (0x%" UVxf ")", PTR2UV(hv)));
2815 TRACEME(("size = %d, used = %d", (int)l, (int)HvUSEDKEYS(hv)));
2818 TRACEME((">hash recur_depth %" IVdf ", recur_sv (0x%" UVxf ") max %" IVdf, cxt->recur_depth,
2819 PTR2UV(cxt->recur_sv), cxt->max_recur_depth_hash));
2820 if (recur_sv != (SV*)hv && cxt->max_recur_depth_hash != -1) {
2823 if (RECURSION_TOO_DEEP_HASH()) {
2824 #if PERL_VERSION_LT(5,15,0)
2825 cleanup_recursive_data(aTHX_ (SV*)hv);
2827 CROAK((MAX_DEPTH_ERROR));
2831 * Save possible iteration state via each() on that table.
2833 * Note that perl as of 5.24 *can* store more than 2G keys, but *not*
2835 * Lengths of hash keys are also limited to I32, which is good.
2838 riter = HvRITER_get(hv);
2839 eiter = HvEITER_get(hv);
2843 * Now store each item recursively.
2845 * If canonical is defined to some true value then store each
2846 * key/value pair in sorted order otherwise the order is random.
2847 * Canonical order is irrelevant when a deep clone operation is performed.
2849 * Fetch the value from perl only once per store() operation, and only
2854 !(cxt->optype & ST_CLONE)
2855 && (cxt->canonical == 1
2856 || (cxt->canonical < 0
2857 && (cxt->canonical =
2858 (SvTRUE(get_sv("Storable::canonical", GV_ADD))
2862 * Storing in order, sorted by key.
2863 * Run through the hash, building up an array of keys in a
2864 * mortal array, sort the array and then run through the
2868 av_extend (av, len);
2870 TRACEME(("using canonical order"));
2872 for (i = 0; i < len; i++) {
2873 #ifdef HAS_RESTRICTED_HASHES
2874 HE *he = hv_iternext_flags(hv, HV_ITERNEXT_WANTPLACEHOLDERS);
2876 HE *he = hv_iternext(hv);
2878 av_store(av, i, hv_iterkeysv(he));
2883 for (i = 0; i < len; i++) {
2884 #ifdef HAS_RESTRICTED_HASHES
2885 int placeholders = (int)HvPLACEHOLDERS_get(hv);
2887 unsigned char flags = 0;
2891 SV *key = av_shift(av);
2892 /* This will fail if key is a placeholder.
2893 Track how many placeholders we have, and error if we
2895 HE *he = hv_fetch_ent(hv, key, 0, 0);
2899 if (!(val = HeVAL(he))) {
2900 /* Internal error, not I/O error */
2904 #ifdef HAS_RESTRICTED_HASHES
2905 /* Should be a placeholder. */
2906 if (placeholders-- < 0) {
2907 /* This should not happen - number of
2908 retrieves should be identical to
2909 number of placeholders. */
2912 /* Value is never needed, and PL_sv_undef is
2913 more space efficient to store. */
2916 ("Flags not 0 but %d", (int)flags));
2917 flags = SHV_K_PLACEHOLDER;
2924 * Store value first.
2927 TRACEME(("(#%d) value 0x%" UVxf, (int)i, PTR2UV(val)));
2929 if ((ret = store(aTHX_ cxt, val))) /* Extra () for -Wall, grr... */
2934 * Keys are written after values to make sure retrieval
2935 * can be optimal in terms of memory usage, where keys are
2936 * read into a fixed unique buffer called kbuf.
2937 * See retrieve_hash() for details.
2940 /* Implementation of restricted hashes isn't nicely
2942 if ((hash_flags & SHV_RESTRICTED)
2943 && SvTRULYREADONLY(val)) {
2944 flags |= SHV_K_LOCKED;
2947 keyval = SvPV(key, keylen_tmp);
2948 keylen = keylen_tmp;
2950 const char *keysave = keyval;
2951 bool is_utf8 = TRUE;
2953 /* Just casting the &klen to (STRLEN) won't work
2954 well if STRLEN and I32 are of different widths.
2956 keyval = (char*)bytes_from_utf8((U8*)keyval,
2960 /* If we were able to downgrade here, then than
2961 means that we have a key which only had chars
2962 0-255, but was utf8 encoded. */
2964 if (keyval != keysave) {
2965 keylen = keylen_tmp;
2966 flags |= SHV_K_WASUTF8;
2968 /* keylen_tmp can't have changed, so no need
2969 to assign back to keylen. */
2970 flags |= SHV_K_UTF8;
2976 TRACEME(("(#%d) key '%s' flags %x %u", (int)i, keyval, flags, *keyval));
2978 /* This is a workaround for a bug in 5.8.0
2979 that causes the HEK_WASUTF8 flag to be
2980 set on an HEK without the hash being
2981 marked as having key flags. We just
2982 cross our fingers and drop the flag.
2984 assert (flags == 0 || flags == SHV_K_WASUTF8);
2985 TRACEME(("(#%d) key '%s'", (int)i, keyval));
2989 WRITE(keyval, keylen);
2990 if (flags & SHV_K_WASUTF8)
2995 * Free up the temporary array
3004 * Storing in "random" order (in the order the keys are stored
3005 * within the hash). This is the default and will be faster!
3008 for (i = 0; i < len; i++) {
3009 #ifdef HV_ITERNEXT_WANTPLACEHOLDERS
3010 HE *he = hv_iternext_flags(hv, HV_ITERNEXT_WANTPLACEHOLDERS);
3012 HE *he = hv_iternext(hv);
3014 SV *val = (he ? hv_iterval(hv, he) : 0);
3017 return 1; /* Internal error, not I/O error */
3019 if ((ret = store_hentry(aTHX_ cxt, hv, i, he, val, hash_flags)))
3024 TRACEME(("ok (hash 0x%" UVxf ")", PTR2UV(hv)));
3027 assert(cxt->max_recur_depth_hash != -1 && cxt->recur_depth > 0);
3028 TRACEME(("<hash recur_depth --%" IVdf , cxt->recur_depth));
3029 if (cxt->max_recur_depth_hash != -1 && recur_sv != (SV*)hv && cxt->recur_depth > 0) {
3032 HvRITER_set(hv, riter); /* Restore hash iterator state */
3033 HvEITER_set(hv, eiter);
3038 static int store_hentry(pTHX_
3039 stcxt_t *cxt, HV* hv, UV i, HE *he, SV *val, unsigned char hash_flags)
3042 int flagged_hash = ((SvREADONLY(hv)
3043 #ifdef HAS_HASH_KEY_FLAGS
3047 /* Implementation of restricted hashes isn't nicely
3049 unsigned char flags = (((hash_flags & SHV_RESTRICTED)
3050 && SvTRULYREADONLY(val))
3051 ? SHV_K_LOCKED : 0);
3055 if (val == &PL_sv_placeholder) {
3056 flags |= SHV_K_PLACEHOLDER;
3061 * Store value first.
3064 TRACEME(("(#%d) value 0x%" UVxf, (int)i, PTR2UV(val)));
3067 HEK* hek = HeKEY_hek(he);
3068 I32 len = HEK_LEN(hek);
3072 if ((ret = store(aTHX_ cxt, val)))
3074 if (len == HEf_SVKEY) {
3075 /* This is somewhat sick, but the internal APIs are
3076 * such that XS code could put one of these in
3078 * Maybe we should be capable of storing one if
3081 key_sv = HeKEY_sv(he);
3082 flags |= SHV_K_ISSV;
3084 /* Regular string key. */
3085 #ifdef HAS_HASH_KEY_FLAGS
3087 flags |= SHV_K_UTF8;
3088 if (HEK_WASUTF8(hek))
3089 flags |= SHV_K_WASUTF8;
3095 * Keys are written after values to make sure retrieval
3096 * can be optimal in terms of memory usage, where keys are
3097 * read into a fixed unique buffer called kbuf.
3098 * See retrieve_hash() for details.
3103 TRACEME(("(#%d) key '%s' flags %x", (int)i, key, flags));
3105 /* This is a workaround for a bug in 5.8.0
3106 that causes the HEK_WASUTF8 flag to be
3107 set on an HEK without the hash being
3108 marked as having key flags. We just
3109 cross our fingers and drop the flag.
3111 assert (flags == 0 || flags == SHV_K_WASUTF8);
3112 TRACEME(("(#%d) key '%s'", (int)i, key));
3114 if (flags & SHV_K_ISSV) {
3115 if ((ret = store(aTHX_ cxt, key_sv)))
3131 * Store a overlong hash table, with >2G keys, which we cannot iterate
3132 * over with perl5. xhv_eiter is only I32 there. (only cperl can)
3133 * and we also do not want to sort it.
3134 * So we walk the buckets and chains manually.
3136 * type, len and flags are already written.
3139 static int store_lhash(pTHX_ stcxt_t *cxt, HV *hv, unsigned char hash_flags)
3147 UV len = (UV)HvTOTALKEYS(hv);
3149 SV * const recur_sv = cxt->recur_sv;
3151 TRACEME(("store_lhash (0x%" UVxf ") (flags %x)", PTR2UV(hv),
3154 TRACEME(("store_lhash (0x%" UVxf ")", PTR2UV(hv)));
3156 TRACEME(("size = %" UVuf ", used = %" UVuf, len, (UV)HvUSEDKEYS(hv)));
3158 TRACEME(("recur_depth %" IVdf ", recur_sv (0x%" UVxf ")", cxt->recur_depth,
3159 PTR2UV(cxt->recur_sv)));
3160 if (recur_sv != (SV*)hv && cxt->max_recur_depth_hash != -1) {
3163 if (RECURSION_TOO_DEEP_HASH()) {
3164 #if PERL_VERSION_LT(5,15,0)
3165 cleanup_recursive_data(aTHX_ (SV*)hv);
3167 CROAK((MAX_DEPTH_ERROR));
3170 array = HvARRAY(hv);
3171 for (i = 0; i <= (Size_t)HvMAX(hv); i++) {
3172 HE* entry = array[i];
3175 SV* val = hv_iterval(hv, entry);
3176 if ((ret = store_hentry(aTHX_ cxt, hv, ix++, entry, val, hash_flags)))
3178 entry = HeNEXT(entry);
3181 if (recur_sv != (SV*)hv && cxt->max_recur_depth_hash != -1 && cxt->recur_depth > 0) {
3182 TRACEME(("recur_depth --%" IVdf, cxt->recur_depth));
3193 * Store a code reference.
3195 * Layout is SX_CODE <length> followed by a scalar containing the perl
3196 * source code of the code reference.
3198 static int store_code(pTHX_ stcxt_t *cxt, CV *cv)
3202 STRLEN count, reallen;
3203 SV *text, *bdeparse;
3205 TRACEME(("store_code (0x%" UVxf ")", PTR2UV(cv)));
3208 cxt->deparse == 0 ||
3209 (cxt->deparse < 0 &&
3211 SvTRUE(get_sv("Storable::Deparse", GV_ADD)) ? 1 : 0))
3213 return store_other(aTHX_ cxt, (SV*)cv);
3217 * Require B::Deparse. At least B::Deparse 0.61 is needed for
3218 * blessed code references.
3220 /* Ownership of both SVs is passed to load_module, which frees them. */
3221 load_module(PERL_LOADMOD_NOIMPORT, newSVpvs("B::Deparse"), newSVnv(0.61));
3228 * create the B::Deparse object
3232 XPUSHs(newSVpvs_flags("B::Deparse", SVs_TEMP));
3234 count = call_method("new", G_SCALAR);
3237 CROAK(("Unexpected return value from B::Deparse::new\n"));
3241 * call the coderef2text method
3245 XPUSHs(bdeparse); /* XXX is this already mortal? */
3246 XPUSHs(sv_2mortal(newRV_inc((SV*)cv)));
3248 count = call_method("coderef2text", G_SCALAR);
3251 CROAK(("Unexpected return value from B::Deparse::coderef2text\n"));
3255 reallen = strlen(SvPV_nolen(text));
3258 * Empty code references or XS functions are deparsed as
3259 * "(prototype) ;" or ";".
3262 if (len == 0 || *(SvPV_nolen(text)+reallen-1) == ';') {
3263 CROAK(("The result of B::Deparse::coderef2text was empty - maybe you're trying to serialize an XS function?\n"));
3267 * Signal code by emitting SX_CODE.
3271 cxt->tagnum++; /* necessary, as SX_CODE is a SEEN() candidate */
3272 TRACEME(("size = %d", (int)len));
3273 TRACEME(("code = %s", SvPV_nolen(text)));
3276 * Now store the source code.
3280 STORE_UTF8STR(SvPV_nolen(text), len);
3282 STORE_SCALAR(SvPV_nolen(text), len);
3287 TRACEME(("ok (code)"));
3292 #if PERL_VERSION_LT(5,8,0)
3293 # define PERL_MAGIC_qr 'r' /* precompiled qr// regex */
3294 # define BFD_Svs_SMG_OR_RMG SVs_RMG
3295 #elif PERL_VERSION_GE(5,8,1)
3296 # define BFD_Svs_SMG_OR_RMG SVs_SMG
3297 # define MY_PLACEHOLDER PL_sv_placeholder
3299 # define BFD_Svs_SMG_OR_RMG SVs_RMG
3300 # define MY_PLACEHOLDER PL_sv_undef
3303 static int get_regexp(pTHX_ stcxt_t *cxt, SV* sv, SV **re, SV **flags) {
3306 #if PERL_VERSION_GE(5,12,0)
3307 CV *cv = get_cv("re::regexp_pattern", 0);
3309 CV *cv = get_cv("Storable::_regexp_pattern", 0);
3317 rv = sv_2mortal((SV*)newRV_inc(sv));
3321 /* optimize to call the XS directly later */
3322 count = call_sv((SV*)cv, G_ARRAY);
3325 CROAK(("re::regexp_pattern returned only %d results", (int)count));
3327 SvREFCNT_inc(*flags);
3338 static int store_regexp(pTHX_ stcxt_t *cxt, SV *sv) {
3342 const char *flags_pv;
3347 if (!get_regexp(aTHX_ cxt, sv, &re, &flags))
3350 re_pv = SvPV(re, re_len);
3351 flags_pv = SvPV(flags, flags_len);
3353 if (re_len > 0xFF) {
3354 op_flags |= SHR_U32_RE_LEN;
3359 if (op_flags & SHR_U32_RE_LEN) {
3360 U32 re_len32 = re_len;
3365 WRITE(re_pv, re_len);
3367 WRITE(flags_pv, flags_len);
3375 * When storing a tied object (be it a tied scalar, array or hash), we lay out
3376 * a special mark, followed by the underlying tied object. For instance, when
3377 * dealing with a tied hash, we store SX_TIED_HASH <hash object>, where
3378 * <hash object> stands for the serialization of the tied hash.
3380 static int store_tied(pTHX_ stcxt_t *cxt, SV *sv)
3385 int svt = SvTYPE(sv);
3388 TRACEME(("store_tied (0x%" UVxf ")", PTR2UV(sv)));
3391 * We have a small run-time penalty here because we chose to factorise
3392 * all tieds objects into the same routine, and not have a store_tied_hash,
3393 * a store_tied_array, etc...
3395 * Don't use a switch() statement, as most compilers don't optimize that
3396 * well for 2/3 values. An if() else if() cascade is just fine. We put
3397 * tied hashes first, as they are the most likely beasts.
3400 if (svt == SVt_PVHV) {
3401 TRACEME(("tied hash"));
3402 PUTMARK(SX_TIED_HASH); /* Introduces tied hash */
3403 } else if (svt == SVt_PVAV) {
3404 TRACEME(("tied array"));
3405 PUTMARK(SX_TIED_ARRAY); /* Introduces tied array */
3407 TRACEME(("tied scalar"));
3408 PUTMARK(SX_TIED_SCALAR); /* Introduces tied scalar */
3412 if (!(mg = mg_find(sv, mtype)))
3413 CROAK(("No magic '%c' found while storing tied %s", mtype,
3414 (svt == SVt_PVHV) ? "hash" :
3415 (svt == SVt_PVAV) ? "array" : "scalar"));
3418 * The mg->mg_obj found by mg_find() above actually points to the
3419 * underlying tied Perl object implementation. For instance, if the
3420 * original SV was that of a tied array, then mg->mg_obj is an AV.
3422 * Note that we store the Perl object as-is. We don't call its FETCH
3423 * method along the way. At retrieval time, we won't call its STORE
3424 * method either, but the tieing magic will be re-installed. In itself,
3425 * that ensures that the tieing semantics are preserved since further
3426 * accesses on the retrieved object will indeed call the magic methods...
3429 /* [#17040] mg_obj is NULL for scalar self-ties. AMS 20030416 */
3430 obj = mg->mg_obj ? mg->mg_obj : newSV(0);
3431 if ((ret = store(aTHX_ cxt, obj)))
3434 TRACEME(("ok (tied)"));
3442 * Stores a reference to an item within a tied structure:
3444 * . \$h{key}, stores both the (tied %h) object and 'key'.
3445 * . \$a[idx], stores both the (tied @a) object and 'idx'.
3447 * Layout is therefore either:
3448 * SX_TIED_KEY <object> <key>
3449 * SX_TIED_IDX <object> <index>
3451 static int store_tied_item(pTHX_ stcxt_t *cxt, SV *sv)
3456 TRACEME(("store_tied_item (0x%" UVxf ")", PTR2UV(sv)));
3458 if (!(mg = mg_find(sv, 'p')))
3459 CROAK(("No magic 'p' found while storing reference to tied item"));
3462 * We discriminate between \$h{key} and \$a[idx] via mg_ptr.
3466 TRACEME(("store_tied_item: storing a ref to a tied hash item"));
3467 PUTMARK(SX_TIED_KEY);
3468 TRACEME(("store_tied_item: storing OBJ 0x%" UVxf, PTR2UV(mg->mg_obj)));
3470 if ((ret = store(aTHX_ cxt, mg->mg_obj))) /* Extra () for -Wall, grr... */
3473 TRACEME(("store_tied_item: storing PTR 0x%" UVxf, PTR2UV(mg->mg_ptr)));
3475 if ((ret = store(aTHX_ cxt, (SV *) mg->mg_ptr))) /* Idem, for -Wall */
3478 I32 idx = mg->mg_len;
3480 TRACEME(("store_tied_item: storing a ref to a tied array item "));
3481 PUTMARK(SX_TIED_IDX);
3482 TRACEME(("store_tied_item: storing OBJ 0x%" UVxf, PTR2UV(mg->mg_obj)));
3484 if ((ret = store(aTHX_ cxt, mg->mg_obj))) /* Idem, for -Wall */
3487 TRACEME(("store_tied_item: storing IDX %d", (int)idx));
3492 TRACEME(("ok (tied item)"));
3498 * store_hook -- dispatched manually, not via sv_store[]
3500 * The blessed SV is serialized by a hook.
3504 * SX_HOOK <flags> <len> <classname> <len2> <str> [<len3> <object-IDs>]
3506 * where <flags> indicates how long <len>, <len2> and <len3> are, whether
3507 * the trailing part [] is present, the type of object (scalar, array or hash).
3508 * There is also a bit which says how the classname is stored between:
3513 * and when the <index> form is used (classname already seen), the "large
3514 * classname" bit in <flags> indicates how large the <index> is.
3516 * The serialized string returned by the hook is of length <len2> and comes
3517 * next. It is an opaque string for us.
3519 * Those <len3> object IDs which are listed last represent the extra references
3520 * not directly serialized by the hook, but which are linked to the object.
3522 * When recursion is mandated to resolve object-IDs not yet seen, we have
3523 * instead, with <header> being flags with bits set to indicate the object type
3524 * and that recursion was indeed needed:
3526 * SX_HOOK <header> <object> <header> <object> <flags>
3528 * that same header being repeated between serialized objects obtained through
3529 * recursion, until we reach flags indicating no recursion, at which point
3530 * we know we've resynchronized with a single layout, after <flags>.
3532 * When storing a blessed ref to a tied variable, the following format is
3535 * SX_HOOK <flags> <extra> ... [<len3> <object-IDs>] <magic object>
3537 * The first <flags> indication carries an object of type SHT_EXTRA, and the
3538 * real object type is held in the <extra> flag. At the very end of the
3539 * serialization stream, the underlying magic object is serialized, just like
3540 * any other tied variable.
3542 static int store_hook(
3556 IV count; /* really len3 + 1 */
3557 unsigned char flags;
3560 int recursed = 0; /* counts recursion */
3561 int obj_type; /* object type, on 2 bits */
3564 int clone = cxt->optype & ST_CLONE;
3565 char mtype = '\0'; /* for blessed ref to tied structures */
3566 unsigned char eflags = '\0'; /* used when object type is SHT_EXTRA */
3568 int need_large_oids = 0;
3571 TRACEME(("store_hook, classname \"%s\", tagged #%d", HvNAME_get(pkg), (int)cxt->tagnum));
3574 * Determine object type on 2 bits.
3580 obj_type = SHT_SCALAR;
3583 obj_type = SHT_ARRAY;
3586 obj_type = SHT_HASH;
3590 * Produced by a blessed ref to a tied data structure, $o in the
3591 * following Perl code.
3595 * my $o = bless \%h, 'BAR';
3597 * Signal the tie-ing magic by setting the object type as SHT_EXTRA
3598 * (since we have only 2 bits in <flags> to store the type), and an
3599 * <extra> byte flag will be emitted after the FIRST <flags> in the
3600 * stream, carrying what we put in 'eflags'.
3602 obj_type = SHT_EXTRA;
3603 switch (SvTYPE(sv)) {
3605 eflags = (unsigned char) SHT_THASH;
3609 eflags = (unsigned char) SHT_TARRAY;
3613 eflags = (unsigned char) SHT_TSCALAR;
3619 CROAK(("Unexpected object type (%d) in store_hook()", type));
3621 flags = SHF_NEED_RECURSE | obj_type;
3623 classname = HvNAME_get(pkg);
3624 len = strlen(classname);
3627 * To call the hook, we need to fake a call like:
3629 * $object->STORABLE_freeze($cloning);
3631 * but we don't have the $object here. For instance, if $object is
3632 * a blessed array, what we have in 'sv' is the array, and we can't
3633 * call a method on those.
3635 * Therefore, we need to create a temporary reference to the object and
3636 * make the call on that reference.
3639 TRACEME(("about to call STORABLE_freeze on class %s", classname));
3641 ref = newRV_inc(sv); /* Temporary reference */
3642 av = array_call(aTHX_ ref, hook, clone); /* @a = $object->STORABLE_freeze($c) */
3643 SvREFCNT_dec(ref); /* Reclaim temporary reference */
3645 count = AvFILLp(av) + 1;
3646 TRACEME(("store_hook, array holds %" IVdf " items", count));
3649 * If they return an empty list, it means they wish to ignore the
3650 * hook for this class (and not just this instance -- that's for them
3651 * to handle if they so wish).
3653 * Simply disable the cached entry for the hook (it won't be recomputed
3654 * since it's present in the cache) and recurse to store_blessed().
3658 /* free empty list returned by the hook */
3663 * They must not change their mind in the middle of a serialization.
3666 if (hv_fetch(cxt->hclass, classname, len, FALSE))
3667 CROAK(("Too late to ignore hooks for %s class \"%s\"",
3668 (cxt->optype & ST_CLONE) ? "cloning" : "storing",
3671 pkg_hide(aTHX_ cxt->hook, pkg, "STORABLE_freeze");
3673 ASSERT(!pkg_can(aTHX_ cxt->hook, pkg, "STORABLE_freeze"),
3674 ("hook invisible"));
3675 TRACEME(("ignoring STORABLE_freeze in class \"%s\"", classname));
3677 return store_blessed(aTHX_ cxt, sv, type, pkg);
3681 * Get frozen string.
3685 pv = SvPV(ary[0], len2);
3686 /* We can't use pkg_can here because it only caches one method per
3689 GV* gv = gv_fetchmethod_autoload(pkg, "STORABLE_attach", FALSE);
3690 if (gv && isGV(gv)) {
3692 CROAK(("Freeze cannot return references if %s class is using STORABLE_attach", classname));
3698 if (count > I32_MAX) {
3699 CROAK(("Too many references returned by STORABLE_freeze()"));
3704 * If they returned more than one item, we need to serialize some
3705 * extra references if not already done.
3707 * Loop over the array, starting at position #1, and for each item,
3708 * ensure it is a reference, serialize it if not already done, and
3709 * replace the entry with the tag ID of the corresponding serialized
3712 * We CHEAT by not calling av_fetch() and read directly within the
3716 for (i = 1; i < count; i++) {
3717 #ifdef USE_PTR_TABLE
3725 AV *av_hook = cxt->hook_seen;
3728 CROAK(("Item #%d returned by STORABLE_freeze "
3729 "for %s is not a reference", (int)i, classname));
3730 xsv = SvRV(rsv); /* Follow ref to know what to look for */
3733 * Look in hseen and see if we have a tag already.
3734 * Serialize entry if not done already, and get its tag.
3737 #ifdef USE_PTR_TABLE
3738 /* Fakery needed because ptr_table_fetch returns zero for a
3739 failure, whereas the existing code assumes that it can
3740 safely store a tag zero. So for ptr_tables we store tag+1
3742 if ((fake_tag = (char *)ptr_table_fetch(cxt->pseen, xsv)))
3743 goto sv_seen; /* Avoid moving code too far to the right */
3745 if ((svh = hv_fetch(cxt->hseen, (char *) &xsv, sizeof(xsv), FALSE)))
3746 goto sv_seen; /* Avoid moving code too far to the right */
3749 TRACEME(("listed object %d at 0x%" UVxf " is unknown", i-1,
3753 * We need to recurse to store that object and get it to be known
3754 * so that we can resolve the list of object-IDs at retrieve time.
3756 * The first time we do this, we need to emit the proper header
3757 * indicating that we recursed, and what the type of object is (the
3758 * object we're storing via a user-hook). Indeed, during retrieval,
3759 * we'll have to create the object before recursing to retrieve the
3760 * others, in case those would point back at that object.
3763 /* [SX_HOOK] <flags> [<extra>] <object>*/
3766 if (len2 > INT32_MAX)
3767 PUTMARK(SX_LOBJECT);
3771 if (obj_type == SHT_EXTRA)
3776 if ((ret = store(aTHX_ cxt, xsv))) /* Given by hook for us to store */
3779 #ifdef USE_PTR_TABLE
3780 fake_tag = (char *)ptr_table_fetch(cxt->pseen, xsv);
3782 CROAK(("Could not serialize item #%d from hook in %s",
3783 (int)i, classname));
3785 svh = hv_fetch(cxt->hseen, (char *) &xsv, sizeof(xsv), FALSE);
3787 CROAK(("Could not serialize item #%d from hook in %s",
3788 (int)i, classname));
3791 * It was the first time we serialized 'xsv'.
3793 * Keep this SV alive until the end of the serialization: if we
3794 * disposed of it right now by decrementing its refcount, and it was
3795 * a temporary value, some next temporary value allocated during
3796 * another STORABLE_freeze might take its place, and we'd wrongly
3797 * assume that new SV was already serialized, based on its presence
3800 * Therefore, push it away in cxt->hook_seen.
3803 av_store(av_hook, AvFILLp(av_hook)+1, SvREFCNT_inc(xsv));
3807 * Dispose of the REF they returned. If we saved the 'xsv' away
3808 * in the array of returned SVs, that will not cause the underlying
3809 * referenced SV to be reclaimed.
3812 ASSERT(SvREFCNT(xsv) > 1, ("SV will survive disposal of its REF"));
3813 SvREFCNT_dec(rsv); /* Dispose of reference */
3816 * Replace entry with its tag (not a real SV, so no refcnt increment)
3819 #ifdef USE_PTR_TABLE
3820 tag = (SV *)--fake_tag;
3825 TRACEME(("listed object %d at 0x%" UVxf " is tag #%" UVuf,
3826 i-1, PTR2UV(xsv), PTR2UV(tag)));
3828 if ((U32)PTR2TAG(tag) != PTR2TAG(tag))
3829 need_large_oids = 1;
3834 * Allocate a class ID if not already done.
3836 * This needs to be done after the recursion above, since at retrieval
3837 * time, we'll see the inner objects first. Many thanks to
3838 * Salvador Ortiz Garcia <sog@msg.com.mx> who spot that bug and
3839 * proposed the right fix. -- RAM, 15/09/2000
3843 if (!known_class(aTHX_ cxt, classname, len, &classnum)) {
3844 TRACEME(("first time we see class %s, ID = %d", classname, (int)classnum));
3845 classnum = -1; /* Mark: we must store classname */
3847 TRACEME(("already seen class %s, ID = %d", classname, (int)classnum));
3851 * Compute leading flags.
3855 if (((classnum == -1) ? len : classnum) > LG_SCALAR)
3856 flags |= SHF_LARGE_CLASSLEN;
3858 flags |= SHF_IDX_CLASSNAME;
3859 if (len2 > LG_SCALAR)
3860 flags |= SHF_LARGE_STRLEN;
3862 flags |= SHF_HAS_LIST;
3863 if (count > (LG_SCALAR + 1))
3864 flags |= SHF_LARGE_LISTLEN;
3866 if (need_large_oids)
3867 flags |= SHF_LARGE_LISTLEN;
3871 * We're ready to emit either serialized form:
3873 * SX_HOOK <flags> <len> <classname> <len2> <str> [<len3> <object-IDs>]
3874 * SX_HOOK <flags> <index> <len2> <str> [<len3> <object-IDs>]
3876 * If we recursed, the SX_HOOK has already been emitted.
3879 TRACEME(("SX_HOOK (recursed=%d) flags=0x%x "
3880 "class=%" IVdf " len=%" IVdf " len2=%" IVdf " len3=%" IVdf,
3881 recursed, flags, (IV)classnum, (IV)len, (IV)len2, count-1));
3883 /* SX_HOOK <flags> [<extra>] */
3886 if (len2 > INT32_MAX)
3887 PUTMARK(SX_LOBJECT);
3891 if (obj_type == SHT_EXTRA)
3896 /* <len> <classname> or <index> */
3897 if (flags & SHF_IDX_CLASSNAME) {
3898 if (flags & SHF_LARGE_CLASSLEN)
3901 unsigned char cnum = (unsigned char) classnum;
3905 if (flags & SHF_LARGE_CLASSLEN)
3908 unsigned char clen = (unsigned char) len;
3911 WRITE(classname, len); /* Final \0 is omitted */
3914 /* <len2> <frozen-str> */
3916 if (len2 > INT32_MAX) {
3921 if (flags & SHF_LARGE_STRLEN) {
3922 U32 wlen2 = len2; /* STRLEN might be 8 bytes */
3923 WLEN(wlen2); /* Must write an I32 for 64-bit machines */
3925 unsigned char clen = (unsigned char) len2;
3929 WRITE(pv, (SSize_t)len2); /* Final \0 is omitted */
3931 /* [<len3> <object-IDs>] */
3932 if (flags & SHF_HAS_LIST) {
3933 int len3 = count - 1;
3934 if (flags & SHF_LARGE_LISTLEN) {
3936 int tlen3 = need_large_oids ? -len3 : len3;
3943 unsigned char clen = (unsigned char) len3;
3948 * NOTA BENE, for 64-bit machines: the ary[i] below does not yield a
3949 * real pointer, rather a tag number, well under the 32-bit limit.
3950 * Which is wrong... if we have more than 2**32 SVs we can get ids over
3954 for (i = 1; i < count; i++) {
3956 if (need_large_oids) {
3957 ntag_t tag = PTR2TAG(ary[i]);
3959 TRACEME(("object %d, tag #%" UVuf, i-1, (UV)tag));
3964 I32 tagval = htonl(LOW_32BITS(ary[i]));
3966 TRACEME(("object %d, tag #%d", i-1, ntohl(tagval)));
3972 * Free the array. We need extra care for indices after 0, since they
3973 * don't hold real SVs but integers cast.
3977 AvFILLp(av) = 0; /* Cheat, nothing after 0 interests us */
3982 * If object was tied, need to insert serialization of the magic object.
3985 if (obj_type == SHT_EXTRA) {
3988 if (!(mg = mg_find(sv, mtype))) {
3989 int svt = SvTYPE(sv);
3990 CROAK(("No magic '%c' found while storing ref to tied %s with hook",
3991 mtype, (svt == SVt_PVHV) ? "hash" :
3992 (svt == SVt_PVAV) ? "array" : "scalar"));
3995 TRACEME(("handling the magic object 0x%" UVxf " part of 0x%" UVxf,
3996 PTR2UV(mg->mg_obj), PTR2UV(sv)));
4001 if ((ret = store(aTHX_ cxt, mg->mg_obj)))
4009 * store_blessed -- dispatched manually, not via sv_store[]
4011 * Check whether there is a STORABLE_xxx hook defined in the class or in one
4012 * of its ancestors. If there is, then redispatch to store_hook();
4014 * Otherwise, the blessed SV is stored using the following layout:
4016 * SX_BLESS <flag> <len> <classname> <object>
4018 * where <flag> indicates whether <len> is stored on 0 or 4 bytes, depending
4019 * on the high-order bit in flag: if 1, then length follows on 4 bytes.
4020 * Otherwise, the low order bits give the length, thereby giving a compact
4021 * representation for class names less than 127 chars long.
4023 * Each <classname> seen is remembered and indexed, so that the next time
4024 * an object in the blessed in the same <classname> is stored, the following
4027 * SX_IX_BLESS <flag> <index> <object>
4029 * where <index> is the classname index, stored on 0 or 4 bytes depending
4030 * on the high-order bit in flag (same encoding as above for <len>).
4032 static int store_blessed(
4044 TRACEME(("store_blessed, type %d, class \"%s\"", type, HvNAME_get(pkg)));
4047 * Look for a hook for this blessed SV and redirect to store_hook()
4051 hook = pkg_can(aTHX_ cxt->hook, pkg, "STORABLE_freeze");
4053 return store_hook(aTHX_ cxt, sv, type, pkg, hook);
4056 * This is a blessed SV without any serialization hook.
4059 classname = HvNAME_get(pkg);
4060 len = strlen(classname);
4062 TRACEME(("blessed 0x%" UVxf " in %s, no hook: tagged #%d",
4063 PTR2UV(sv), classname, (int)cxt->tagnum));
4066 * Determine whether it is the first time we see that class name (in which
4067 * case it will be stored in the SX_BLESS form), or whether we already
4068 * saw that class name before (in which case the SX_IX_BLESS form will be
4072 if (known_class(aTHX_ cxt, classname, len, &classnum)) {
4073 TRACEME(("already seen class %s, ID = %d", classname, (int)classnum));
4074 PUTMARK(SX_IX_BLESS);
4075 if (classnum <= LG_BLESS) {
4076 unsigned char cnum = (unsigned char) classnum;
4079 unsigned char flag = (unsigned char) 0x80;
4084 TRACEME(("first time we see class %s, ID = %d", classname,
4087 if (len <= LG_BLESS) {
4088 unsigned char clen = (unsigned char) len;
4091 unsigned char flag = (unsigned char) 0x80;
4093 WLEN(len); /* Don't BER-encode, this should be rare */
4095 WRITE(classname, len); /* Final \0 is omitted */
4099 * Now emit the <object> part.
4102 return SV_STORE(type)(aTHX_ cxt, sv);
4108 * We don't know how to store the item we reached, so return an error condition.
4109 * (it's probably a GLOB, some CODE reference, etc...)
4111 * If they defined the 'forgive_me' variable at the Perl level to some
4112 * true value, then don't croak, just warn, and store a placeholder string
4115 static int store_other(pTHX_ stcxt_t *cxt, SV *sv)
4120 TRACEME(("store_other"));
4123 * Fetch the value from perl only once per store() operation.
4127 cxt->forgive_me == 0 ||
4128 (cxt->forgive_me < 0 &&
4129 !(cxt->forgive_me = SvTRUE
4130 (get_sv("Storable::forgive_me", GV_ADD)) ? 1 : 0))
4132 CROAK(("Can't store %s items", sv_reftype(sv, FALSE)));
4134 warn("Can't store item %s(0x%" UVxf ")",
4135 sv_reftype(sv, FALSE), PTR2UV(sv));
4138 * Store placeholder string as a scalar instead...
4141 (void) sprintf(buf, "You lost %s(0x%" UVxf ")%c", sv_reftype(sv, FALSE),
4142 PTR2UV(sv), (char) 0);
4146 STORE_SCALAR(buf, len);
4147 TRACEME(("ok (dummy \"%s\", length = %" IVdf ")", buf, (IV) len));
4153 *** Store driving routines
4159 * WARNING: partially duplicates Perl's sv_reftype for speed.
4161 * Returns the type of the SV, identified by an integer. That integer
4162 * may then be used to index the dynamic routine dispatch table.
4164 static int sv_type(pTHX_ SV *sv)
4166 switch (SvTYPE(sv)) {
4168 #if PERL_VERSION_LT(5,11,0)
4173 * No need to check for ROK, that can't be set here since there
4174 * is no field capable of hodling the xrv_rv reference.
4178 #if PERL_VERSION_LT(5,11,0)
4186 * Starting from SVt_PV, it is possible to have the ROK flag
4187 * set, the pointer to the other SV being either stored in
4188 * the xrv_rv (in the case of a pure SVt_RV), or as the
4189 * xpv_pv field of an SVt_PV and its heirs.
4191 * However, those SV cannot be magical or they would be an
4192 * SVt_PVMG at least.
4194 return SvROK(sv) ? svis_REF : svis_SCALAR;
4196 #if PERL_VERSION_LT(5,11,0)
4197 if ((SvFLAGS(sv) & (SVs_OBJECT|SVf_OK|SVs_GMG|SVs_SMG|SVs_RMG))
4198 == (SVs_OBJECT|BFD_Svs_SMG_OR_RMG)
4199 && mg_find(sv, PERL_MAGIC_qr)) {
4203 case SVt_PVLV: /* Workaround for perl5.004_04 "LVALUE" bug */
4204 if ((SvFLAGS(sv) & (SVs_GMG|SVs_SMG|SVs_RMG)) ==
4205 (SVs_GMG|SVs_SMG|SVs_RMG) &&
4207 return svis_TIED_ITEM;
4209 #if PERL_VERSION_LT(5,9,0)
4212 if ((SvFLAGS(sv) & (SVs_GMG|SVs_SMG|SVs_RMG)) ==
4213 (SVs_GMG|SVs_SMG|SVs_RMG) &&
4216 return SvROK(sv) ? svis_REF : svis_SCALAR;
4218 if (SvRMAGICAL(sv) && (mg_find(sv, 'P')))
4222 if (SvRMAGICAL(sv) && (mg_find(sv, 'P')))
4227 #if PERL_VERSION_GE(5,9,0)
4228 /* case SVt_INVLIST: */
4230 #if PERL_VERSION_GE(5,11,0)
4244 * Recursively store objects pointed to by the sv to the specified file.
4246 * Layout is <content> or SX_OBJECT <tagnum> if we reach an already stored
4247 * object (one for which storage has started -- it may not be over if we have
4248 * a self-referenced structure). This data set forms a stored <object>.
4250 static int store(pTHX_ stcxt_t *cxt, SV *sv)
4255 #ifdef USE_PTR_TABLE
4256 struct ptr_tbl *pseen = cxt->pseen;
4258 HV *hseen = cxt->hseen;
4261 TRACEME(("store (0x%" UVxf ")", PTR2UV(sv)));
4264 * If object has already been stored, do not duplicate data.
4265 * Simply emit the SX_OBJECT marker followed by its tag data.
4266 * The tag is always written in network order.
4268 * NOTA BENE, for 64-bit machines: the "*svh" below does not yield a
4269 * real pointer, rather a tag number (watch the insertion code below).
4270 * That means it probably safe to assume it is well under the 32-bit
4271 * limit, and makes the truncation safe.
4272 * -- RAM, 14/09/1999
4275 #ifdef USE_PTR_TABLE
4276 svh = (SV **)ptr_table_fetch(pseen, sv);
4278 svh = hv_fetch(hseen, (char *) &sv, sizeof(sv), FALSE);
4282 if (sv == &PL_sv_undef) {
4283 /* We have seen PL_sv_undef before, but fake it as
4286 Not the simplest solution to making restricted
4287 hashes work on 5.8.0, but it does mean that
4288 repeated references to the one true undef will
4289 take up less space in the output file.
4291 /* Need to jump past the next hv_store, because on the
4292 second store of undef the old hash value will be
4293 SvREFCNT_dec()ed, and as Storable cheats horribly
4294 by storing non-SVs in the hash a SEGV will ensure.
4295 Need to increase the tag number so that the
4296 receiver has no idea what games we're up to. This
4297 special casing doesn't affect hooks that store
4298 undef, as the hook routine does its own lookup into
4299 hseen. Also this means that any references back
4300 to PL_sv_undef (from the pathological case of hooks
4301 storing references to it) will find the seen hash
4302 entry for the first time, as if we didn't have this
4303 hackery here. (That hseen lookup works even on 5.8.0
4304 because it's a key of &PL_sv_undef and a value
4305 which is a tag number, not a value which is
4309 goto undef_special_case;
4312 #ifdef USE_PTR_TABLE
4313 tagval = PTR2TAG(((char *)svh)-1);
4315 tagval = PTR2TAG(*svh);
4319 /* older versions of Storable streat the tag as a signed value
4320 used in an array lookup, corrupting the data structure.
4321 Ensure only a newer Storable will be able to parse this tag id
4322 if it's over the 2G mark.
4324 if (tagval > I32_MAX) {
4326 TRACEME(("object 0x%" UVxf " seen as #%" UVuf, PTR2UV(sv),
4329 PUTMARK(SX_LOBJECT);
4339 ltagval = htonl((I32)tagval);
4341 TRACEME(("object 0x%" UVxf " seen as #%d", PTR2UV(sv),
4351 * Allocate a new tag and associate it with the address of the sv being
4352 * stored, before recursing...
4354 * In order to avoid creating new SvIVs to hold the tagnum we just
4355 * cast the tagnum to an SV pointer and store that in the hash. This
4356 * means that we must clean up the hash manually afterwards, but gives
4357 * us a 15% throughput increase.
4362 #ifdef USE_PTR_TABLE
4363 ptr_table_store(pseen, sv, INT2PTR(SV*, 1 + cxt->tagnum));
4365 if (!hv_store(hseen,
4366 (char *) &sv, sizeof(sv), INT2PTR(SV*, cxt->tagnum), 0))
4371 * Store 'sv' and everything beneath it, using appropriate routine.
4372 * Abort immediately if we get a non-zero status back.
4375 type = sv_type(aTHX_ sv);
4378 TRACEME(("storing 0x%" UVxf " tag #%d, type %d...",
4379 PTR2UV(sv), (int)cxt->tagnum, (int)type));
4382 HV *pkg = SvSTASH(sv);
4383 ret = store_blessed(aTHX_ cxt, sv, type, pkg);
4385 ret = SV_STORE(type)(aTHX_ cxt, sv);
4387 TRACEME(("%s (stored 0x%" UVxf ", refcnt=%d, %s)",
4388 ret ? "FAILED" : "ok", PTR2UV(sv),
4389 (int)SvREFCNT(sv), sv_reftype(sv, FALSE)));
4397 * Write magic number and system information into the file.
4398 * Layout is <magic> <network> [<len> <byteorder> <sizeof int> <sizeof long>
4399 * <sizeof ptr>] where <len> is the length of the byteorder hexa string.
4400 * All size and lengths are written as single characters here.
4402 * Note that no byte ordering info is emitted when <network> is true, since
4403 * integers will be emitted in network order in that case.
4405 static int magic_write(pTHX_ stcxt_t *cxt)
4408 * Starting with 0.6, the "use_network_order" byte flag is also used to
4409 * indicate the version number of the binary image, encoded in the upper
4410 * bits. The bit 0 is always used to indicate network order.
4413 * Starting with 0.7, a full byte is dedicated to the minor version of
4414 * the binary format, which is incremented only when new markers are
4415 * introduced, for instance, but when backward compatibility is preserved.
4418 /* Make these at compile time. The WRITE() macro is sufficiently complex
4419 that it saves about 200 bytes doing it this way and only using it
4421 static const unsigned char network_file_header[] = {
4423 (STORABLE_BIN_MAJOR << 1) | 1,
4424 STORABLE_BIN_WRITE_MINOR
4426 static const unsigned char file_header[] = {
4428 (STORABLE_BIN_MAJOR << 1) | 0,
4429 STORABLE_BIN_WRITE_MINOR,
4430 /* sizeof the array includes the 0 byte at the end: */
4431 (char) sizeof (byteorderstr) - 1,
4433 (unsigned char) sizeof(int),
4434 (unsigned char) sizeof(long),
4435 (unsigned char) sizeof(char *),
4436 (unsigned char) sizeof(NV)
4438 #ifdef USE_56_INTERWORK_KLUDGE
4439 static const unsigned char file_header_56[] = {
4441 (STORABLE_BIN_MAJOR << 1) | 0,
4442 STORABLE_BIN_WRITE_MINOR,
4443 /* sizeof the array includes the 0 byte at the end: */
4444 (char) sizeof (byteorderstr_56) - 1,
4446 (unsigned char) sizeof(int),
4447 (unsigned char) sizeof(long),
4448 (unsigned char) sizeof(char *),
4449 (unsigned char) sizeof(NV)
4452 const unsigned char *header;
4455 TRACEME(("magic_write on fd=%d", cxt->fio ? PerlIO_fileno(cxt->fio) : -1));
4457 if (cxt->netorder) {
4458 header = network_file_header;
4459 length = sizeof (network_file_header);
4461 #ifdef USE_56_INTERWORK_KLUDGE
4462 if (SvTRUE(get_sv("Storable::interwork_56_64bit", GV_ADD))) {
4463 header = file_header_56;
4464 length = sizeof (file_header_56);
4468 header = file_header;
4469 length = sizeof (file_header);
4474 /* sizeof the array includes the 0 byte at the end. */
4475 header += sizeof (magicstr) - 1;
4476 length -= sizeof (magicstr) - 1;
4479 WRITE( (unsigned char*) header, length);
4481 if (!cxt->netorder) {
4482 TRACEME(("ok (magic_write byteorder = 0x%lx [%d], I%d L%d P%d D%d)",
4483 (unsigned long) BYTEORDER, (int) sizeof (byteorderstr) - 1,
4484 (int) sizeof(int), (int) sizeof(long),
4485 (int) sizeof(char *), (int) sizeof(NV)));
4493 * Common code for store operations.
4495 * When memory store is requested (f = NULL) and a non null SV* is given in
4496 * 'res', it is filled with a new SV created out of the memory buffer.
4498 * It is required to provide a non-null 'res' when the operation type is not
4499 * dclone() and store() is performed to memory.
4501 static int do_store(pTHX_
4511 ASSERT(!(f == 0 && !(optype & ST_CLONE)) || res,
4512 ("must supply result SV pointer for real recursion to memory"));
4514 TRACEMED(("do_store (optype=%d, netorder=%d)",
4515 optype, network_order));
4520 * Workaround for CROAK leak: if they enter with a "dirty" context,
4521 * free up memory for them now.
4526 clean_context(aTHX_ cxt);
4529 * Now that STORABLE_xxx hooks exist, it is possible that they try to
4530 * re-enter store() via the hooks. We need to stack contexts.
4534 cxt = allocate_context(aTHX_ cxt);
4540 ASSERT(cxt->entry == 1, ("starting new recursion"));
4541 ASSERT(!cxt->s_dirty, ("clean context"));
4544 * Ensure sv is actually a reference. From perl, we called something
4546 * pstore(aTHX_ FILE, \@array);
4547 * so we must get the scalar value behind that reference.
4551 CROAK(("Not a reference"));
4552 sv = SvRV(sv); /* So follow it to know what to store */
4555 * If we're going to store to memory, reset the buffer.
4562 * Prepare context and emit headers.
4565 init_store_context(aTHX_ cxt, f, optype, network_order);
4567 if (-1 == magic_write(aTHX_ cxt)) /* Emit magic and ILP info */
4568 return 0; /* Error */
4571 * Recursively store object...
4574 ASSERT(is_storing(aTHX), ("within store operation"));
4576 status = store(aTHX_ cxt, sv); /* Just do it! */
4579 * If they asked for a memory store and they provided an SV pointer,
4580 * make an SV string out of the buffer and fill their pointer.
4582 * When asking for ST_REAL, it's MANDATORY for the caller to provide
4583 * an SV, since context cleanup might free the buffer if we did recurse.
4584 * (unless caller is dclone(), which is aware of that).
4587 if (!cxt->fio && res)
4588 *res = mbuf2sv(aTHX);
4590 TRACEME(("do_store returns %d", status));
4595 * The "root" context is never freed, since it is meant to be always
4596 * handy for the common case where no recursion occurs at all (i.e.
4597 * we enter store() outside of any Storable code and leave it, period).
4598 * We know it's the "root" context because there's nothing stacked
4603 * When deep cloning, we don't free the context: doing so would force
4604 * us to copy the data in the memory buffer. Sicne we know we're
4605 * about to enter do_retrieve...
4608 clean_store_context(aTHX_ cxt);
4609 if (cxt->prev && !(cxt->optype & ST_CLONE))
4610 free_context(aTHX_ cxt);
4622 * Build a new SV out of the content of the internal memory buffer.
4624 static SV *mbuf2sv(pTHX)
4629 return newSVpv(mbase, MBUF_SIZE());
4633 *** Specific retrieve callbacks.
4639 * Return an error via croak, since it is not possible that we get here
4640 * under normal conditions, when facing a file produced via pstore().
4642 static SV *retrieve_other(pTHX_ stcxt_t *cxt, const char *cname)
4644 PERL_UNUSED_ARG(cname);
4646 cxt->ver_major != STORABLE_BIN_MAJOR &&
4647 cxt->ver_minor != STORABLE_BIN_MINOR
4649 CROAK(("Corrupted storable %s (binary v%d.%d), current is v%d.%d",
4650 cxt->fio ? "file" : "string",
4651 cxt->ver_major, cxt->ver_minor,
4652 STORABLE_BIN_MAJOR, STORABLE_BIN_MINOR));
4654 CROAK(("Corrupted storable %s (binary v%d.%d)",
4655 cxt->fio ? "file" : "string",
4656 cxt->ver_major, cxt->ver_minor));
4659 return (SV *) 0; /* Just in case */
4663 * retrieve_idx_blessed
4665 * Layout is SX_IX_BLESS <index> <object> with SX_IX_BLESS already read.
4666 * <index> can be coded on either 1 or 5 bytes.
4668 static SV *retrieve_idx_blessed(pTHX_ stcxt_t *cxt, const char *cname)
4671 const char *classname;
4675 PERL_UNUSED_ARG(cname);
4676 TRACEME(("retrieve_idx_blessed (#%d)", (int)cxt->tagnum));
4677 ASSERT(!cname, ("no bless-into class given here, got %s", cname));
4679 GETMARK(idx); /* Index coded on a single char? */
4684 * Fetch classname in 'aclass'
4687 sva = av_fetch(cxt->aclass, idx, FALSE);
4689 CROAK(("Class name #%" IVdf " should have been seen already",
4692 classname = SvPVX(*sva); /* We know it's a PV, by construction */
4694 TRACEME(("class ID %d => %s", (int)idx, classname));
4697 * Retrieve object and bless it.
4700 sv = retrieve(aTHX_ cxt, classname); /* First SV which is SEEN
4709 * Layout is SX_BLESS <len> <classname> <object> with SX_BLESS already read.
4710 * <len> can be coded on either 1 or 5 bytes.
4712 static SV *retrieve_blessed(pTHX_ stcxt_t *cxt, const char *cname)
4716 char buf[LG_BLESS + 1]; /* Avoid malloc() if possible */
4717 char *classname = buf;
4718 char *malloced_classname = NULL;
4720 PERL_UNUSED_ARG(cname);
4721 TRACEME(("retrieve_blessed (#%d)", (int)cxt->tagnum));
4722 ASSERT(!cname, ("no bless-into class given here, got %s", cname));
4725 * Decode class name length and read that name.
4727 * Short classnames have two advantages: their length is stored on one
4728 * single byte, and the string can be read on the stack.
4731 GETMARK(len); /* Length coded on a single char? */
4734 TRACEME(("** allocating %ld bytes for class name", (long)len+1));
4736 CROAK(("Corrupted classname length %lu", (long)len));
4737 PL_nomemok = TRUE; /* handle error by ourselves */
4738 New(10003, classname, len+1, char);
4741 CROAK(("Out of memory with len %ld", (long)len));
4743 malloced_classname = classname;
4745 SAFEPVREAD(classname, (I32)len, malloced_classname);
4746 classname[len] = '\0'; /* Mark string end */
4749 * It's a new classname, otherwise it would have been an SX_IX_BLESS.
4752 TRACEME(("new class name \"%s\" will bear ID = %d", classname,
4753 (int)cxt->classnum));
4755 if (!av_store(cxt->aclass, cxt->classnum++, newSVpvn(classname, len))) {
4756 Safefree(malloced_classname);
4761 * Retrieve object and bless it.
4764 sv = retrieve(aTHX_ cxt, classname); /* First SV which is SEEN will be blessed */
4765 if (malloced_classname)
4766 Safefree(malloced_classname);
4774 * Layout: SX_HOOK <flags> <len> <classname> <len2> <str> [<len3> <object-IDs>]
4775 * with leading mark already read, as usual.
4777 * When recursion was involved during serialization of the object, there
4778 * is an unknown amount of serialized objects after the SX_HOOK mark. Until
4779 * we reach a <flags> marker with the recursion bit cleared.
4781 * If the first <flags> byte contains a type of SHT_EXTRA, then the real type
4782 * is held in the <extra> byte, and if the object is tied, the serialized
4783 * magic object comes at the very end:
4785 * SX_HOOK <flags> <extra> ... [<len3> <object-IDs>] <magic object>
4787 * This means the STORABLE_thaw hook will NOT get a tied variable during its
4788 * processing (since we won't have seen the magic object by the time the hook
4789 * is called). See comments below for why it was done that way.
4791 static SV *retrieve_hook_common(pTHX_ stcxt_t *cxt, const char *cname, int large)
4794 char buf[LG_BLESS + 1]; /* Avoid malloc() if possible */
4795 char *classname = buf;
4807 int clone = cxt->optype & ST_CLONE;
4809 unsigned int extra_type = 0;
4811 int has_large_oids = 0;
4814 PERL_UNUSED_ARG(cname);
4815 TRACEME(("retrieve_hook (#%d)", (int)cxt->tagnum));
4816 ASSERT(!cname, ("no bless-into class given here, got %s", cname));
4820 PERL_UNUSED_ARG(large);
4824 * Read flags, which tell us about the type, and whether we need
4831 * Create the (empty) object, and mark it as seen.
4833 * This must be done now, because tags are incremented, and during
4834 * serialization, the object tag was affected before recursion could
4838 obj_type = flags & SHF_TYPE_MASK;
4844 sv = (SV *) newAV();
4847 sv = (SV *) newHV();
4851 * Read <extra> flag to know the type of the object.
4852 * Record associated magic type for later.
4854 GETMARK(extra_type);
4855 switch (extra_type) {
4861 sv = (SV *) newAV();
4865 sv = (SV *) newHV();
4869 return retrieve_other(aTHX_ cxt, 0);/* Let it croak */
4873 return retrieve_other(aTHX_ cxt, 0); /* Let it croak */
4875 SEEN0_NN(sv, 0); /* Don't bless yet */
4878 * Whilst flags tell us to recurse, do so.
4880 * We don't need to remember the addresses returned by retrieval, because
4881 * all the references will be obtained through indirection via the object
4882 * tags in the object-ID list.
4884 * We need to decrement the reference count for these objects
4885 * because, if the user doesn't save a reference to them in the hook,
4886 * they must be freed when this context is cleaned.
4889 while (flags & SHF_NEED_RECURSE) {
4890 TRACEME(("retrieve_hook recursing..."));
4891 rv = retrieve(aTHX_ cxt, 0);
4895 TRACEME(("retrieve_hook back with rv=0x%" UVxf,
4900 if (flags & SHF_IDX_CLASSNAME) {
4905 * Fetch index from 'aclass'
4908 if (flags & SHF_LARGE_CLASSLEN)
4913 sva = av_fetch(cxt->aclass, idx, FALSE);
4915 CROAK(("Class name #%" IVdf " should have been seen already",
4918 classname = SvPVX(*sva); /* We know it's a PV, by construction */
4919 TRACEME(("class ID %d => %s", (int)idx, classname));
4923 * Decode class name length and read that name.
4925 * NOTA BENE: even if the length is stored on one byte, we don't read
4926 * on the stack. Just like retrieve_blessed(), we limit the name to
4927 * LG_BLESS bytes. This is an arbitrary decision.
4929 char *malloced_classname = NULL;
4931 if (flags & SHF_LARGE_CLASSLEN)
4936 TRACEME(("** allocating %ld bytes for class name", (long)len+1));
4937 if (len > I32_MAX) /* security */
4938 CROAK(("Corrupted classname length %lu", (long)len));
4939 else if (len > LG_BLESS) { /* security: signed len */
4940 PL_nomemok = TRUE; /* handle error by ourselves */
4941 New(10003, classname, len+1, char);
4944 CROAK(("Out of memory with len %u", (unsigned)len+1));
4945 malloced_classname = classname;
4948 SAFEPVREAD(classname, (I32)len, malloced_classname);
4949 classname[len] = '\0'; /* Mark string end */
4952 * Record new classname.
4955 if (!av_store(cxt->aclass, cxt->classnum++,
4956 newSVpvn(classname, len))) {
4957 Safefree(malloced_classname);
4962 TRACEME(("class name: %s", classname));
4965 * Decode user-frozen string length and read it in an SV.
4967 * For efficiency reasons, we read data directly into the SV buffer.
4968 * To understand that code, read retrieve_scalar()
4977 if (flags & SHF_LARGE_STRLEN) {
4985 frozen = NEWSV(10002, len2 ? len2 : 1);
4987 SAFEREAD(SvPVX(frozen), len2, frozen);
4989 SvCUR_set(frozen, len2);
4990 *SvEND(frozen) = '\0';
4991 (void) SvPOK_only(frozen); /* Validates string pointer */
4992 if (cxt->s_tainted) /* Is input source tainted? */
4995 TRACEME(("frozen string: %d bytes", (int)len2));
4998 * Decode object-ID list length, if present.
5001 if (flags & SHF_HAS_LIST) {
5002 if (flags & SHF_LARGE_LISTLEN) {
5009 CROAK(("Large object ids in hook data not supported on 32-bit platforms"));
5018 av_extend(av, len3 + 1); /* Leave room for [0] */
5019 AvFILLp(av) = len3; /* About to be filled anyway */
5023 TRACEME(("has %d object IDs to link", (int)len3));
5026 * Read object-ID list into array.
5027 * Because we pre-extended it, we can cheat and fill it manually.
5029 * We read object tags and we can convert them into SV* on the fly
5030 * because we know all the references listed in there (as tags)
5031 * have been already serialized, hence we have a valid correspondence
5032 * between each of those tags and the recreated SV.
5036 SV **ary = AvARRAY(av);
5038 for (i = 1; i <= len3; i++) { /* We leave [0] alone */
5044 if (has_large_oids) {
5057 svh = av_fetch(cxt->aseen, tag, FALSE);
5059 if (tag == cxt->where_is_undef) {
5060 /* av_fetch uses PL_sv_undef internally, hence this
5061 somewhat gruesome hack. */
5065 CROAK(("Object #%" IVdf
5066 " should have been retrieved already",
5071 ary[i] = SvREFCNT_inc(xsv);
5076 * Look up the STORABLE_attach hook
5077 * If blessing is disabled, just return what we've got.
5079 if (!(cxt->flags & FLAG_BLESS_OK)) {
5080 TRACEME(("skipping bless because flags is %d", cxt->flags));
5085 * Bless the object and look up the STORABLE_thaw hook.
5087 stash = gv_stashpv(classname, GV_ADD);
5089 /* Handle attach case; again can't use pkg_can because it only
5090 * caches one method */
5091 attach = gv_fetchmethod_autoload(stash, "STORABLE_attach", FALSE);
5092 if (attach && isGV(attach)) {
5094 SV* attach_hook = newRV_inc((SV*) GvCV(attach));
5097 CROAK(("STORABLE_attach called with unexpected references"));
5101 AvARRAY(av)[0] = SvREFCNT_inc(frozen);
5102 rv = newSVpv(classname, 0);
5103 attached = scalar_call(aTHX_ rv, attach_hook, clone, av, G_SCALAR);
5104 /* Free memory after a call */
5106 SvREFCNT_dec(frozen);
5109 SvREFCNT_dec(attach_hook);
5112 sv_derived_from(attached, classname)
5115 /* refcnt of unneeded sv is 2 at this point
5116 (one from newHV, second from SEEN call) */
5119 /* we need to free RV but preserve value that RV point to */
5120 sv = SvRV(attached);
5122 SvRV_set(attached, NULL);
5123 SvREFCNT_dec(attached);
5124 if (!(flags & SHF_IDX_CLASSNAME) && classname != buf)
5125 Safefree(classname);
5128 CROAK(("STORABLE_attach did not return a %s object", classname));
5132 * Bless the object and look up the STORABLE_thaw hook.
5137 hook = pkg_can(aTHX_ cxt->hook, stash, "STORABLE_thaw");
5140 * Hook not found. Maybe they did not require the module where this
5141 * hook is defined yet?
5143 * If the load below succeeds, we'll be able to find the hook.
5144 * Still, it only works reliably when each class is defined in a
5148 TRACEME(("No STORABLE_thaw defined for objects of class %s", classname));
5149 TRACEME(("Going to load module '%s'", classname));
5150 load_module(PERL_LOADMOD_NOIMPORT, newSVpv(classname, 0), Nullsv);
5153 * We cache results of pkg_can, so we need to uncache before attempting
5157 pkg_uncache(aTHX_ cxt->hook, SvSTASH(sv), "STORABLE_thaw");
5158 hook = pkg_can(aTHX_ cxt->hook, SvSTASH(sv), "STORABLE_thaw");
5161 CROAK(("No STORABLE_thaw defined for objects of class %s "
5162 "(even after a \"require %s;\")", classname, classname));
5166 * If we don't have an 'av' yet, prepare one.
5167 * Then insert the frozen string as item [0].
5175 AvARRAY(av)[0] = SvREFCNT_inc(frozen);
5180 * $object->STORABLE_thaw($cloning, $frozen, @refs);
5182 * where $object is our blessed (empty) object, $cloning is a boolean
5183 * telling whether we're running a deep clone, $frozen is the frozen
5184 * string the user gave us in his serializing hook, and @refs, which may
5185 * be empty, is the list of extra references he returned along for us
5188 * In effect, the hook is an alternate creation routine for the class,
5189 * the object itself being already created by the runtime.
5192 TRACEME(("calling STORABLE_thaw on %s at 0x%" UVxf " (%" IVdf " args)",
5193 classname, PTR2UV(sv), (IV) AvFILLp(av) + 1));
5196 (void) scalar_call(aTHX_ rv, hook, clone, av, G_SCALAR|G_DISCARD);
5203 SvREFCNT_dec(frozen);
5206 if (!(flags & SHF_IDX_CLASSNAME) && classname != buf)
5207 Safefree(classname);
5210 * If we had an <extra> type, then the object was not as simple, and
5211 * we need to restore extra magic now.
5217 TRACEME(("retrieving magic object for 0x%" UVxf "...", PTR2UV(sv)));
5219 rv = retrieve(aTHX_ cxt, 0); /* Retrieve <magic object> */
5221 TRACEME(("restoring the magic object 0x%" UVxf " part of 0x%" UVxf,
5222 PTR2UV(rv), PTR2UV(sv)));
5224 switch (extra_type) {
5226 sv_upgrade(sv, SVt_PVMG);
5229 sv_upgrade(sv, SVt_PVAV);
5230 AvREAL_off((AV *)sv);
5233 sv_upgrade(sv, SVt_PVHV);
5236 CROAK(("Forgot to deal with extra type %d", extra_type));
5241 * Adding the magic only now, well after the STORABLE_thaw hook was called
5242 * means the hook cannot know it deals with an object whose variable is
5243 * tied. But this is happening when retrieving $o in the following case:
5247 * my $o = bless \%h, 'BAR';
5249 * The 'BAR' class is NOT the one where %h is tied into. Therefore, as
5250 * far as the 'BAR' class is concerned, the fact that %h is not a REAL
5251 * hash but a tied one should not matter at all, and remain transparent.
5252 * This means the magic must be restored by Storable AFTER the hook is
5255 * That looks very reasonable to me, but then I've come up with this
5256 * after a bug report from David Nesting, who was trying to store such
5257 * an object and caused Storable to fail. And unfortunately, it was
5258 * also the easiest way to retrofit support for blessed ref to tied objects
5259 * into the existing design. -- RAM, 17/02/2001
5262 sv_magic(sv, rv, mtype, (char *)NULL, 0);
5263 SvREFCNT_dec(rv); /* Undo refcnt inc from sv_magic() */
5268 static SV *retrieve_hook(pTHX_ stcxt_t *cxt, const char *cname) {
5269 return retrieve_hook_common(aTHX_ cxt, cname, FALSE);
5275 * Retrieve reference to some other scalar.
5276 * Layout is SX_REF <object>, with SX_REF already read.
5278 static SV *retrieve_ref(pTHX_ stcxt_t *cxt, const char *cname)
5284 TRACEME(("retrieve_ref (#%d)", (int)cxt->tagnum));
5287 * We need to create the SV that holds the reference to the yet-to-retrieve
5288 * object now, so that we may record the address in the seen table.
5289 * Otherwise, if the object to retrieve references us, we won't be able
5290 * to resolve the SX_OBJECT we'll see at that point! Hence we cannot
5291 * do the retrieve first and use rv = newRV(sv) since it will be too late
5292 * for SEEN() recording.
5295 rv = NEWSV(10002, 0);
5297 stash = gv_stashpv(cname, GV_ADD);
5300 SEEN_NN(rv, stash, 0); /* Will return if rv is null */
5301 sv = retrieve(aTHX_ cxt, 0);/* Retrieve <object> */
5303 return (SV *) 0; /* Failed */
5306 * WARNING: breaks RV encapsulation.
5308 * Now for the tricky part. We have to upgrade our existing SV, so that
5309 * it is now an RV on sv... Again, we cheat by duplicating the code
5310 * held in newSVrv(), since we already got our SV from retrieve().
5314 * SvRV(rv) = SvREFCNT_inc(sv);
5316 * here because the reference count we got from retrieve() above is
5317 * already correct: if the object was retrieved from the file, then
5318 * its reference count is one. Otherwise, if it was retrieved via
5319 * an SX_OBJECT indication, a ref count increment was done.
5323 /* No need to do anything, as rv will already be PVMG. */
5324 assert (SvTYPE(rv) == SVt_RV || SvTYPE(rv) >= SVt_PV);
5326 sv_upgrade(rv, SVt_RV);
5329 SvRV_set(rv, sv); /* $rv = \$sv */
5331 /*if (cxt->entry && ++cxt->ref_cnt > MAX_REF_CNT) {
5332 CROAK(("Max. recursion depth with nested refs exceeded"));
5335 TRACEME(("ok (retrieve_ref at 0x%" UVxf ")", PTR2UV(rv)));
5343 * Retrieve weak reference to some other scalar.
5344 * Layout is SX_WEAKREF <object>, with SX_WEAKREF already read.
5346 static SV *retrieve_weakref(pTHX_ stcxt_t *cxt, const char *cname)
5350 TRACEME(("retrieve_weakref (#%d)", (int)cxt->tagnum));
5352 sv = retrieve_ref(aTHX_ cxt, cname);
5364 * retrieve_overloaded
5366 * Retrieve reference to some other scalar with overloading.
5367 * Layout is SX_OVERLOAD <object>, with SX_OVERLOAD already read.
5369 static SV *retrieve_overloaded(pTHX_ stcxt_t *cxt, const char *cname)
5375 TRACEME(("retrieve_overloaded (#%d)", (int)cxt->tagnum));
5378 * Same code as retrieve_ref(), duplicated to avoid extra call.
5381 rv = NEWSV(10002, 0);
5382 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5383 SEEN_NN(rv, stash, 0); /* Will return if rv is null */
5384 cxt->in_retrieve_overloaded = 1; /* so sv_bless doesn't call S_reset_amagic */
5385 sv = retrieve(aTHX_ cxt, 0); /* Retrieve <object> */
5386 cxt->in_retrieve_overloaded = 0;
5388 return (SV *) 0; /* Failed */
5391 * WARNING: breaks RV encapsulation.
5394 SvUPGRADE(rv, SVt_RV);
5395 SvRV_set(rv, sv); /* $rv = \$sv */
5399 * Restore overloading magic.
5402 stash = SvTYPE(sv) ? (HV *) SvSTASH (sv) : 0;
5404 CROAK(("Cannot restore overloading on %s(0x%" UVxf
5405 ") (package <unknown>)",
5406 sv_reftype(sv, FALSE),
5409 if (!Gv_AMG(stash)) {
5410 const char *package = HvNAME_get(stash);
5411 TRACEME(("No overloading defined for package %s", package));
5412 TRACEME(("Going to load module '%s'", package));
5413 load_module(PERL_LOADMOD_NOIMPORT, newSVpv(package, 0), Nullsv);
5414 if (!Gv_AMG(stash)) {
5415 CROAK(("Cannot restore overloading on %s(0x%" UVxf
5416 ") (package %s) (even after a \"require %s;\")",
5417 sv_reftype(sv, FALSE),
5425 TRACEME(("ok (retrieve_overloaded at 0x%" UVxf ")", PTR2UV(rv)));
5431 * retrieve_weakoverloaded
5433 * Retrieve weak overloaded reference to some other scalar.
5434 * Layout is SX_WEAKOVERLOADED <object>, with SX_WEAKOVERLOADED already read.
5436 static SV *retrieve_weakoverloaded(pTHX_ stcxt_t *cxt, const char *cname)
5440 TRACEME(("retrieve_weakoverloaded (#%d)", (int)cxt->tagnum));
5442 sv = retrieve_overloaded(aTHX_ cxt, cname);
5454 * retrieve_tied_array
5456 * Retrieve tied array
5457 * Layout is SX_TIED_ARRAY <object>, with SX_TIED_ARRAY already read.
5459 static SV *retrieve_tied_array(pTHX_ stcxt_t *cxt, const char *cname)
5465 TRACEME(("retrieve_tied_array (#%d)", (int)cxt->tagnum));
5467 if (!(cxt->flags & FLAG_TIE_OK)) {
5468 CROAK(("Tying is disabled."));
5471 tv = NEWSV(10002, 0);
5472 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5473 SEEN_NN(tv, stash, 0); /* Will return if tv is null */
5474 sv = retrieve(aTHX_ cxt, 0); /* Retrieve <object> */
5476 return (SV *) 0; /* Failed */
5478 sv_upgrade(tv, SVt_PVAV);
5479 sv_magic(tv, sv, 'P', (char *)NULL, 0);
5480 SvREFCNT_dec(sv); /* Undo refcnt inc from sv_magic() */
5482 TRACEME(("ok (retrieve_tied_array at 0x%" UVxf ")", PTR2UV(tv)));
5488 * retrieve_tied_hash
5490 * Retrieve tied hash
5491 * Layout is SX_TIED_HASH <object>, with SX_TIED_HASH already read.
5493 static SV *retrieve_tied_hash(pTHX_ stcxt_t *cxt, const char *cname)
5499 TRACEME(("retrieve_tied_hash (#%d)", (int)cxt->tagnum));
5501 if (!(cxt->flags & FLAG_TIE_OK)) {
5502 CROAK(("Tying is disabled."));
5505 tv = NEWSV(10002, 0);
5506 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5507 SEEN_NN(tv, stash, 0); /* Will return if tv is null */
5508 sv = retrieve(aTHX_ cxt, 0); /* Retrieve <object> */
5510 return (SV *) 0; /* Failed */
5512 sv_upgrade(tv, SVt_PVHV);
5513 sv_magic(tv, sv, 'P', (char *)NULL, 0);
5514 SvREFCNT_dec(sv); /* Undo refcnt inc from sv_magic() */
5516 TRACEME(("ok (retrieve_tied_hash at 0x%" UVxf ")", PTR2UV(tv)));
5522 * retrieve_tied_scalar
5524 * Retrieve tied scalar
5525 * Layout is SX_TIED_SCALAR <object>, with SX_TIED_SCALAR already read.
5527 static SV *retrieve_tied_scalar(pTHX_ stcxt_t *cxt, const char *cname)
5530 SV *sv, *obj = NULL;
5533 TRACEME(("retrieve_tied_scalar (#%d)", (int)cxt->tagnum));
5535 if (!(cxt->flags & FLAG_TIE_OK)) {
5536 CROAK(("Tying is disabled."));
5539 tv = NEWSV(10002, 0);
5540 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5541 SEEN_NN(tv, stash, 0); /* Will return if rv is null */
5542 sv = retrieve(aTHX_ cxt, 0); /* Retrieve <object> */
5544 return (SV *) 0; /* Failed */
5546 else if (SvTYPE(sv) != SVt_NULL) {
5550 sv_upgrade(tv, SVt_PVMG);
5551 sv_magic(tv, obj, 'q', (char *)NULL, 0);
5554 /* Undo refcnt inc from sv_magic() */
5558 TRACEME(("ok (retrieve_tied_scalar at 0x%" UVxf ")", PTR2UV(tv)));
5566 * Retrieve reference to value in a tied hash.
5567 * Layout is SX_TIED_KEY <object> <key>, with SX_TIED_KEY already read.
5569 static SV *retrieve_tied_key(pTHX_ stcxt_t *cxt, const char *cname)
5576 TRACEME(("retrieve_tied_key (#%d)", (int)cxt->tagnum));
5578 if (!(cxt->flags & FLAG_TIE_OK)) {
5579 CROAK(("Tying is disabled."));
5582 tv = NEWSV(10002, 0);
5583 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5584 SEEN_NN(tv, stash, 0); /* Will return if tv is null */
5585 sv = retrieve(aTHX_ cxt, 0); /* Retrieve <object> */
5587 return (SV *) 0; /* Failed */
5589 key = retrieve(aTHX_ cxt, 0); /* Retrieve <key> */
5591 return (SV *) 0; /* Failed */
5593 sv_upgrade(tv, SVt_PVMG);
5594 sv_magic(tv, sv, 'p', (char *)key, HEf_SVKEY);
5595 SvREFCNT_dec(key); /* Undo refcnt inc from sv_magic() */
5596 SvREFCNT_dec(sv); /* Undo refcnt inc from sv_magic() */
5604 * Retrieve reference to value in a tied array.
5605 * Layout is SX_TIED_IDX <object> <idx>, with SX_TIED_IDX already read.
5607 static SV *retrieve_tied_idx(pTHX_ stcxt_t *cxt, const char *cname)
5614 TRACEME(("retrieve_tied_idx (#%d)", (int)cxt->tagnum));
5616 if (!(cxt->flags & FLAG_TIE_OK)) {
5617 CROAK(("Tying is disabled."));
5620 tv = NEWSV(10002, 0);
5621 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5622 SEEN_NN(tv, stash, 0); /* Will return if tv is null */
5623 sv = retrieve(aTHX_ cxt, 0); /* Retrieve <object> */
5625 return (SV *) 0; /* Failed */
5627 RLEN(idx); /* Retrieve <idx> */
5629 sv_upgrade(tv, SVt_PVMG);
5630 sv_magic(tv, sv, 'p', (char *)NULL, idx);
5631 SvREFCNT_dec(sv); /* Undo refcnt inc from sv_magic() */
5639 * Helper to read a string
5641 static SV *get_lstring(pTHX_ stcxt_t *cxt, UV len, int isutf8, const char *cname)
5646 TRACEME(("get_lstring (#%d), len = %" UVuf, (int)cxt->tagnum, len));
5649 * Allocate an empty scalar of the suitable length.
5652 sv = NEWSV(10002, len);
5653 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5654 SEEN_NN(sv, stash, 0); /* Associate this new scalar with tag "tagnum" */
5662 * WARNING: duplicates parts of sv_setpv and breaks SV data encapsulation.
5664 * Now, for efficiency reasons, read data directly inside the SV buffer,
5665 * and perform the SV final settings directly by duplicating the final
5666 * work done by sv_setpv. Since we're going to allocate lots of scalars
5667 * this way, it's worth the hassle and risk.
5670 SAFEREAD(SvPVX(sv), len, sv);
5671 SvCUR_set(sv, len); /* Record C string length */
5672 *SvEND(sv) = '\0'; /* Ensure it's null terminated anyway */
5673 (void) SvPOK_only(sv); /* Validate string pointer */
5674 if (cxt->s_tainted) /* Is input source tainted? */
5675 SvTAINT(sv); /* External data cannot be trusted */
5677 /* Check for CVE-215-1592 */
5678 if (cname && len == 13 && strEQc(cname, "CGITempFile")
5679 && strEQc(SvPVX(sv), "mt-config.cgi")) {
5680 #if defined(USE_CPERL) && defined(WARN_SECURITY)
5681 Perl_warn_security(aTHX_
5682 "Movable-Type CVE-2015-1592 Storable metasploit attack");
5685 "SECURITY: Movable-Type CVE-2015-1592 Storable metasploit attack");
5690 TRACEME(("large utf8 string len %" UVuf " '%s'", len,
5691 len >= 2048 ? "<string too long>" : SvPVX(sv)));
5692 #ifdef HAS_UTF8_SCALARS
5695 if (cxt->use_bytes < 0)
5697 = (SvTRUE(get_sv("Storable::drop_utf8", GV_ADD))
5699 if (cxt->use_bytes == 0)
5703 TRACEME(("large string len %" UVuf " '%s'", len,
5704 len >= 2048 ? "<string too long>" : SvPVX(sv)));
5706 TRACEME(("ok (get_lstring at 0x%" UVxf ")", PTR2UV(sv)));
5714 * Retrieve defined long (string) scalar.
5716 * Layout is SX_LSCALAR <length> <data>, with SX_LSCALAR already read.
5717 * The scalar is "long" in that <length> is larger than LG_SCALAR so it
5718 * was not stored on a single byte, but in 4 bytes. For strings longer than
5719 * 4 byte (>2GB) see retrieve_lobject.
5721 static SV *retrieve_lscalar(pTHX_ stcxt_t *cxt, const char *cname)
5725 return get_lstring(aTHX_ cxt, len, 0, cname);
5731 * Retrieve defined short (string) scalar.
5733 * Layout is SX_SCALAR <length> <data>, with SX_SCALAR already read.
5734 * The scalar is "short" so <length> is single byte. If it is 0, there
5735 * is no <data> section.
5737 static SV *retrieve_scalar(pTHX_ stcxt_t *cxt, const char *cname)
5744 TRACEME(("retrieve_scalar (#%d), len = %d", (int)cxt->tagnum, len));
5745 return get_lstring(aTHX_ cxt, (UV)len, 0, cname);
5751 * Like retrieve_scalar(), but tag result as utf8.
5752 * If we're retrieving UTF8 data in a non-UTF8 perl, croaks.
5754 static SV *retrieve_utf8str(pTHX_ stcxt_t *cxt, const char *cname)
5759 TRACEME(("retrieve_utf8str"));
5761 return get_lstring(aTHX_ cxt, (UV)len, 1, cname);
5767 * Like retrieve_lscalar(), but tag result as utf8.
5768 * If we're retrieving UTF8 data in a non-UTF8 perl, croaks.
5770 static SV *retrieve_lutf8str(pTHX_ stcxt_t *cxt, const char *cname)
5774 TRACEME(("retrieve_lutf8str"));
5777 return get_lstring(aTHX_ cxt, (UV)len, 1, cname);
5783 * Retrieve a vstring, and then retrieve the stringy scalar following it,
5784 * attaching the vstring to the scalar via magic.
5785 * If we're retrieving a vstring in a perl without vstring magic, croaks.
5787 * The vstring layout mirrors an SX_SCALAR string:
5788 * SX_VSTRING <length> <data> with SX_VSTRING already read.
5790 static SV *retrieve_vstring(pTHX_ stcxt_t *cxt, const char *cname)
5798 TRACEME(("retrieve_vstring (#%d), len = %d", (int)cxt->tagnum, len));
5801 sv = retrieve(aTHX_ cxt, cname);
5803 return (SV *) 0; /* Failed */
5804 sv_magic(sv,NULL,PERL_MAGIC_vstring,s,len);
5805 /* 5.10.0 and earlier seem to need this */
5808 TRACEME(("ok (retrieve_vstring at 0x%" UVxf ")", PTR2UV(sv)));
5819 * Like retrieve_vstring, but for longer vstrings.
5821 static SV *retrieve_lvstring(pTHX_ stcxt_t *cxt, const char *cname)
5829 TRACEME(("retrieve_lvstring (#%d), len = %" UVuf,
5830 (int)cxt->tagnum, (UV)len));
5832 /* Since we'll no longer produce such large vstrings, reject them
5835 if (len >= I32_MAX) {
5836 CROAK(("vstring too large to fetch"));
5839 New(10003, s, len+1, char);
5840 SAFEPVREAD(s, (I32)len, s);
5842 sv = retrieve(aTHX_ cxt, cname);
5845 return (SV *) 0; /* Failed */
5847 sv_magic(sv,NULL,PERL_MAGIC_vstring,s,len);
5848 /* 5.10.0 and earlier seem to need this */
5853 TRACEME(("ok (retrieve_lvstring at 0x%" UVxf ")", PTR2UV(sv)));
5864 * Retrieve defined integer.
5865 * Layout is SX_INTEGER <data>, whith SX_INTEGER already read.
5867 static SV *retrieve_integer(pTHX_ stcxt_t *cxt, const char *cname)
5873 TRACEME(("retrieve_integer (#%d)", (int)cxt->tagnum));
5875 READ(&iv, sizeof(iv));
5877 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5878 SEEN_NN(sv, stash, 0); /* Associate this new scalar with tag "tagnum" */
5880 TRACEME(("integer %" IVdf, iv));
5881 TRACEME(("ok (retrieve_integer at 0x%" UVxf ")", PTR2UV(sv)));
5889 * Retrieve overlong scalar, array or hash.
5890 * Layout is SX_LOBJECT type U64_len ...
5892 static SV *retrieve_lobject(pTHX_ stcxt_t *cxt, const char *cname)
5901 TRACEME(("retrieve_lobject (#%d)", (int)cxt->tagnum));
5904 TRACEME(("object type %d", type));
5907 if (type == SX_FLAG_HASH) {
5908 /* we write the flags immediately after the op. I could have
5909 changed the writer, but this may allow someone to recover
5910 data they're already frozen, though such a very large hash
5913 GETMARK(hash_flags);
5915 else if (type == SX_HOOK) {
5916 return retrieve_hook_common(aTHX_ cxt, cname, TRUE);
5920 TRACEME(("wlen %" UVuf, len));
5924 /* not a large object, just a large index */
5925 SV **svh = av_fetch(cxt->aseen, len, FALSE);
5927 CROAK(("Object #%" UVuf " should have been retrieved already",
5930 TRACEME(("had retrieved #%" UVuf " at 0x%" UVxf, len, PTR2UV(sv)));
5935 sv = get_lstring(aTHX_ cxt, len, 0, cname);
5938 sv = get_lstring(aTHX_ cxt, len, 1, cname);
5941 sv = get_larray(aTHX_ cxt, len, cname);
5943 /* <5.12 you could store larger hashes, but cannot iterate over them.
5944 So we reject them, it's a bug. */
5946 sv = get_lhash(aTHX_ cxt, len, hash_flags, cname);
5949 sv = get_lhash(aTHX_ cxt, len, 0, cname);
5952 CROAK(("Unexpected type %d in retrieve_lobject\n", type));
5955 TRACEME(("ok (retrieve_lobject at 0x%" UVxf ")", PTR2UV(sv)));
5958 PERL_UNUSED_ARG(cname);
5960 /* previously this (brokenly) checked the length value and only failed if
5961 the length was over 4G.
5962 Since this op should only occur with objects over 4GB (or 2GB) we can just
5965 CROAK(("Invalid large object op for this 32bit system"));
5972 * Retrieve defined integer in network order.
5973 * Layout is SX_NETINT <data>, whith SX_NETINT already read.
5975 static SV *retrieve_netint(pTHX_ stcxt_t *cxt, const char *cname)
5981 TRACEME(("retrieve_netint (#%d)", (int)cxt->tagnum));
5985 sv = newSViv((int) ntohl(iv));
5986 TRACEME(("network integer %d", (int) ntohl(iv)));
5989 TRACEME(("network integer (as-is) %d", iv));
5991 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5992 SEEN_NN(sv, stash, 0); /* Associate this new scalar with tag "tagnum" */
5994 TRACEME(("ok (retrieve_netint at 0x%" UVxf ")", PTR2UV(sv)));
6002 * Retrieve defined double.
6003 * Layout is SX_DOUBLE <data>, whith SX_DOUBLE already read.
6005 static SV *retrieve_double(pTHX_ stcxt_t *cxt, const char *cname)
6011 TRACEME(("retrieve_double (#%d)", (int)cxt->tagnum));
6013 READ(&nv, sizeof(nv));
6015 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
6016 SEEN_NN(sv, stash, 0); /* Associate this new scalar with tag "tagnum" */
6018 TRACEME(("double %" NVff, nv));
6019 TRACEME(("ok (retrieve_double at 0x%" UVxf ")", PTR2UV(sv)));
6027 * Retrieve defined byte (small integer within the [-128, +127] range).
6028 * Layout is SX_BYTE <data>, whith SX_BYTE already read.
6030 static SV *retrieve_byte(pTHX_ stcxt_t *cxt, const char *cname)
6036 /* MSVC 2017 doesn't handle the AIX workaround well */
6039 signed char tmp; /* Workaround for AIX cc bug --H.Merijn Brand */
6042 TRACEME(("retrieve_byte (#%d)", (int)cxt->tagnum));
6045 TRACEME(("small integer read as %d", (unsigned char) siv));
6046 tmp = (unsigned char) siv - 128;
6048 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
6049 SEEN_NN(sv, stash, 0); /* Associate this new scalar with tag "tagnum" */
6051 TRACEME(("byte %d", tmp));
6052 TRACEME(("ok (retrieve_byte at 0x%" UVxf ")", PTR2UV(sv)));
6060 * Return the undefined value.
6062 static SV *retrieve_undef(pTHX_ stcxt_t *cxt, const char *cname)
6067 TRACEME(("retrieve_undef"));
6070 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
6071 SEEN_NN(sv, stash, 0);
6079 * Return the immortal undefined value.
6081 static SV *retrieve_sv_undef(pTHX_ stcxt_t *cxt, const char *cname)
6083 SV *sv = &PL_sv_undef;
6086 TRACEME(("retrieve_sv_undef"));
6088 /* Special case PL_sv_undef, as av_fetch uses it internally to mark
6089 deleted elements, and will return NULL (fetch failed) whenever it
6091 if (cxt->where_is_undef == UNSET_NTAG_T) {
6092 cxt->where_is_undef = cxt->tagnum;
6094 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
6095 SEEN_NN(sv, stash, 1);
6102 * Return the immortal yes value.
6104 static SV *retrieve_sv_yes(pTHX_ stcxt_t *cxt, const char *cname)
6106 SV *sv = &PL_sv_yes;
6109 TRACEME(("retrieve_sv_yes"));
6111 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
6112 SEEN_NN(sv, stash, 1);
6119 * Return the immortal no value.
6121 static SV *retrieve_sv_no(pTHX_ stcxt_t *cxt, const char *cname)
6126 TRACEME(("retrieve_sv_no"));
6128 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
6129 SEEN_NN(sv, stash, 1);
6134 * retrieve_svundef_elem
6136 * Return &PL_sv_placeholder, representing &PL_sv_undef in an array. This
6137 * is a bit of a hack, but we already use SX_SV_UNDEF to mean a nonexistent
6138 * element, for historical reasons.
6140 static SV *retrieve_svundef_elem(pTHX_ stcxt_t *cxt, const char *cname)
6142 TRACEME(("retrieve_svundef_elem"));
6144 /* SEEN reads the contents of its SV argument, which we are not
6145 supposed to do with &PL_sv_placeholder. */
6146 SEEN_NN(&PL_sv_undef, cname, 1);
6148 return &PL_sv_placeholder;
6154 * Retrieve a whole array.
6155 * Layout is SX_ARRAY <size> followed by each item, in increasing index order.
6156 * Each item is stored as <object>.
6158 * When we come here, SX_ARRAY has been read already.
6160 static SV *retrieve_array(pTHX_ stcxt_t *cxt, const char *cname)
6166 bool seen_null = FALSE;
6168 TRACEME(("retrieve_array (#%d)", (int)cxt->tagnum));
6171 * Read length, and allocate array, then pre-extend it.
6175 TRACEME(("size = %d", (int)len));
6177 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
6178 SEEN_NN(av, stash, 0); /* Will return if array not allocated nicely */
6182 return (SV *) av; /* No data follow if array is empty */
6185 * Now get each item in turn...
6188 for (i = 0; i < len; i++) {
6189 TRACEME(("(#%d) item", (int)i));
6190 sv = retrieve(aTHX_ cxt, 0); /* Retrieve item */
6193 if (sv == &PL_sv_undef) {
6197 if (sv == &PL_sv_placeholder)
6199 if (av_store(av, i, sv) == 0)
6202 if (seen_null) av_fill(av, len-1);
6204 TRACEME(("ok (retrieve_array at 0x%" UVxf ")", PTR2UV(av)));
6211 /* internal method with len already read */
6213 static SV *get_larray(pTHX_ stcxt_t *cxt, UV len, const char *cname)
6219 bool seen_null = FALSE;
6221 TRACEME(("get_larray (#%d) %lu", (int)cxt->tagnum, (unsigned long)len));
6224 * allocate array, then pre-extend it.
6228 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
6229 SEEN_NN(av, stash, 0); /* Will return if array not allocated nicely */
6234 * Now get each item in turn...
6237 for (i = 0; i < len; i++) {
6238 TRACEME(("(#%d) item", (int)i));
6239 sv = retrieve(aTHX_ cxt, 0); /* Retrieve item */
6242 if (sv == &PL_sv_undef) {
6246 if (sv == &PL_sv_placeholder)
6248 if (av_store(av, i, sv) == 0)
6251 if (seen_null) av_fill(av, len-1);
6253 TRACEME(("ok (get_larray at 0x%" UVxf ")", PTR2UV(av)));
6261 * Retrieve a overlong hash table.
6262 * <len> is already read. What follows is each key/value pair, in random order.
6263 * Keys are stored as <length> <data>, the <data> section being omitted
6265 * Values are stored as <object>.
6268 static SV *get_lhash(pTHX_ stcxt_t *cxt, UV len, int hash_flags, const char *cname)
6276 TRACEME(("get_lhash (#%d)", (int)cxt->tagnum));
6278 #ifdef HAS_RESTRICTED_HASHES
6279 PERL_UNUSED_ARG(hash_flags);
6281 if (hash_flags & SHV_RESTRICTED) {
6282 if (cxt->derestrict < 0)
6283 cxt->derestrict = (SvTRUE
6284 (get_sv("Storable::downgrade_restricted", GV_ADD))
6286 if (cxt->derestrict == 0)
6287 RESTRICTED_HASH_CROAK();
6291 TRACEME(("size = %lu", (unsigned long)len));
6293 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
6294 SEEN_NN(hv, stash, 0); /* Will return if table not allocated properly */
6296 return (SV *) hv; /* No data follow if table empty */
6297 TRACEME(("split %lu", (unsigned long)len+1));
6298 hv_ksplit(hv, len+1); /* pre-extend hash to save multiple splits */
6301 * Now get each key/value pair in turn...
6304 for (i = 0; i < len; i++) {
6309 TRACEME(("(#%d) value", (int)i));
6310 sv = retrieve(aTHX_ cxt, 0);
6316 * Since we're reading into kbuf, we must ensure we're not
6317 * recursing between the read and the hv_store() where it's used.
6318 * Hence the key comes after the value.
6321 RLEN(size); /* Get key size */
6322 KBUFCHK((STRLEN)size); /* Grow hash key read pool if needed */
6325 kbuf[size] = '\0'; /* Mark string end, just in case */
6326 TRACEME(("(#%d) key '%s'", (int)i, kbuf));
6329 * Enter key/value pair into hash table.
6332 if (hv_store(hv, kbuf, (U32) size, sv, 0) == 0)
6336 TRACEME(("ok (get_lhash at 0x%" UVxf ")", PTR2UV(hv)));
6344 * Retrieve a whole hash table.
6345 * Layout is SX_HASH <size> followed by each key/value pair, in random order.
6346 * Keys are stored as <length> <data>, the <data> section being omitted
6348 * Values are stored as <object>.
6350 * When we come here, SX_HASH has been read already.
6352 static SV *retrieve_hash(pTHX_ stcxt_t *cxt, const char *cname)
6361 TRACEME(("retrieve_hash (#%d)", (int)cxt->tagnum));
6364 * Read length, allocate table.
6368 TRACEME(("size = %d", (int)len));
6370 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
6371 SEEN_NN(hv, stash, 0); /* Will return if table not allocated properly */
6373 return (SV *) hv; /* No data follow if table empty */
6374 TRACEME(("split %d", (int)len+1));
6375 hv_ksplit(hv, len+1); /* pre-extend hash to save multiple splits */
6378 * Now get each key/value pair in turn...
6381 for (i = 0; i < len; i++) {
6386 TRACEME(("(#%d) value", (int)i));
6387 sv = retrieve(aTHX_ cxt, 0);
6393 * Since we're reading into kbuf, we must ensure we're not
6394 * recursing between the read and the hv_store() where it's used.
6395 * Hence the key comes after the value.
6398 RLEN(size); /* Get key size */
6399 KBUFCHK((STRLEN)size); /* Grow hash key read pool if needed */
6402 kbuf[size] = '\0'; /* Mark string end, just in case */
6403 TRACEME(("(#%d) key '%s'", (int)i, kbuf));
6406 * Enter key/value pair into hash table.
6409 if (hv_store(hv, kbuf, (U32) size, sv, 0) == 0)
6413 TRACEME(("ok (retrieve_hash at 0x%" UVxf ")", PTR2UV(hv)));
6421 * Retrieve a whole hash table.
6422 * Layout is SX_HASH <size> followed by each key/value pair, in random order.
6423 * Keys are stored as <length> <data>, the <data> section being omitted
6425 * Values are stored as <object>.
6427 * When we come here, SX_HASH has been read already.
6429 static SV *retrieve_flag_hash(pTHX_ stcxt_t *cxt, const char *cname)
6440 GETMARK(hash_flags);
6441 TRACEME(("retrieve_flag_hash (#%d)", (int)cxt->tagnum));
6443 * Read length, allocate table.
6446 #ifndef HAS_RESTRICTED_HASHES
6447 if (hash_flags & SHV_RESTRICTED) {
6448 if (cxt->derestrict < 0)
6449 cxt->derestrict = (SvTRUE
6450 (get_sv("Storable::downgrade_restricted", GV_ADD))
6452 if (cxt->derestrict == 0)
6453 RESTRICTED_HASH_CROAK();
6458 TRACEME(("size = %d, flags = %d", (int)len, hash_flags));
6460 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
6461 SEEN_NN(hv, stash, 0); /* Will return if table not allocated properly */
6463 return (SV *) hv; /* No data follow if table empty */
6464 TRACEME(("split %d", (int)len+1));
6465 hv_ksplit(hv, len+1); /* pre-extend hash to save multiple splits */
6468 * Now get each key/value pair in turn...
6471 for (i = 0; i < len; i++) {
6473 int store_flags = 0;
6478 TRACEME(("(#%d) value", (int)i));
6479 sv = retrieve(aTHX_ cxt, 0);
6484 #ifdef HAS_RESTRICTED_HASHES
6485 if ((hash_flags & SHV_RESTRICTED) && (flags & SHV_K_LOCKED))
6489 if (flags & SHV_K_ISSV) {
6490 /* XXX you can't set a placeholder with an SV key.
6491 Then again, you can't get an SV key.
6492 Without messing around beyond what the API is supposed to do.
6495 TRACEME(("(#%d) keysv, flags=%d", (int)i, flags));
6496 keysv = retrieve(aTHX_ cxt, 0);
6500 if (!hv_store_ent(hv, keysv, sv, 0))
6505 * Since we're reading into kbuf, we must ensure we're not
6506 * recursing between the read and the hv_store() where it's used.
6507 * Hence the key comes after the value.
6510 if (flags & SHV_K_PLACEHOLDER) {
6512 sv = &PL_sv_placeholder;
6513 store_flags |= HVhek_PLACEHOLD;
6515 if (flags & SHV_K_UTF8) {
6516 #ifdef HAS_UTF8_HASHES
6517 store_flags |= HVhek_UTF8;
6519 if (cxt->use_bytes < 0)
6521 = (SvTRUE(get_sv("Storable::drop_utf8", GV_ADD))
6523 if (cxt->use_bytes == 0)
6527 #ifdef HAS_UTF8_HASHES
6528 if (flags & SHV_K_WASUTF8)
6529 store_flags |= HVhek_WASUTF8;
6532 RLEN(size); /* Get key size */
6533 KBUFCHK((STRLEN)size);/* Grow hash key read pool if needed */
6536 kbuf[size] = '\0'; /* Mark string end, just in case */
6537 TRACEME(("(#%d) key '%s' flags %X store_flags %X", (int)i, kbuf,
6538 flags, store_flags));
6541 * Enter key/value pair into hash table.
6544 #ifdef HAS_RESTRICTED_HASHES
6545 if (hv_store_flags(hv, kbuf, size, sv, 0, store_flags) == 0)
6548 if (!(store_flags & HVhek_PLACEHOLD))
6549 if (hv_store(hv, kbuf, size, sv, 0) == 0)
6554 #ifdef HAS_RESTRICTED_HASHES
6555 if (hash_flags & SHV_RESTRICTED)
6559 TRACEME(("ok (retrieve_hash at 0x%" UVxf ")", PTR2UV(hv)));
6567 * Return a code reference.
6569 static SV *retrieve_code(pTHX_ stcxt_t *cxt, const char *cname)
6575 SV *sv, *text, *sub, *errsv;
6578 TRACEME(("retrieve_code (#%d)", (int)cxt->tagnum));
6581 * Insert dummy SV in the aseen array so that we don't screw
6582 * up the tag numbers. We would just make the internal
6583 * scalar an untagged item in the stream, but
6584 * retrieve_scalar() calls SEEN(). So we just increase the
6587 tagnum = cxt->tagnum;
6589 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
6590 SEEN_NN(sv, stash, 0);
6593 * Retrieve the source of the code reference
6594 * as a small or large scalar
6600 text = retrieve_scalar(aTHX_ cxt, cname);
6603 text = retrieve_lscalar(aTHX_ cxt, cname);
6606 text = retrieve_utf8str(aTHX_ cxt, cname);
6609 text = retrieve_lutf8str(aTHX_ cxt, cname);
6612 CROAK(("Unexpected type %d in retrieve_code\n", (int)type));
6616 CROAK(("Unable to retrieve code\n"));
6620 * prepend "sub " to the source
6623 sub = newSVpvs("sub ");
6626 sv_catpv(sub, SvPV_nolen(text)); /* XXX no sv_catsv! */
6630 * evaluate the source to a code reference and use the CV value
6633 if (cxt->eval == NULL) {
6634 cxt->eval = get_sv("Storable::Eval", GV_ADD);
6635 SvREFCNT_inc(cxt->eval);
6637 if (!SvTRUE(cxt->eval)) {
6638 if (cxt->forgive_me == 0 ||
6639 (cxt->forgive_me < 0 &&
6640 !(cxt->forgive_me = SvTRUE
6641 (get_sv("Storable::forgive_me", GV_ADD)) ? 1 : 0))
6643 CROAK(("Can't eval, please set $Storable::Eval to a true value"));
6646 /* fix up the dummy entry... */
6647 av_store(cxt->aseen, tagnum, SvREFCNT_inc(sv));
6655 errsv = get_sv("@", GV_ADD);
6656 SvPVCLEAR(errsv); /* clear $@ */
6657 if (SvROK(cxt->eval) && SvTYPE(SvRV(cxt->eval)) == SVt_PVCV) {
6659 XPUSHs(sv_2mortal(newSVsv(sub)));
6661 count = call_sv(cxt->eval, G_SCALAR);
6663 CROAK(("Unexpected return value from $Storable::Eval callback\n"));
6665 eval_sv(sub, G_SCALAR);
6671 if (SvTRUE(errsv)) {
6672 CROAK(("code %s caused an error: %s",
6673 SvPV_nolen(sub), SvPV_nolen(errsv)));
6676 if (cv && SvROK(cv) && SvTYPE(SvRV(cv)) == SVt_PVCV) {
6679 CROAK(("code %s did not evaluate to a subroutine reference\n",
6683 SvREFCNT_inc(sv); /* XXX seems to be necessary */
6688 /* fix up the dummy entry... */
6689 av_store(cxt->aseen, tagnum, SvREFCNT_inc(sv));
6694 static SV *retrieve_regexp(pTHX_ stcxt_t *cxt, const char *cname) {
6695 #if PERL_VERSION_GE(5,8,0)
6711 if (op_flags & SHR_U32_RE_LEN) {
6717 re = sv_2mortal(NEWSV(10002, re_len ? re_len : 1));
6718 READ(SvPVX(re), re_len);
6719 SvCUR_set(re, re_len);
6724 flags = sv_2mortal(NEWSV(10002, flags_len ? flags_len : 1));
6725 READ(SvPVX(flags), flags_len);
6726 SvCUR_set(flags, flags_len);
6727 *SvEND(flags) = '\0';
6737 count = call_pv("Storable::_make_re", G_SCALAR);
6742 CROAK(("Bad count %d calling _make_re", (int)count));
6749 CROAK(("_make_re didn't return a reference"));
6753 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
6754 SEEN_NN(sv, stash, 0);
6761 CROAK(("retrieve_regexp does not work with 5.6 or earlier"));
6766 * old_retrieve_array
6768 * Retrieve a whole array in pre-0.6 binary format.
6770 * Layout is SX_ARRAY <size> followed by each item, in increasing index order.
6771 * Each item is stored as SX_ITEM <object> or SX_IT_UNDEF for "holes".
6773 * When we come here, SX_ARRAY has been read already.
6775 static SV *old_retrieve_array(pTHX_ stcxt_t *cxt, const char *cname)
6783 PERL_UNUSED_ARG(cname);
6784 TRACEME(("old_retrieve_array (#%d)", (int)cxt->tagnum));
6787 * Read length, and allocate array, then pre-extend it.
6791 TRACEME(("size = %d", (int)len));
6793 SEEN0_NN(av, 0); /* Will return if array not allocated nicely */
6797 return (SV *) av; /* No data follow if array is empty */
6800 * Now get each item in turn...
6803 for (i = 0; i < len; i++) {
6805 if (c == SX_IT_UNDEF) {
6806 TRACEME(("(#%d) undef item", (int)i));
6807 continue; /* av_extend() already filled us with undef */
6810 (void) retrieve_other(aTHX_ cxt, 0);/* Will croak out */
6811 TRACEME(("(#%d) item", (int)i));
6812 sv = retrieve(aTHX_ cxt, 0); /* Retrieve item */
6815 if (av_store(av, i, sv) == 0)
6819 TRACEME(("ok (old_retrieve_array at 0x%" UVxf ")", PTR2UV(av)));
6827 * Retrieve a whole hash table in pre-0.6 binary format.
6829 * Layout is SX_HASH <size> followed by each key/value pair, in random order.
6830 * Keys are stored as SX_KEY <length> <data>, the <data> section being omitted
6832 * Values are stored as SX_VALUE <object> or SX_VL_UNDEF for "holes".
6834 * When we come here, SX_HASH has been read already.
6836 static SV *old_retrieve_hash(pTHX_ stcxt_t *cxt, const char *cname)
6844 SV *sv_h_undef = (SV *) 0; /* hv_store() bug */
6846 PERL_UNUSED_ARG(cname);
6847 TRACEME(("old_retrieve_hash (#%d)", (int)cxt->tagnum));
6850 * Read length, allocate table.
6854 TRACEME(("size = %d", (int)len));
6856 SEEN0_NN(hv, 0); /* Will return if table not allocated properly */
6858 return (SV *) hv; /* No data follow if table empty */
6859 TRACEME(("split %d", (int)len+1));
6860 hv_ksplit(hv, len+1); /* pre-extend hash to save multiple splits */
6863 * Now get each key/value pair in turn...
6866 for (i = 0; i < len; i++) {
6872 if (c == SX_VL_UNDEF) {
6873 TRACEME(("(#%d) undef value", (int)i));
6875 * Due to a bug in hv_store(), it's not possible to pass
6876 * &PL_sv_undef to hv_store() as a value, otherwise the
6877 * associated key will not be creatable any more. -- RAM, 14/01/97
6880 sv_h_undef = newSVsv(&PL_sv_undef);
6881 sv = SvREFCNT_inc(sv_h_undef);
6882 } else if (c == SX_VALUE) {
6883 TRACEME(("(#%d) value", (int)i));
6884 sv = retrieve(aTHX_ cxt, 0);
6888 (void) retrieve_other(aTHX_ cxt, 0); /* Will croak out */
6892 * Since we're reading into kbuf, we must ensure we're not
6893 * recursing between the read and the hv_store() where it's used.
6894 * Hence the key comes after the value.
6899 (void) retrieve_other(aTHX_ cxt, 0); /* Will croak out */
6900 RLEN(size); /* Get key size */
6901 KBUFCHK((STRLEN)size); /* Grow hash key read pool if needed */
6904 kbuf[size] = '\0'; /* Mark string end, just in case */
6905 TRACEME(("(#%d) key '%s'", (int)i, kbuf));
6908 * Enter key/value pair into hash table.
6911 if (hv_store(hv, kbuf, (U32) size, sv, 0) == 0)
6915 TRACEME(("ok (retrieve_hash at 0x%" UVxf ")", PTR2UV(hv)));
6921 *** Retrieval engine.
6927 * Make sure the stored data we're trying to retrieve has been produced
6928 * on an ILP compatible system with the same byteorder. It croaks out in
6929 * case an error is detected. [ILP = integer-long-pointer sizes]
6930 * Returns null if error is detected, &PL_sv_undef otherwise.
6932 * Note that there's no byte ordering info emitted when network order was
6933 * used at store time.
6935 static SV *magic_check(pTHX_ stcxt_t *cxt)
6937 /* The worst case for a malicious header would be old magic (which is
6938 longer), major, minor, byteorder length byte of 255, 255 bytes of
6939 garbage, sizeof int, long, pointer, NV.
6940 So the worse of that we can read is 255 bytes of garbage plus 4.
6941 Err, I am assuming 8 bit bytes here. Please file a bug report if you're
6942 compiling perl on a system with chars that are larger than 8 bits.
6943 (Even Crays aren't *that* perverse).
6945 unsigned char buf[4 + 255];
6946 unsigned char *current;
6949 int use_network_order;
6953 int version_minor = 0;
6955 TRACEME(("magic_check"));
6958 * The "magic number" is only for files, not when freezing in memory.
6962 /* This includes the '\0' at the end. I want to read the extra byte,
6963 which is usually going to be the major version number. */
6964 STRLEN len = sizeof(magicstr);
6967 READ(buf, (SSize_t)(len)); /* Not null-terminated */
6969 /* Point at the byte after the byte we read. */
6970 current = buf + --len; /* Do the -- outside of macros. */
6972 if (memNE(buf, magicstr, len)) {
6974 * Try to read more bytes to check for the old magic number, which
6978 TRACEME(("trying for old magic number"));
6980 old_len = sizeof(old_magicstr) - 1;
6981 READ(current + 1, (SSize_t)(old_len - len));
6983 if (memNE(buf, old_magicstr, old_len))
6984 CROAK(("File is not a perl storable"));
6986 current = buf + old_len;
6988 use_network_order = *current;
6990 GETMARK(use_network_order);
6994 * Starting with 0.6, the "use_network_order" byte flag is also used to
6995 * indicate the version number of the binary, and therefore governs the
6996 * setting of sv_retrieve_vtbl. See magic_write().
6998 if (old_magic && use_network_order > 1) {
6999 /* 0.1 dump - use_network_order is really byte order length */
7003 version_major = use_network_order >> 1;
7005 cxt->retrieve_vtbl = (SV*(**)(pTHX_ stcxt_t *cxt, const char *cname)) (version_major > 0 ? sv_retrieve : sv_old_retrieve);
7007 TRACEME(("magic_check: netorder = 0x%x", use_network_order));
7011 * Starting with 0.7 (binary major 2), a full byte is dedicated to the
7012 * minor version of the protocol. See magic_write().
7015 if (version_major > 1)
7016 GETMARK(version_minor);
7018 cxt->ver_major = version_major;
7019 cxt->ver_minor = version_minor;
7021 TRACEME(("binary image version is %d.%d", version_major, version_minor));
7024 * Inter-operability sanity check: we can't retrieve something stored
7025 * using a format more recent than ours, because we have no way to
7026 * know what has changed, and letting retrieval go would mean a probable
7027 * failure reporting a "corrupted" storable file.
7031 version_major > STORABLE_BIN_MAJOR ||
7032 (version_major == STORABLE_BIN_MAJOR &&
7033 version_minor > STORABLE_BIN_MINOR)
7036 TRACEME(("but I am version is %d.%d", STORABLE_BIN_MAJOR,
7037 STORABLE_BIN_MINOR));
7039 if (version_major == STORABLE_BIN_MAJOR) {
7040 TRACEME(("cxt->accept_future_minor is %d",
7041 cxt->accept_future_minor));
7042 if (cxt->accept_future_minor < 0)
7043 cxt->accept_future_minor
7044 = (SvTRUE(get_sv("Storable::accept_future_minor",
7047 if (cxt->accept_future_minor == 1)
7048 croak_now = 0; /* Don't croak yet. */
7051 CROAK(("Storable binary image v%d.%d more recent than I am (v%d.%d)",
7052 version_major, version_minor,
7053 STORABLE_BIN_MAJOR, STORABLE_BIN_MINOR));
7058 * If they stored using network order, there's no byte ordering
7059 * information to check.
7062 if ((cxt->netorder = (use_network_order & 0x1))) /* Extra () for -Wall */
7063 return &PL_sv_undef; /* No byte ordering info */
7065 /* In C truth is 1, falsehood is 0. Very convenient. */
7066 use_NV_size = version_major >= 2 && version_minor >= 2;
7068 if (version_major >= 0) {
7072 c = use_network_order;
7074 length = c + 3 + use_NV_size;
7075 READ(buf, length); /* Not null-terminated */
7077 TRACEME(("byte order '%.*s' %d", c, buf, c));
7079 #ifdef USE_56_INTERWORK_KLUDGE
7080 /* No point in caching this in the context as we only need it once per
7081 retrieve, and we need to recheck it each read. */
7082 if (SvTRUE(get_sv("Storable::interwork_56_64bit", GV_ADD))) {
7083 if ((c != (sizeof (byteorderstr_56) - 1))
7084 || memNE(buf, byteorderstr_56, c))
7085 CROAK(("Byte order is not compatible"));
7089 if ((c != (sizeof (byteorderstr) - 1))
7090 || memNE(buf, byteorderstr, c))
7091 CROAK(("Byte order is not compatible"));
7097 if ((int) *current++ != sizeof(int))
7098 CROAK(("Integer size is not compatible"));
7101 if ((int) *current++ != sizeof(long))
7102 CROAK(("Long integer size is not compatible"));
7104 /* sizeof(char *) */
7105 if ((int) *current != sizeof(char *))
7106 CROAK(("Pointer size is not compatible"));
7110 if ((int) *++current != sizeof(NV))
7111 CROAK(("Double size is not compatible"));
7114 return &PL_sv_undef; /* OK */
7120 * Recursively retrieve objects from the specified file and return their
7121 * root SV (which may be an AV or an HV for what we care).
7122 * Returns null if there is a problem.
7124 static SV *retrieve(pTHX_ stcxt_t *cxt, const char *cname)
7130 TRACEME(("retrieve"));
7133 * Grab address tag which identifies the object if we are retrieving
7134 * an older format. Since the new binary format counts objects and no
7135 * longer explicitly tags them, we must keep track of the correspondence
7138 * The following section will disappear one day when the old format is
7139 * no longer supported, hence the final "goto" in the "if" block.
7142 if (cxt->hseen) { /* Retrieving old binary */
7144 if (cxt->netorder) {
7146 READ(&nettag, sizeof(I32)); /* Ordered sequence of I32 */
7147 tag = (stag_t) nettag;
7149 READ(&tag, sizeof(stag_t)); /* Original address of the SV */
7152 if (type == SX_OBJECT) {
7154 svh = hv_fetch(cxt->hseen, (char *) &tag, sizeof(tag), FALSE);
7156 CROAK(("Old tag 0x%" UVxf " should have been mapped already",
7158 tagn = SvIV(*svh); /* Mapped tag number computed earlier below */
7161 * The following code is common with the SX_OBJECT case below.
7164 svh = av_fetch(cxt->aseen, tagn, FALSE);
7166 CROAK(("Object #%" IVdf " should have been retrieved already",
7169 TRACEME(("has retrieved #%d at 0x%" UVxf, (int)tagn, PTR2UV(sv)));
7170 SvREFCNT_inc(sv); /* One more reference to this same sv */
7171 return sv; /* The SV pointer where object was retrieved */
7175 * Map new object, but don't increase tagnum. This will be done
7176 * by each of the retrieve_* functions when they call SEEN().
7178 * The mapping associates the "tag" initially present with a unique
7179 * tag number. See test for SX_OBJECT above to see how this is perused.
7182 if (!hv_store(cxt->hseen, (char *) &tag, sizeof(tag),
7183 newSViv(cxt->tagnum), 0))
7190 * Regular post-0.6 binary format.
7195 TRACEME(("retrieve type = %d", type));
7198 * Are we dealing with an object we should have already retrieved?
7201 if (type == SX_OBJECT) {
7206 /* A 32-bit system can't have over 2**31 objects anyway */
7208 CROAK(("Object #%" IVdf " out of range", (IV)tag));
7210 /* Older versions of Storable on with 64-bit support on 64-bit
7211 systems can produce values above the 2G boundary (or wrapped above
7212 the 4G boundary, which we can't do much about), treat those as
7214 This same commit stores tag ids over the 2G boundary as long tags
7215 since older Storables will mis-handle them as short tags.
7217 svh = av_fetch(cxt->aseen, (U32)tag, FALSE);
7219 CROAK(("Object #%" IVdf " should have been retrieved already",
7222 TRACEME(("had retrieved #%d at 0x%" UVxf, (int)tag, PTR2UV(sv)));
7223 SvREFCNT_inc(sv); /* One more reference to this same sv */
7224 return sv; /* The SV pointer where object was retrieved */
7225 } else if (type >= SX_LAST && cxt->ver_minor > STORABLE_BIN_MINOR) {
7226 if (cxt->accept_future_minor < 0)
7227 cxt->accept_future_minor
7228 = (SvTRUE(get_sv("Storable::accept_future_minor",
7231 if (cxt->accept_future_minor == 1) {
7232 CROAK(("Storable binary image v%d.%d contains data of type %d. "
7233 "This Storable is v%d.%d and can only handle data types up to %d",
7234 cxt->ver_major, cxt->ver_minor, type,
7235 STORABLE_BIN_MAJOR, STORABLE_BIN_MINOR, SX_LAST - 1));
7239 first_time: /* Will disappear when support for old format is dropped */
7242 * Okay, first time through for this one.
7245 sv = RETRIEVE(cxt, type)(aTHX_ cxt, cname);
7247 return (SV *) 0; /* Failed */
7250 * Old binary formats (pre-0.7).
7252 * Final notifications, ended by SX_STORED may now follow.
7253 * Currently, the only pertinent notification to apply on the
7254 * freshly retrieved object is either:
7255 * SX_CLASS <char-len> <classname> for short classnames.
7256 * SX_LG_CLASS <int-len> <classname> for larger one (rare!).
7257 * Class name is then read into the key buffer pool used by
7258 * hash table key retrieval.
7261 if (cxt->ver_major < 2) {
7262 while ((type = GETCHAR()) != SX_STORED) {
7267 GETMARK(len); /* Length coded on a single char */
7269 case SX_LG_CLASS: /* Length coded on a regular integer */
7274 return (SV *) 0; /* Failed */
7276 KBUFCHK((STRLEN)len); /* Grow buffer as necessary */
7279 kbuf[len] = '\0'; /* Mark string end */
7280 stash = gv_stashpvn(kbuf, len, GV_ADD);
7285 TRACEME(("ok (retrieved 0x%" UVxf ", refcnt=%d, %s)", PTR2UV(sv),
7286 (int)SvREFCNT(sv) - 1, sv_reftype(sv, FALSE)));
7294 * Retrieve data held in file and return the root object.
7295 * Common routine for pretrieve and mretrieve.
7297 static SV *do_retrieve(
7306 int is_tainted; /* Is input source tainted? */
7307 int pre_06_fmt = 0; /* True with pre Storable 0.6 formats */
7309 TRACEMED(("do_retrieve (optype = 0x%x, flags=0x%x)",
7310 (unsigned)optype, (unsigned)flags));
7312 optype |= ST_RETRIEVE;
7316 * Sanity assertions for retrieve dispatch tables.
7319 ASSERT(sizeof(sv_old_retrieve) == sizeof(sv_retrieve),
7320 ("old and new retrieve dispatch table have same size"));
7321 ASSERT(sv_old_retrieve[(int)SX_LAST] == retrieve_other,
7322 ("SX_LAST entry correctly initialized in old dispatch table"));
7323 ASSERT(sv_retrieve[(int)SX_LAST] == retrieve_other,
7324 ("SX_LAST entry correctly initialized in new dispatch table"));
7327 * Workaround for CROAK leak: if they enter with a "dirty" context,
7328 * free up memory for them now.
7333 clean_context(aTHX_ cxt);
7336 * Now that STORABLE_xxx hooks exist, it is possible that they try to
7337 * re-enter retrieve() via the hooks.
7341 cxt = allocate_context(aTHX_ cxt);
7348 ASSERT(cxt->entry == 1, ("starting new recursion"));
7349 ASSERT(!cxt->s_dirty, ("clean context"));
7354 * Data is loaded into the memory buffer when f is NULL, unless 'in' is
7355 * also NULL, in which case we're expecting the data to already lie
7356 * in the buffer (dclone case).
7359 KBUFINIT(); /* Allocate hash key reading pool once */
7365 const char *orig = SvPV(in, length);
7367 /* This is quite deliberate. I want the UTF8 routines
7368 to encounter the '\0' which perl adds at the end
7369 of all scalars, so that any new string also has
7372 STRLEN klen_tmp = length + 1;
7373 bool is_utf8 = TRUE;
7375 /* Just casting the &klen to (STRLEN) won't work
7376 well if STRLEN and I32 are of different widths.
7378 asbytes = (char*)bytes_from_utf8((U8*)orig,
7382 CROAK(("Frozen string corrupt - contains characters outside 0-255"));
7384 if (asbytes != orig) {
7385 /* String has been converted.
7386 There is no need to keep any reference to
7388 in = sv_newmortal();
7389 /* We donate the SV the malloc()ed string
7390 bytes_from_utf8 returned us. */
7391 SvUPGRADE(in, SVt_PV);
7393 SvPV_set(in, asbytes);
7394 SvLEN_set(in, klen_tmp);
7395 SvCUR_set(in, klen_tmp - 1);
7399 MBUF_SAVE_AND_LOAD(in);
7403 * Magic number verifications.
7405 * This needs to be done before calling init_retrieve_context()
7406 * since the format indication in the file are necessary to conduct
7407 * some of the initializations.
7410 cxt->fio = f; /* Where I/O are performed */
7412 if (!magic_check(aTHX_ cxt))
7413 CROAK(("Magic number checking on storable %s failed",
7414 cxt->fio ? "file" : "string"));
7416 TRACEME(("data stored in %s format",
7417 cxt->netorder ? "net order" : "native"));
7420 * Check whether input source is tainted, so that we don't wrongly
7421 * taint perfectly good values...
7423 * We assume file input is always tainted. If both 'f' and 'in' are
7424 * NULL, then we come from dclone, and tainted is already filled in
7425 * the context. That's a kludge, but the whole dclone() thing is
7426 * already quite a kludge anyway! -- RAM, 15/09/2000.
7429 is_tainted = f ? 1 : (in ? SvTAINTED(in) : cxt->s_tainted);
7430 TRACEME(("input source is %s", is_tainted ? "tainted" : "trusted"));
7431 init_retrieve_context(aTHX_ cxt, optype, is_tainted);
7433 ASSERT(is_retrieving(aTHX), ("within retrieve operation"));
7435 sv = retrieve(aTHX_ cxt, 0); /* Recursively retrieve object, get root SV */
7444 pre_06_fmt = cxt->hseen != NULL; /* Before we clean context */
7447 * The "root" context is never freed.
7450 clean_retrieve_context(aTHX_ cxt);
7451 if (cxt->prev) /* This context was stacked */
7452 free_context(aTHX_ cxt); /* It was not the "root" context */
7455 * Prepare returned value.
7459 TRACEMED(("retrieve ERROR"));
7460 return &PL_sv_undef; /* Something went wrong, return undef */
7463 TRACEMED(("retrieve got %s(0x%" UVxf ")",
7464 sv_reftype(sv, FALSE), PTR2UV(sv)));
7467 * Backward compatibility with Storable-0.5@9 (which we know we
7468 * are retrieving if hseen is non-null): don't create an extra RV
7469 * for objects since we special-cased it at store time.
7471 * Build a reference to the SV returned by pretrieve even if it is
7472 * already one and not a scalar, for consistency reasons.
7475 if (pre_06_fmt) { /* Was not handling overloading by then */
7477 TRACEMED(("fixing for old formats -- pre 0.6"));
7478 if (sv_type(aTHX_ sv) == svis_REF && (rv = SvRV(sv)) && SvOBJECT(rv)) {
7479 TRACEME(("ended do_retrieve() with an object -- pre 0.6"));
7485 * If reference is overloaded, restore behaviour.
7487 * NB: minor glitch here: normally, overloaded refs are stored specially
7488 * so that we can croak when behaviour cannot be re-installed, and also
7489 * avoid testing for overloading magic at each reference retrieval.
7491 * Unfortunately, the root reference is implicitly stored, so we must
7492 * check for possible overloading now. Furthermore, if we don't restore
7493 * overloading, we cannot croak as if the original ref was, because we
7494 * have no way to determine whether it was an overloaded ref or not in
7497 * It's a pity that overloading magic is attached to the rv, and not to
7498 * the underlying sv as blessing is.
7502 HV *stash = (HV *) SvSTASH(sv);
7503 SV *rv = newRV_noinc(sv);
7504 if (stash && Gv_AMG(stash)) {
7506 TRACEMED(("restored overloading on root reference"));
7508 TRACEMED(("ended do_retrieve() with an object"));
7512 TRACEMED(("regular do_retrieve() end"));
7514 return newRV_noinc(sv);
7520 * Retrieve data held in file and return the root object, undef on error.
7522 static SV *pretrieve(pTHX_ PerlIO *f, IV flag)
7524 TRACEMED(("pretrieve"));
7525 return do_retrieve(aTHX_ f, Nullsv, 0, (int)flag);
7531 * Retrieve data held in scalar and return the root object, undef on error.
7533 static SV *mretrieve(pTHX_ SV *sv, IV flag)
7535 TRACEMED(("mretrieve"));
7536 return do_retrieve(aTHX_ (PerlIO*) 0, sv, 0, (int)flag);
7546 * Deep clone: returns a fresh copy of the original referenced SV tree.
7548 * This is achieved by storing the object in memory and restoring from
7549 * there. Not that efficient, but it should be faster than doing it from
7552 static SV *dclone(pTHX_ SV *sv)
7556 stcxt_t *real_context;
7559 TRACEMED(("dclone"));
7562 * Workaround for CROAK leak: if they enter with a "dirty" context,
7563 * free up memory for them now.
7568 clean_context(aTHX_ cxt);
7571 * Tied elements seem to need special handling.
7574 if ((SvTYPE(sv) == SVt_PVLV
7575 #if PERL_VERSION_LT(5,8,0)
7576 || SvTYPE(sv) == SVt_PVMG
7578 ) && (SvFLAGS(sv) & (SVs_GMG|SVs_SMG|SVs_RMG)) ==
7579 (SVs_GMG|SVs_SMG|SVs_RMG) &&
7585 * do_store() optimizes for dclone by not freeing its context, should
7586 * we need to allocate one because we're deep cloning from a hook.
7589 if (!do_store(aTHX_ (PerlIO*) 0, sv, ST_CLONE, FALSE, (SV**) 0))
7590 return &PL_sv_undef; /* Error during store */
7593 * Because of the above optimization, we have to refresh the context,
7594 * since a new one could have been allocated and stacked by do_store().
7597 { dSTCXT; real_context = cxt; } /* Sub-block needed for macro */
7598 cxt = real_context; /* And we need this temporary... */
7601 * Now, 'cxt' may refer to a new context.
7605 ASSERT(!cxt->s_dirty, ("clean context"));
7606 ASSERT(!cxt->entry, ("entry will not cause new context allocation"));
7609 TRACEME(("dclone stored %ld bytes", (long)size));
7613 * Since we're passing do_retrieve() both a NULL file and sv, we need
7614 * to pre-compute the taintedness of the input by setting cxt->tainted
7615 * to whatever state our own input string was. -- RAM, 15/09/2000
7617 * do_retrieve() will free non-root context.
7620 cxt->s_tainted = SvTAINTED(sv);
7621 out = do_retrieve(aTHX_ (PerlIO*) 0, Nullsv, ST_CLONE, FLAG_BLESS_OK | FLAG_TIE_OK);
7623 TRACEMED(("dclone returns 0x%" UVxf, PTR2UV(out)));
7633 * The Perl IO GV object distinguishes between input and output for sockets
7634 * but not for plain files. To allow Storable to transparently work on
7635 * plain files and sockets transparently, we have to ask xsubpp to fetch the
7636 * right object for us. Hence the OutputStream and InputStream declarations.
7638 * Before perl 5.004_05, those entries in the standard typemap are not
7639 * defined in perl include files, so we do that here.
7642 #ifndef OutputStream
7643 #define OutputStream PerlIO *
7644 #define InputStream PerlIO *
7645 #endif /* !OutputStream */
7648 storable_free(pTHX_ SV *sv, MAGIC* mg) {
7649 stcxt_t *cxt = (stcxt_t *)SvPVX(sv);
7651 PERL_UNUSED_ARG(mg);
7652 #ifdef USE_PTR_TABLE
7654 ptr_table_free(cxt->pseen);
7658 if (!cxt->membuf_ro && mbase)
7660 if (cxt->membuf_ro && (cxt->msaved).arena)
7661 Safefree((cxt->msaved).arena);
7665 MODULE = Storable PACKAGE = Storable
7671 HV *stash = gv_stashpvn("Storable", 8, GV_ADD);
7672 newCONSTSUB(stash, "BIN_MAJOR", newSViv(STORABLE_BIN_MAJOR));
7673 newCONSTSUB(stash, "BIN_MINOR", newSViv(STORABLE_BIN_MINOR));
7674 newCONSTSUB(stash, "BIN_WRITE_MINOR", newSViv(STORABLE_BIN_WRITE_MINOR));
7676 newCONSTSUB(stash, "CAN_FLOCK", CAN_FLOCK);
7678 init_perinterp(aTHX);
7679 gv_fetchpv("Storable::drop_utf8", GV_ADDMULTI, SVt_PV);
7681 /* Only disable the used only once warning if we are in debugging mode. */
7682 gv_fetchpv("Storable::DEBUGME", GV_ADDMULTI, SVt_PV);
7684 #ifdef USE_56_INTERWORK_KLUDGE
7685 gv_fetchpv("Storable::interwork_56_64bit", GV_ADDMULTI, SVt_PV);
7692 init_perinterp(aTHX);
7696 # Store the transitive data closure of given object to disk.
7697 # Returns undef on error, a true value otherwise.
7701 # Same as pstore(), but network order is used for integers and doubles are
7702 # emitted as strings.
7711 RETVAL = do_store(aTHX_ f, obj, 0, ix, (SV **)0) ? &PL_sv_yes : &PL_sv_undef;
7712 /* do_store() can reallocate the stack, so need a sequence point to ensure
7713 that ST(0) knows about it. Hence using two statements. */
7719 # Store the transitive data closure of given object to memory.
7720 # Returns undef on error, a scalar value containing the data otherwise.
7724 # Same as mstore(), but network order is used for integers and doubles are
7725 # emitted as strings.
7733 RETVAL = &PL_sv_undef;
7734 if (!do_store(aTHX_ (PerlIO*) 0, obj, 0, ix, &RETVAL))
7735 RETVAL = &PL_sv_undef;
7740 pretrieve(f, flag = 6)
7744 RETVAL = pretrieve(aTHX_ f, flag);
7749 mretrieve(sv, flag = 6)
7753 RETVAL = mretrieve(aTHX_ sv, flag);
7761 RETVAL = dclone(aTHX_ sv);
7766 last_op_in_netorder()
7768 is_storing = ST_STORE
7769 is_retrieving = ST_RETRIEVE
7776 result = cxt->entry && (cxt->optype & ix) ? TRUE : FALSE;
7778 result = !!last_op_in_netorder(aTHX);
7780 ST(0) = boolSV(result);
7786 RETVAL = SvIV(get_sv("Storable::recursion_limit", GV_ADD));
7793 RETVAL = SvIV(get_sv("Storable::recursion_limit_hash", GV_ADD));