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 */
20 # define NEED_PL_parser
21 # define NEED_sv_2pv_flags
22 # define NEED_load_module
23 # define NEED_vload_module
24 # define NEED_newCONSTSUB
25 # define NEED_newSVpvn_flags
26 # define NEED_newRV_noinc
27 #include "ppport.h" /* handle old perls */
31 #define DEBUGME /* Debug mode, turns assertions on as well */
32 #define DASSERT /* Assertion mode */
36 * Earlier versions of perl might be used, we can't assume they have the latest!
39 /* perl <= 5.8.2 needs this */
41 # define SvIsCOW(sv) 0
45 # define HvRITER_set(hv,r) (HvRITER(hv) = r)
48 # define HvEITER_set(hv,r) (HvEITER(hv) = r)
52 # define HvRITER_get HvRITER
55 # define HvEITER_get HvEITER
58 #ifndef HvPLACEHOLDERS_get
59 # define HvPLACEHOLDERS_get HvPLACEHOLDERS
63 # define HvTOTALKEYS(hv) HvKEYS(hv)
67 # define HvUSEDKEYS(hv) HvKEYS(hv)
71 # define SvTRULYREADONLY(sv) SvREADONLY(sv)
73 # define SvTRULYREADONLY(sv) (SvREADONLY(sv) && !SvIsCOW(sv))
77 # define strEQc(s,c) memEQ(s, ("" c ""), sizeof(c))
80 #if defined(HAS_FLOCK) || defined(FCNTL_CAN_LOCK) && defined(HAS_LOCKF)
81 #define CAN_FLOCK &PL_sv_yes
83 #define CAN_FLOCK &PL_sv_no
93 * TRACEME() will only output things when the $Storable::DEBUGME is true,
94 * using the value traceme cached in the context.
97 * TRACEMED() directly looks at the variable, for use before traceme has been
104 { PerlIO_stdoutf x; PerlIO_stdoutf("\n"); } \
107 #define TRACEMED(x) \
109 if (SvTRUE(get_sv("Storable::DEBUGME", GV_ADD))) \
110 { PerlIO_stdoutf x; PerlIO_stdoutf("\n"); } \
113 #define INIT_TRACEME \
115 cxt->traceme = SvTRUE(get_sv("Storable::DEBUGME", GV_ADD)); \
125 #define ASSERT(x,y) \
128 PerlIO_stdoutf("ASSERT FAILED (\"%s\", line %d): ", \
129 __FILE__, (int)__LINE__); \
130 PerlIO_stdoutf y; PerlIO_stdoutf("\n"); \
141 #define C(x) ((char) (x)) /* For markers with dynamic retrieval handling */
143 #define SX_OBJECT C(0) /* Already stored object */
144 #define SX_LSCALAR C(1) /* Scalar (large binary) follows (length, data) */
145 #define SX_ARRAY C(2) /* Array forthcoming (size, item list) */
146 #define SX_HASH C(3) /* Hash forthcoming (size, key/value pair list) */
147 #define SX_REF C(4) /* Reference to object forthcoming */
148 #define SX_UNDEF C(5) /* Undefined scalar */
149 #define SX_INTEGER C(6) /* Integer forthcoming */
150 #define SX_DOUBLE C(7) /* Double forthcoming */
151 #define SX_BYTE C(8) /* (signed) byte forthcoming */
152 #define SX_NETINT C(9) /* Integer in network order forthcoming */
153 #define SX_SCALAR C(10) /* Scalar (binary, small) follows (length, data) */
154 #define SX_TIED_ARRAY C(11) /* Tied array forthcoming */
155 #define SX_TIED_HASH C(12) /* Tied hash forthcoming */
156 #define SX_TIED_SCALAR C(13) /* Tied scalar forthcoming */
157 #define SX_SV_UNDEF C(14) /* Perl's immortal PL_sv_undef */
158 #define SX_SV_YES C(15) /* Perl's immortal PL_sv_yes */
159 #define SX_SV_NO C(16) /* Perl's immortal PL_sv_no */
160 #define SX_BLESS C(17) /* Object is blessed */
161 #define SX_IX_BLESS C(18) /* Object is blessed, classname given by index */
162 #define SX_HOOK C(19) /* Stored via hook, user-defined */
163 #define SX_OVERLOAD C(20) /* Overloaded reference */
164 #define SX_TIED_KEY C(21) /* Tied magic key forthcoming */
165 #define SX_TIED_IDX C(22) /* Tied magic index forthcoming */
166 #define SX_UTF8STR C(23) /* UTF-8 string forthcoming (small) */
167 #define SX_LUTF8STR C(24) /* UTF-8 string forthcoming (large) */
168 #define SX_FLAG_HASH C(25) /* Hash with flags forthcoming (size, flags, key/flags/value triplet list) */
169 #define SX_CODE C(26) /* Code references as perl source code */
170 #define SX_WEAKREF C(27) /* Weak reference to object forthcoming */
171 #define SX_WEAKOVERLOAD C(28) /* Overloaded weak reference */
172 #define SX_VSTRING C(29) /* vstring forthcoming (small) */
173 #define SX_LVSTRING C(30) /* vstring forthcoming (large) */
174 #define SX_SVUNDEF_ELEM C(31) /* array element set to &PL_sv_undef */
175 #define SX_REGEXP C(32) /* Regexp */
176 #define SX_LOBJECT C(33) /* Large object: string, array or hash (size >2G) */
177 #define SX_BOOLEAN_TRUE C(34) /* Boolean true */
178 #define SX_BOOLEAN_FALSE C(35) /* Boolean false */
179 #define SX_LAST C(36) /* 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 12 /* 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, HEK *hek, 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_BOOLEAN_TRUE not supported */
1458 (sv_retrieve_t)retrieve_other, /* SX_BOOLEAN_FALSE not supported */
1459 (sv_retrieve_t)retrieve_other, /* SX_LAST */
1462 static SV *retrieve_hook_common(pTHX_ stcxt_t *cxt, const char *cname, int large);
1464 static SV *retrieve_array(pTHX_ stcxt_t *cxt, const char *cname);
1465 static SV *retrieve_hash(pTHX_ stcxt_t *cxt, const char *cname);
1466 static SV *retrieve_sv_undef(pTHX_ stcxt_t *cxt, const char *cname);
1467 static SV *retrieve_sv_yes(pTHX_ stcxt_t *cxt, const char *cname);
1468 static SV *retrieve_sv_no(pTHX_ stcxt_t *cxt, const char *cname);
1469 static SV *retrieve_blessed(pTHX_ stcxt_t *cxt, const char *cname);
1470 static SV *retrieve_idx_blessed(pTHX_ stcxt_t *cxt, const char *cname);
1471 static SV *retrieve_hook(pTHX_ stcxt_t *cxt, const char *cname);
1472 static SV *retrieve_overloaded(pTHX_ stcxt_t *cxt, const char *cname);
1473 static SV *retrieve_tied_key(pTHX_ stcxt_t *cxt, const char *cname);
1474 static SV *retrieve_tied_idx(pTHX_ stcxt_t *cxt, const char *cname);
1475 static SV *retrieve_flag_hash(pTHX_ stcxt_t *cxt, const char *cname);
1476 static SV *retrieve_code(pTHX_ stcxt_t *cxt, const char *cname);
1477 static SV *retrieve_weakref(pTHX_ stcxt_t *cxt, const char *cname);
1478 static SV *retrieve_weakoverloaded(pTHX_ stcxt_t *cxt, const char *cname);
1479 static SV *retrieve_vstring(pTHX_ stcxt_t *cxt, const char *cname);
1480 static SV *retrieve_lvstring(pTHX_ stcxt_t *cxt, const char *cname);
1481 static SV *retrieve_svundef_elem(pTHX_ stcxt_t *cxt, const char *cname);
1482 static SV *retrieve_boolean_true(pTHX_ stcxt_t *cxt, const char *cname);
1483 static SV *retrieve_boolean_false(pTHX_ stcxt_t *cxt, const char *cname);
1485 static const sv_retrieve_t sv_retrieve[] = {
1486 0, /* SX_OBJECT -- entry unused dynamically */
1487 (sv_retrieve_t)retrieve_lscalar, /* SX_LSCALAR */
1488 (sv_retrieve_t)retrieve_array, /* SX_ARRAY */
1489 (sv_retrieve_t)retrieve_hash, /* SX_HASH */
1490 (sv_retrieve_t)retrieve_ref, /* SX_REF */
1491 (sv_retrieve_t)retrieve_undef, /* SX_UNDEF */
1492 (sv_retrieve_t)retrieve_integer, /* SX_INTEGER */
1493 (sv_retrieve_t)retrieve_double, /* SX_DOUBLE */
1494 (sv_retrieve_t)retrieve_byte, /* SX_BYTE */
1495 (sv_retrieve_t)retrieve_netint, /* SX_NETINT */
1496 (sv_retrieve_t)retrieve_scalar, /* SX_SCALAR */
1497 (sv_retrieve_t)retrieve_tied_array, /* SX_TIED_ARRAY */
1498 (sv_retrieve_t)retrieve_tied_hash, /* SX_TIED_HASH */
1499 (sv_retrieve_t)retrieve_tied_scalar,/* SX_TIED_SCALAR */
1500 (sv_retrieve_t)retrieve_sv_undef, /* SX_SV_UNDEF */
1501 (sv_retrieve_t)retrieve_sv_yes, /* SX_SV_YES */
1502 (sv_retrieve_t)retrieve_sv_no, /* SX_SV_NO */
1503 (sv_retrieve_t)retrieve_blessed, /* SX_BLESS */
1504 (sv_retrieve_t)retrieve_idx_blessed,/* SX_IX_BLESS */
1505 (sv_retrieve_t)retrieve_hook, /* SX_HOOK */
1506 (sv_retrieve_t)retrieve_overloaded, /* SX_OVERLOAD */
1507 (sv_retrieve_t)retrieve_tied_key, /* SX_TIED_KEY */
1508 (sv_retrieve_t)retrieve_tied_idx, /* SX_TIED_IDX */
1509 (sv_retrieve_t)retrieve_utf8str, /* SX_UTF8STR */
1510 (sv_retrieve_t)retrieve_lutf8str, /* SX_LUTF8STR */
1511 (sv_retrieve_t)retrieve_flag_hash, /* SX_HASH */
1512 (sv_retrieve_t)retrieve_code, /* SX_CODE */
1513 (sv_retrieve_t)retrieve_weakref, /* SX_WEAKREF */
1514 (sv_retrieve_t)retrieve_weakoverloaded,/* SX_WEAKOVERLOAD */
1515 (sv_retrieve_t)retrieve_vstring, /* SX_VSTRING */
1516 (sv_retrieve_t)retrieve_lvstring, /* SX_LVSTRING */
1517 (sv_retrieve_t)retrieve_svundef_elem,/* SX_SVUNDEF_ELEM */
1518 (sv_retrieve_t)retrieve_regexp, /* SX_REGEXP */
1519 (sv_retrieve_t)retrieve_lobject, /* SX_LOBJECT */
1520 (sv_retrieve_t)retrieve_boolean_true, /* SX_BOOLEAN_TRUE */
1521 (sv_retrieve_t)retrieve_boolean_false, /* SX_BOOLEAN_FALSE */
1522 (sv_retrieve_t)retrieve_other, /* SX_LAST */
1525 #define RETRIEVE(c,x) ((x) >= SX_LAST ? retrieve_other : *(c)->retrieve_vtbl[x])
1527 static SV *mbuf2sv(pTHX);
1530 *** Context management.
1536 * Called once per "thread" (interpreter) to initialize some global context.
1538 static void init_perinterp(pTHX)
1542 cxt->netorder = 0; /* true if network order used */
1543 cxt->forgive_me = -1; /* whether to be forgiving... */
1544 cxt->accept_future_minor = -1; /* would otherwise occur too late */
1550 * Called at the end of every context cleaning, to perform common reset
1553 static void reset_context(stcxt_t *cxt)
1557 cxt->recur_sv = NULL;
1558 cxt->recur_depth = 0;
1559 cxt->optype &= ~(ST_STORE|ST_RETRIEVE); /* Leave ST_CLONE alone */
1563 * init_store_context
1565 * Initialize a new store context for real recursion.
1567 static void init_store_context(pTHX_
1575 TRACEME(("init_store_context"));
1577 cxt->netorder = network_order;
1578 cxt->forgive_me = -1; /* Fetched from perl if needed */
1579 cxt->deparse = -1; /* Idem */
1580 cxt->eval = NULL; /* Idem */
1581 cxt->canonical = -1; /* Idem */
1582 cxt->tagnum = -1; /* Reset tag numbers */
1583 cxt->classnum = -1; /* Reset class numbers */
1584 cxt->fio = f; /* Where I/O are performed */
1585 cxt->optype = optype; /* A store, or a deep clone */
1586 cxt->entry = 1; /* No recursion yet */
1589 * The 'hseen' table is used to keep track of each SV stored and their
1590 * associated tag numbers is special. It is "abused" because the
1591 * values stored are not real SV, just integers cast to (SV *),
1592 * which explains the freeing below.
1594 * It is also one possible bottleneck to achieve good storing speed,
1595 * so the "shared keys" optimization is turned off (unlikely to be
1596 * of any use here), and the hash table is "pre-extended". Together,
1597 * those optimizations increase the throughput by 12%.
1600 #ifdef USE_PTR_TABLE
1601 cxt->pseen = ptr_table_new();
1604 cxt->hseen = newHV(); /* Table where seen objects are stored */
1605 HvSHAREKEYS_off(cxt->hseen);
1608 * The following does not work well with perl5.004_04, and causes
1609 * a core dump later on, in a completely unrelated spot, which
1610 * makes me think there is a memory corruption going on.
1612 * Calling hv_ksplit(hseen, HBUCKETS) instead of manually hacking
1613 * it below does not make any difference. It seems to work fine
1614 * with perl5.004_68 but given the probable nature of the bug,
1615 * that does not prove anything.
1617 * It's a shame because increasing the amount of buckets raises
1618 * store() throughput by 5%, but until I figure this out, I can't
1619 * allow for this to go into production.
1621 * It is reported fixed in 5.005, hence the #if.
1623 #define HBUCKETS 4096 /* Buckets for %hseen */
1624 #ifndef USE_PTR_TABLE
1625 HvMAX(cxt->hseen) = HBUCKETS - 1; /* keys %hseen = $HBUCKETS; */
1629 * The 'hclass' hash uses the same settings as 'hseen' above, but it is
1630 * used to assign sequential tags (numbers) to class names for blessed
1633 * We turn the shared key optimization on.
1636 cxt->hclass = newHV(); /* Where seen classnames are stored */
1638 HvMAX(cxt->hclass) = HBUCKETS - 1; /* keys %hclass = $HBUCKETS; */
1641 * The 'hook' hash table is used to keep track of the references on
1642 * the STORABLE_freeze hook routines, when found in some class name.
1644 * It is assumed that the inheritance tree will not be changed during
1645 * storing, and that no new method will be dynamically created by the
1649 cxt->hook = newHV(); /* Table where hooks are cached */
1652 * The 'hook_seen' array keeps track of all the SVs returned by
1653 * STORABLE_freeze hooks for us to serialize, so that they are not
1654 * reclaimed until the end of the serialization process. Each SV is
1655 * only stored once, the first time it is seen.
1658 cxt->hook_seen = newAV(); /* Lists SVs returned by STORABLE_freeze */
1660 cxt->max_recur_depth = SvIV(get_sv("Storable::recursion_limit", GV_ADD));
1661 cxt->max_recur_depth_hash = SvIV(get_sv("Storable::recursion_limit_hash", GV_ADD));
1665 * clean_store_context
1667 * Clean store context by
1669 static void clean_store_context(pTHX_ stcxt_t *cxt)
1673 TRACEMED(("clean_store_context"));
1675 ASSERT(cxt->optype & ST_STORE, ("was performing a store()"));
1678 * Insert real values into hashes where we stored faked pointers.
1681 #ifndef USE_PTR_TABLE
1683 hv_iterinit(cxt->hseen);
1684 while ((he = hv_iternext(cxt->hseen))) /* Extra () for -Wall */
1685 HeVAL(he) = &PL_sv_undef;
1690 hv_iterinit(cxt->hclass);
1691 while ((he = hv_iternext(cxt->hclass))) /* Extra () for -Wall */
1692 HeVAL(he) = &PL_sv_undef;
1696 * And now dispose of them...
1698 * The surrounding if() protection has been added because there might be
1699 * some cases where this routine is called more than once, during
1700 * exceptional events. This was reported by Marc Lehmann when Storable
1701 * is executed from mod_perl, and the fix was suggested by him.
1702 * -- RAM, 20/12/2000
1705 #ifdef USE_PTR_TABLE
1707 struct ptr_tbl *pseen = cxt->pseen;
1709 ptr_table_free(pseen);
1711 assert(!cxt->hseen);
1714 HV *hseen = cxt->hseen;
1717 sv_free((SV *) hseen);
1722 HV *hclass = cxt->hclass;
1725 sv_free((SV *) hclass);
1729 HV *hook = cxt->hook;
1732 sv_free((SV *) hook);
1735 if (cxt->hook_seen) {
1736 AV *hook_seen = cxt->hook_seen;
1738 av_undef(hook_seen);
1739 sv_free((SV *) hook_seen);
1742 cxt->forgive_me = -1; /* Fetched from perl if needed */
1743 cxt->deparse = -1; /* Idem */
1745 SvREFCNT_dec(cxt->eval);
1747 cxt->eval = NULL; /* Idem */
1748 cxt->canonical = -1; /* Idem */
1754 * init_retrieve_context
1756 * Initialize a new retrieve context for real recursion.
1758 static void init_retrieve_context(pTHX_
1759 stcxt_t *cxt, int optype, int is_tainted)
1763 TRACEME(("init_retrieve_context"));
1766 * The hook hash table is used to keep track of the references on
1767 * the STORABLE_thaw hook routines, when found in some class name.
1769 * It is assumed that the inheritance tree will not be changed during
1770 * storing, and that no new method will be dynamically created by the
1774 cxt->hook = newHV(); /* Caches STORABLE_thaw */
1776 #ifdef USE_PTR_TABLE
1781 * If retrieving an old binary version, the cxt->retrieve_vtbl variable
1782 * was set to sv_old_retrieve. We'll need a hash table to keep track of
1783 * the correspondence between the tags and the tag number used by the
1784 * new retrieve routines.
1787 cxt->hseen = (((void*)cxt->retrieve_vtbl == (void*)sv_old_retrieve)
1790 cxt->aseen = newAV(); /* Where retrieved objects are kept */
1791 cxt->where_is_undef = UNSET_NTAG_T; /* Special case for PL_sv_undef */
1792 cxt->aclass = newAV(); /* Where seen classnames are kept */
1793 cxt->tagnum = 0; /* Have to count objects... */
1794 cxt->classnum = 0; /* ...and class names as well */
1795 cxt->optype = optype;
1796 cxt->s_tainted = is_tainted;
1797 cxt->entry = 1; /* No recursion yet */
1798 #ifndef HAS_RESTRICTED_HASHES
1799 cxt->derestrict = -1; /* Fetched from perl if needed */
1801 #ifndef HAS_UTF8_ALL
1802 cxt->use_bytes = -1; /* Fetched from perl if needed */
1804 cxt->accept_future_minor = -1;/* Fetched from perl if needed */
1805 cxt->in_retrieve_overloaded = 0;
1807 cxt->max_recur_depth = SvIV(get_sv("Storable::recursion_limit", GV_ADD));
1808 cxt->max_recur_depth_hash = SvIV(get_sv("Storable::recursion_limit_hash", GV_ADD));
1812 * clean_retrieve_context
1814 * Clean retrieve context by
1816 static void clean_retrieve_context(pTHX_ stcxt_t *cxt)
1818 TRACEMED(("clean_retrieve_context"));
1820 ASSERT(cxt->optype & ST_RETRIEVE, ("was performing a retrieve()"));
1823 AV *aseen = cxt->aseen;
1826 sv_free((SV *) aseen);
1828 cxt->where_is_undef = UNSET_NTAG_T;
1831 AV *aclass = cxt->aclass;
1834 sv_free((SV *) aclass);
1838 HV *hook = cxt->hook;
1841 sv_free((SV *) hook);
1845 HV *hseen = cxt->hseen;
1848 sv_free((SV *) hseen); /* optional HV, for backward compat. */
1851 #ifndef HAS_RESTRICTED_HASHES
1852 cxt->derestrict = -1; /* Fetched from perl if needed */
1854 #ifndef HAS_UTF8_ALL
1855 cxt->use_bytes = -1; /* Fetched from perl if needed */
1857 cxt->accept_future_minor = -1; /* Fetched from perl if needed */
1859 cxt->in_retrieve_overloaded = 0;
1866 * A workaround for the CROAK bug: cleanup the last context.
1868 static void clean_context(pTHX_ stcxt_t *cxt)
1870 TRACEMED(("clean_context"));
1872 ASSERT(cxt->s_dirty, ("dirty context"));
1877 ASSERT(!cxt->membuf_ro, ("mbase is not read-only"));
1879 if (cxt->optype & ST_RETRIEVE)
1880 clean_retrieve_context(aTHX_ cxt);
1881 else if (cxt->optype & ST_STORE)
1882 clean_store_context(aTHX_ cxt);
1886 ASSERT(!cxt->s_dirty, ("context is clean"));
1887 ASSERT(cxt->entry == 0, ("context is reset"));
1893 * Allocate a new context and push it on top of the parent one.
1894 * This new context is made globally visible via SET_STCXT().
1896 static stcxt_t *allocate_context(pTHX_ stcxt_t *parent_cxt)
1900 ASSERT(!parent_cxt->s_dirty, ("parent context clean"));
1902 NEW_STORABLE_CXT_OBJ(cxt);
1903 TRACEMED(("allocate_context"));
1905 cxt->prev = parent_cxt->my_sv;
1908 ASSERT(!cxt->s_dirty, ("clean context"));
1916 * Free current context, which cannot be the "root" one.
1917 * Make the context underneath globally visible via SET_STCXT().
1919 static void free_context(pTHX_ stcxt_t *cxt)
1921 stcxt_t *prev = (stcxt_t *)(cxt->prev ? SvPVX(SvRV(cxt->prev)) : 0);
1923 TRACEMED(("free_context"));
1925 ASSERT(!cxt->s_dirty, ("clean context"));
1926 ASSERT(prev, ("not freeing root context"));
1929 SvREFCNT_dec(cxt->my_sv);
1932 ASSERT(cxt, ("context not void"));
1939 /* these two functions are currently only used within asserts */
1944 * Tells whether we're in the middle of a store operation.
1946 static int is_storing(pTHX)
1950 return cxt->entry && (cxt->optype & ST_STORE);
1956 * Tells whether we're in the middle of a retrieve operation.
1958 static int is_retrieving(pTHX)
1962 return cxt->entry && (cxt->optype & ST_RETRIEVE);
1967 * last_op_in_netorder
1969 * Returns whether last operation was made using network order.
1971 * This is typically out-of-band information that might prove useful
1972 * to people wishing to convert native to network order data when used.
1974 static int last_op_in_netorder(pTHX)
1979 return cxt->netorder;
1983 *** Hook lookup and calling routines.
1989 * A wrapper on gv_fetchmethod_autoload() which caches results.
1991 * Returns the routine reference as an SV*, or null if neither the package
1992 * nor its ancestors know about the method.
1994 static SV *pkg_fetchmeth(pTHX_
2001 const char *hvname = HvNAME_get(pkg);
2007 * The following code is the same as the one performed by UNIVERSAL::can
2011 gv = gv_fetchmethod_autoload(pkg, method, FALSE);
2012 if (gv && isGV(gv)) {
2013 sv = newRV_inc((SV*) GvCV(gv));
2014 TRACEME(("%s->%s: 0x%" UVxf, hvname, method, PTR2UV(sv)));
2016 sv = newSVsv(&PL_sv_undef);
2017 TRACEME(("%s->%s: not found", hvname, method));
2021 * Cache the result, ignoring failure: if we can't store the value,
2022 * it just won't be cached.
2025 (void) hv_store(cache, hvname, strlen(hvname), sv, 0);
2027 return SvOK(sv) ? sv : (SV *) 0;
2033 * Force cached value to be undef: hook ignored even if present.
2035 static void pkg_hide(pTHX_
2040 const char *hvname = HvNAME_get(pkg);
2041 PERL_UNUSED_ARG(method);
2042 (void) hv_store(cache,
2043 hvname, strlen(hvname), newSVsv(&PL_sv_undef), 0);
2049 * Discard cached value: a whole fetch loop will be retried at next lookup.
2051 static void pkg_uncache(pTHX_
2056 const char *hvname = HvNAME_get(pkg);
2057 PERL_UNUSED_ARG(method);
2058 (void) hv_delete(cache, hvname, strlen(hvname), G_DISCARD);
2064 * Our own "UNIVERSAL::can", which caches results.
2066 * Returns the routine reference as an SV*, or null if the object does not
2067 * know about the method.
2069 static SV *pkg_can(pTHX_
2076 const char *hvname = HvNAME_get(pkg);
2081 TRACEME(("pkg_can for %s->%s", hvname, method));
2084 * Look into the cache to see whether we already have determined
2085 * where the routine was, if any.
2087 * NOTA BENE: we don't use 'method' at all in our lookup, since we know
2088 * that only one hook (i.e. always the same) is cached in a given cache.
2091 svh = hv_fetch(cache, hvname, strlen(hvname), FALSE);
2095 TRACEME(("cached %s->%s: not found", hvname, method));
2098 TRACEME(("cached %s->%s: 0x%" UVxf,
2099 hvname, method, PTR2UV(sv)));
2104 TRACEME(("not cached yet"));
2105 return pkg_fetchmeth(aTHX_ cache, pkg, method); /* Fetch and cache */
2111 * Call routine as obj->hook(av) in scalar context.
2112 * Propagates the single returned value if not called in void context.
2114 static SV *scalar_call(pTHX_
2128 TRACEME(("scalar_call (cloning=%d)", cloning));
2135 XPUSHs(sv_2mortal(newSViv(cloning))); /* Cloning flag */
2137 SV **ary = AvARRAY(av);
2138 SSize_t cnt = AvFILLp(av) + 1;
2140 XPUSHs(ary[0]); /* Frozen string */
2141 for (i = 1; i < cnt; i++) {
2142 TRACEME(("pushing arg #%d (0x%" UVxf ")...",
2143 (int)i, PTR2UV(ary[i])));
2144 XPUSHs(sv_2mortal(newRV_inc(ary[i])));
2149 TRACEME(("calling..."));
2150 count = call_sv(hook, flags); /* Go back to Perl code */
2151 TRACEME(("count = %d", count));
2157 SvREFCNT_inc(sv); /* We're returning it, must stay alive! */
2170 * Call routine obj->hook(cloning) in list context.
2171 * Returns the list of returned values in an array.
2173 static AV *array_call(pTHX_
2186 TRACEME(("array_call (cloning=%d)", cloning));
2192 XPUSHs(obj); /* Target object */
2193 XPUSHs(sv_2mortal(newSViv(cloning))); /* Cloning flag */
2196 count = call_sv(hook, G_LIST); /* Go back to Perl code */
2201 for (i = count - 1; i >= 0; i--) {
2203 av_store(av, i, SvREFCNT_inc(sv));
2213 #if PERL_VERSION_LT(5,15,0)
2215 cleanup_recursive_av(pTHX_ AV* av) {
2216 SSize_t i = AvFILLp(av);
2217 SV** arr = AvARRAY(av);
2218 if (SvMAGICAL(av)) return;
2221 #if PERL_VERSION_LT(5,14,0)
2224 SvREFCNT_dec(arr[i]);
2231 #ifndef SvREFCNT_IMMORTAL
2233 /* exercise the immortal resurrection code in sv_free2() */
2234 # define SvREFCNT_IMMORTAL 1000
2236 # define SvREFCNT_IMMORTAL ((~(U32)0)/2)
2241 cleanup_recursive_hv(pTHX_ HV* hv) {
2242 SSize_t i = HvTOTALKEYS(hv);
2243 HE** arr = HvARRAY(hv);
2244 if (SvMAGICAL(hv)) return;
2247 SvREFCNT(HeVAL(arr[i])) = SvREFCNT_IMMORTAL;
2248 arr[i] = NULL; /* let it leak. too dangerous to clean it up here */
2252 #if PERL_VERSION_LT(5,8,0)
2253 ((XPVHV*)SvANY(hv))->xhv_array = NULL;
2257 HvTOTALKEYS(hv) = 0;
2260 cleanup_recursive_rv(pTHX_ SV* sv) {
2261 if (sv && SvROK(sv))
2262 SvREFCNT_dec(SvRV(sv));
2265 cleanup_recursive_data(pTHX_ SV* sv) {
2266 if (SvTYPE(sv) == SVt_PVAV) {
2267 cleanup_recursive_av(aTHX_ (AV*)sv);
2269 else if (SvTYPE(sv) == SVt_PVHV) {
2270 cleanup_recursive_hv(aTHX_ (HV*)sv);
2273 cleanup_recursive_rv(aTHX_ sv);
2281 * Lookup the class name in the 'hclass' table and either assign it a new ID
2282 * or return the existing one, by filling in 'classnum'.
2284 * Return true if the class was known, false if the ID was just generated.
2286 static int known_class(pTHX_
2288 char *name, /* Class name */
2289 int len, /* Name length */
2293 HV *hclass = cxt->hclass;
2295 TRACEME(("known_class (%s)", name));
2298 * Recall that we don't store pointers in this hash table, but tags.
2299 * Therefore, we need LOW_32BITS() to extract the relevant parts.
2302 svh = hv_fetch(hclass, name, len, FALSE);
2304 *classnum = LOW_32BITS(*svh);
2309 * Unknown classname, we need to record it.
2313 if (!hv_store(hclass, name, len, INT2PTR(SV*, cxt->classnum), 0))
2314 CROAK(("Unable to record new classname"));
2316 *classnum = cxt->classnum;
2321 *** Specific store routines.
2327 * Store a reference.
2328 * Layout is SX_REF <object> or SX_OVERLOAD <object>.
2330 static int store_ref(pTHX_ stcxt_t *cxt, SV *sv)
2334 TRACEME(("store_ref (0x%" UVxf ")", PTR2UV(sv)));
2337 * Follow reference, and check if target is overloaded.
2343 TRACEME(("ref (0x%" UVxf ") is%s weak", PTR2UV(sv),
2344 is_weak ? "" : "n't"));
2349 HV *stash = (HV *) SvSTASH(sv);
2350 if (stash && Gv_AMG(stash)) {
2351 TRACEME(("ref (0x%" UVxf ") is overloaded", PTR2UV(sv)));
2352 PUTMARK(is_weak ? SX_WEAKOVERLOAD : SX_OVERLOAD);
2354 PUTMARK(is_weak ? SX_WEAKREF : SX_REF);
2356 PUTMARK(is_weak ? SX_WEAKREF : SX_REF);
2360 TRACEME((">ref recur_depth %" IVdf ", recur_sv (0x%" UVxf ") max %" IVdf, cxt->recur_depth,
2361 PTR2UV(cxt->recur_sv), cxt->max_recur_depth));
2362 if (RECURSION_TOO_DEEP()) {
2363 #if PERL_VERSION_LT(5,15,0)
2364 cleanup_recursive_data(aTHX_ (SV*)sv);
2366 CROAK((MAX_DEPTH_ERROR));
2369 retval = store(aTHX_ cxt, sv);
2370 if (cxt->max_recur_depth != -1 && cxt->recur_depth > 0) {
2371 TRACEME(("<ref recur_depth --%" IVdf, cxt->recur_depth));
2382 * Layout is SX_LSCALAR <length> <data>, SX_SCALAR <length> <data> or SX_UNDEF.
2383 * SX_LUTF8STR and SX_UTF8STR are used for UTF-8 strings.
2384 * The <data> section is omitted if <length> is 0.
2386 * For vstrings, the vstring portion is stored first with
2387 * SX_LVSTRING <length> <data> or SX_VSTRING <length> <data>, followed by
2388 * SX_(L)SCALAR or SX_(L)UTF8STR with the actual PV.
2390 * If integer or double, the layout is SX_INTEGER <data> or SX_DOUBLE <data>.
2391 * Small integers (within [-127, +127]) are stored as SX_BYTE <byte>.
2393 * For huge strings use SX_LOBJECT SX_type SX_U64 <type> <data>
2395 static int store_scalar(pTHX_ stcxt_t *cxt, SV *sv)
2400 U32 flags = SvFLAGS(sv); /* "cc -O" may put it in register */
2402 TRACEME(("store_scalar (0x%" UVxf ")", PTR2UV(sv)));
2405 * For efficiency, break the SV encapsulation by peaking at the flags
2406 * directly without using the Perl macros to avoid dereferencing
2407 * sv->sv_flags each time we wish to check the flags.
2410 if (!(flags & SVf_OK)) { /* !SvOK(sv) */
2411 if (sv == &PL_sv_undef) {
2412 TRACEME(("immortal undef"));
2413 PUTMARK(SX_SV_UNDEF);
2415 TRACEME(("undef at 0x%" UVxf, PTR2UV(sv)));
2422 * Always store the string representation of a scalar if it exists.
2423 * Gisle Aas provided me with this test case, better than a long speach:
2425 * perl -MDevel::Peek -le '$a="abc"; $a+0; Dump($a)'
2426 * SV = PVNV(0x80c8520)
2428 * FLAGS = (NOK,POK,pNOK,pPOK)
2431 * PV = 0x80c83d0 "abc"\0
2435 * Write SX_SCALAR, length, followed by the actual data.
2437 * Otherwise, write an SX_BYTE, SX_INTEGER or an SX_DOUBLE as
2438 * appropriate, followed by the actual (binary) data. A double
2439 * is written as a string if network order, for portability.
2441 * NOTE: instead of using SvNOK(sv), we test for SvNOKp(sv).
2442 * The reason is that when the scalar value is tainted, the SvNOK(sv)
2445 * The test for a read-only scalar with both POK and NOK set is meant
2446 * to quickly detect &PL_sv_yes and &PL_sv_no without having to pay the
2447 * address comparison for each scalar we store.
2450 #define SV_MAYBE_IMMORTAL (SVf_READONLY|SVf_POK|SVf_NOK)
2452 if ((flags & SV_MAYBE_IMMORTAL) == SV_MAYBE_IMMORTAL) {
2453 if (sv == &PL_sv_yes) {
2454 TRACEME(("immortal yes"));
2456 } else if (sv == &PL_sv_no) {
2457 TRACEME(("immortal no"));
2460 pv = SvPV(sv, len); /* We know it's SvPOK */
2461 goto string; /* Share code below */
2464 } else if (SvIsBOOL(sv)) {
2465 TRACEME(("mortal boolean"));
2466 if (SvTRUE_nomg_NN(sv)) {
2467 PUTMARK(SX_BOOLEAN_TRUE);
2470 PUTMARK(SX_BOOLEAN_FALSE);
2473 } else if (flags & SVf_POK) {
2474 /* public string - go direct to string read. */
2475 goto string_readlen;
2477 #if PERL_VERSION_LT(5,7,0)
2478 /* For 5.6 and earlier NV flag trumps IV flag, so only use integer
2479 direct if NV flag is off. */
2480 (flags & (SVf_NOK | SVf_IOK)) == SVf_IOK
2482 /* 5.7 rules are that if IV public flag is set, IV value is as
2483 good, if not better, than NV value. */
2489 * Will come here from below with iv set if double is an integer.
2493 /* Sorry. This isn't in 5.005_56 (IIRC) or earlier. */
2495 /* Need to do this out here, else 0xFFFFFFFF becomes iv of -1
2496 * (for example) and that ends up in the optimised small integer
2499 if ((flags & SVf_IVisUV) && SvUV(sv) > IV_MAX) {
2500 TRACEME(("large unsigned integer as string, value = %" UVuf,
2502 goto string_readlen;
2506 * Optimize small integers into a single byte, otherwise store as
2507 * a real integer (converted into network order if they asked).
2510 if (iv >= -128 && iv <= 127) {
2511 unsigned char siv = (unsigned char) (iv + 128); /* [0,255] */
2514 TRACEME(("small integer stored as %d", (int)siv));
2515 } else if (cxt->netorder) {
2517 TRACEME(("no htonl, fall back to string for integer"));
2518 goto string_readlen;
2526 /* Sorry. This isn't in 5.005_56 (IIRC) or earlier. */
2527 ((flags & SVf_IVisUV) && SvUV(sv) > (UV)0x7FFFFFFF) ||
2529 (iv > (IV)0x7FFFFFFF) || (iv < -(IV)0x80000000)) {
2530 /* Bigger than 32 bits. */
2531 TRACEME(("large network order integer as string, value = %" IVdf, iv));
2532 goto string_readlen;
2536 niv = (I32) htonl((I32) iv);
2537 TRACEME(("using network order"));
2542 PUTMARK(SX_INTEGER);
2543 WRITE(&iv, sizeof(iv));
2546 TRACEME(("ok (integer 0x%" UVxf ", value = %" IVdf ")", PTR2UV(sv), iv));
2547 } else if (flags & SVf_NOK) {
2550 /* if we can't tell if there's padding, clear the whole NV and hope the
2551 compiler leaves the padding alone
2553 Zero(&nv, 1, NV_bytes);
2555 #if PERL_VERSION_LT(5,7,0)
2558 * Watch for number being an integer in disguise.
2560 if (nv.nv == (NV) (iv = I_V(nv.nv))) {
2561 TRACEME(("double %" NVff " is actually integer %" IVdf, nv, iv));
2562 goto integer; /* Share code above */
2567 if (SvIOK_notUV(sv)) {
2569 goto integer; /* Share code above */
2574 if (cxt->netorder) {
2575 TRACEME(("double %" NVff " stored as string", nv.nv));
2576 goto string_readlen; /* Share code below */
2579 Zero(nv.bytes + NVSIZE - NV_PADDING, NV_PADDING, char);
2583 WRITE(&nv, sizeof(nv));
2585 TRACEME(("ok (double 0x%" UVxf ", value = %" NVff ")", PTR2UV(sv), nv.nv));
2587 } else if (flags & (SVp_POK | SVp_NOK | SVp_IOK)) {
2591 UV wlen; /* For 64-bit machines */
2597 * Will come here from above if it was readonly, POK and NOK but
2598 * neither &PL_sv_yes nor &PL_sv_no.
2603 if (SvMAGICAL(sv) && (mg = mg_find(sv, 'V'))) {
2604 /* The macro passes this by address, not value, and a lot of
2605 called code assumes that it's 32 bits without checking. */
2606 const SSize_t len = mg->mg_len;
2607 /* we no longer accept vstrings over I32_SIZE-1, so don't emit
2608 them, also, older Storables handle them badly.
2610 if (len >= I32_MAX) {
2611 CROAK(("vstring too large to freeze"));
2613 STORE_PV_LEN((const char *)mg->mg_ptr,
2614 len, SX_VSTRING, SX_LVSTRING);
2620 STORE_UTF8STR(pv, wlen);
2622 STORE_SCALAR(pv, wlen);
2623 TRACEME(("ok (scalar 0x%" UVxf " '%s', length = %" UVuf ")",
2624 PTR2UV(sv), len >= 2048 ? "<string too long>" : SvPVX(sv),
2627 CROAK(("Can't determine type of %s(0x%" UVxf ")",
2628 sv_reftype(sv, FALSE),
2631 return 0; /* Ok, no recursion on scalars */
2639 * Layout is SX_ARRAY <size> followed by each item, in increasing index order.
2640 * Each item is stored as <object>.
2642 static int store_array(pTHX_ stcxt_t *cxt, AV *av)
2645 UV len = av_len(av) + 1;
2648 SV *const recur_sv = cxt->recur_sv;
2650 TRACEME(("store_array (0x%" UVxf ")", PTR2UV(av)));
2653 if (len > 0x7fffffffu) {
2655 * Large array by emitting SX_LOBJECT 1 U64 data
2657 PUTMARK(SX_LOBJECT);
2660 TRACEME(("lobject size = %lu", (unsigned long)len));
2665 * Normal array by emitting SX_ARRAY, followed by the array length.
2670 TRACEME(("size = %d", (int)l));
2673 TRACEME((">array recur_depth %" IVdf ", recur_sv (0x%" UVxf ") max %" IVdf, cxt->recur_depth,
2674 PTR2UV(cxt->recur_sv), cxt->max_recur_depth));
2675 if (recur_sv != (SV*)av) {
2676 if (RECURSION_TOO_DEEP()) {
2677 /* with <= 5.14 it recurses in the cleanup also, needing 2x stack size */
2678 #if PERL_VERSION_LT(5,15,0)
2679 cleanup_recursive_data(aTHX_ (SV*)av);
2681 CROAK((MAX_DEPTH_ERROR));
2686 * Now store each item recursively.
2689 for (i = 0; i < len; i++) {
2690 sav = av_fetch(av, i, 0);
2692 TRACEME(("(#%d) nonexistent item", (int)i));
2696 #if PERL_VERSION_GE(5,19,0)
2697 /* In 5.19.3 and up, &PL_sv_undef can actually be stored in
2698 * an array; it no longer represents nonexistent elements.
2699 * Historically, we have used SX_SV_UNDEF in arrays for
2700 * nonexistent elements, so we use SX_SVUNDEF_ELEM for
2701 * &PL_sv_undef itself. */
2702 if (*sav == &PL_sv_undef) {
2703 TRACEME(("(#%d) undef item", (int)i));
2705 PUTMARK(SX_SVUNDEF_ELEM);
2709 TRACEME(("(#%d) item", (int)i));
2710 if ((ret = store(aTHX_ cxt, *sav))) /* Extra () for -Wall */
2714 if (recur_sv != (SV*)av) {
2715 assert(cxt->max_recur_depth == -1 || cxt->recur_depth > 0);
2716 if (cxt->max_recur_depth != -1 && cxt->recur_depth > 0) {
2717 TRACEME(("<array recur_depth --%" IVdf, cxt->recur_depth));
2721 TRACEME(("ok (array)"));
2727 #if PERL_VERSION_LT(5,7,0)
2733 * Borrowed from perl source file pp_ctl.c, where it is used by pp_sort.
2736 sortcmp(const void *a, const void *b)
2738 #if defined(USE_ITHREADS)
2740 #endif /* USE_ITHREADS */
2741 return sv_cmp(*(SV * const *) a, *(SV * const *) b);
2744 #endif /* PERL_VERSION_LT(5,7,0) */
2749 * Store a hash table.
2751 * For a "normal" hash (not restricted, no utf8 keys):
2753 * Layout is SX_HASH <size> followed by each key/value pair, in random order.
2754 * Values are stored as <object>.
2755 * Keys are stored as <length> <data>, the <data> section being omitted
2758 * For a "fancy" hash (restricted or utf8 keys):
2760 * Layout is SX_FLAG_HASH <size> <hash flags> followed by each key/value pair,
2762 * Values are stored as <object>.
2763 * Keys are stored as <flags> <length> <data>, the <data> section being omitted
2765 * Currently the only hash flag is "restricted"
2766 * Key flags are as for hv.h
2768 static int store_hash(pTHX_ stcxt_t *cxt, HV *hv)
2771 UV len = (UV)HvTOTALKEYS(hv);
2776 int flagged_hash = ((SvREADONLY(hv)
2777 #ifdef HAS_HASH_KEY_FLAGS
2781 unsigned char hash_flags = (SvREADONLY(hv) ? SHV_RESTRICTED : 0);
2782 SV * const recur_sv = cxt->recur_sv;
2785 * Signal hash by emitting SX_HASH, followed by the table length.
2786 * Max number of keys per perl version:
2788 * STRLEN 5.14 - 5.24 (size_t: U32/U64)
2789 * SSize_t 5.22c - 5.24c (I32/I64)
2793 if (len > 0x7fffffffu) { /* keys > I32_MAX */
2795 * Large hash: SX_LOBJECT type hashflags? U64 data
2797 * Stupid limitation:
2798 * Note that perl5 can store more than 2G keys, but only iterate
2799 * over 2G max. (cperl can)
2800 * We need to manually iterate over it then, unsorted.
2801 * But until perl itself cannot do that, skip that.
2803 TRACEME(("lobject size = %lu", (unsigned long)len));
2805 PUTMARK(SX_LOBJECT);
2807 PUTMARK(SX_FLAG_HASH);
2808 PUTMARK(hash_flags);
2813 return store_lhash(aTHX_ cxt, hv, hash_flags);
2815 /* <5.12 you could store larger hashes, but cannot iterate over them.
2816 So we reject them, it's a bug. */
2817 CROAK(("Cannot store large objects on a 32bit system"));
2822 TRACEME(("store_hash (0x%" UVxf ") (flags %x)", PTR2UV(hv),
2823 (unsigned int)hash_flags));
2824 PUTMARK(SX_FLAG_HASH);
2825 PUTMARK(hash_flags);
2827 TRACEME(("store_hash (0x%" UVxf ")", PTR2UV(hv)));
2831 TRACEME(("size = %d, used = %d", (int)l, (int)HvUSEDKEYS(hv)));
2834 TRACEME((">hash recur_depth %" IVdf ", recur_sv (0x%" UVxf ") max %" IVdf, cxt->recur_depth,
2835 PTR2UV(cxt->recur_sv), cxt->max_recur_depth_hash));
2836 if (recur_sv != (SV*)hv && cxt->max_recur_depth_hash != -1) {
2839 if (RECURSION_TOO_DEEP_HASH()) {
2840 #if PERL_VERSION_LT(5,15,0)
2841 cleanup_recursive_data(aTHX_ (SV*)hv);
2843 CROAK((MAX_DEPTH_ERROR));
2847 * Save possible iteration state via each() on that table.
2849 * Note that perl as of 5.24 *can* store more than 2G keys, but *not*
2851 * Lengths of hash keys are also limited to I32, which is good.
2854 riter = HvRITER_get(hv);
2855 eiter = HvEITER_get(hv);
2859 * Now store each item recursively.
2861 * If canonical is defined to some true value then store each
2862 * key/value pair in sorted order otherwise the order is random.
2863 * Canonical order is irrelevant when a deep clone operation is performed.
2865 * Fetch the value from perl only once per store() operation, and only
2870 !(cxt->optype & ST_CLONE)
2871 && (cxt->canonical == 1
2872 || (cxt->canonical < 0
2873 && (cxt->canonical =
2874 (SvTRUE(get_sv("Storable::canonical", GV_ADD))
2878 * Storing in order, sorted by key.
2879 * Run through the hash, building up an array of keys in a
2880 * mortal array, sort the array and then run through the
2884 av_extend (av, len);
2886 TRACEME(("using canonical order"));
2888 for (i = 0; i < len; i++) {
2889 #ifdef HAS_RESTRICTED_HASHES
2890 HE *he = hv_iternext_flags(hv, HV_ITERNEXT_WANTPLACEHOLDERS);
2892 HE *he = hv_iternext(hv);
2894 av_store(av, i, hv_iterkeysv(he));
2899 for (i = 0; i < len; i++) {
2900 #ifdef HAS_RESTRICTED_HASHES
2901 int placeholders = (int)HvPLACEHOLDERS_get(hv);
2903 unsigned char flags = 0;
2907 SV *key = av_shift(av);
2908 /* This will fail if key is a placeholder.
2909 Track how many placeholders we have, and error if we
2911 HE *he = hv_fetch_ent(hv, key, 0, 0);
2915 if (!(val = HeVAL(he))) {
2916 /* Internal error, not I/O error */
2920 #ifdef HAS_RESTRICTED_HASHES
2921 /* Should be a placeholder. */
2922 if (placeholders-- < 0) {
2923 /* This should not happen - number of
2924 retrieves should be identical to
2925 number of placeholders. */
2928 /* Value is never needed, and PL_sv_undef is
2929 more space efficient to store. */
2932 ("Flags not 0 but %d", (int)flags));
2933 flags = SHV_K_PLACEHOLDER;
2940 * Store value first.
2943 TRACEME(("(#%d) value 0x%" UVxf, (int)i, PTR2UV(val)));
2945 if ((ret = store(aTHX_ cxt, val))) /* Extra () for -Wall, grr... */
2950 * Keys are written after values to make sure retrieval
2951 * can be optimal in terms of memory usage, where keys are
2952 * read into a fixed unique buffer called kbuf.
2953 * See retrieve_hash() for details.
2956 /* Implementation of restricted hashes isn't nicely
2958 if ((hash_flags & SHV_RESTRICTED)
2959 && SvTRULYREADONLY(val)) {
2960 flags |= SHV_K_LOCKED;
2963 keyval = SvPV(key, keylen_tmp);
2964 keylen = keylen_tmp;
2966 const char *keysave = keyval;
2967 bool is_utf8 = TRUE;
2969 /* Just casting the &klen to (STRLEN) won't work
2970 well if STRLEN and I32 are of different widths.
2972 keyval = (char*)bytes_from_utf8((U8*)keyval,
2976 /* If we were able to downgrade here, then than
2977 means that we have a key which only had chars
2978 0-255, but was utf8 encoded. */
2980 if (keyval != keysave) {
2981 keylen = keylen_tmp;
2982 flags |= SHV_K_WASUTF8;
2984 /* keylen_tmp can't have changed, so no need
2985 to assign back to keylen. */
2986 flags |= SHV_K_UTF8;
2992 TRACEME(("(#%d) key '%s' flags %x %u", (int)i, keyval, flags, *keyval));
2994 /* This is a workaround for a bug in 5.8.0
2995 that causes the HEK_WASUTF8 flag to be
2996 set on an HEK without the hash being
2997 marked as having key flags. We just
2998 cross our fingers and drop the flag.
3000 assert (flags == 0 || flags == SHV_K_WASUTF8);
3001 TRACEME(("(#%d) key '%s'", (int)i, keyval));
3005 WRITE(keyval, keylen);
3006 if (flags & SHV_K_WASUTF8)
3011 * Free up the temporary array
3020 * Storing in "random" order (in the order the keys are stored
3021 * within the hash). This is the default and will be faster!
3024 for (i = 0; i < len; i++) {
3025 #ifdef HV_ITERNEXT_WANTPLACEHOLDERS
3026 HE *he = hv_iternext_flags(hv, HV_ITERNEXT_WANTPLACEHOLDERS);
3028 HE *he = hv_iternext(hv);
3030 SV *val = (he ? hv_iterval(hv, he) : 0);
3033 return 1; /* Internal error, not I/O error */
3035 if ((ret = store_hentry(aTHX_ cxt, hv, i, HeKEY_hek(he), val, hash_flags)))
3040 TRACEME(("ok (hash 0x%" UVxf ")", PTR2UV(hv)));
3043 assert(cxt->max_recur_depth_hash != -1 && cxt->recur_depth > 0);
3044 TRACEME(("<hash recur_depth --%" IVdf , cxt->recur_depth));
3045 if (cxt->max_recur_depth_hash != -1 && recur_sv != (SV*)hv && cxt->recur_depth > 0) {
3048 HvRITER_set(hv, riter); /* Restore hash iterator state */
3049 HvEITER_set(hv, eiter);
3054 static int store_hentry(pTHX_
3055 stcxt_t *cxt, HV* hv, UV i, HEK *hek, SV *val, unsigned char hash_flags)
3058 int flagged_hash = ((SvREADONLY(hv)
3059 #ifdef HAS_HASH_KEY_FLAGS
3063 /* Implementation of restricted hashes isn't nicely
3065 unsigned char flags = (((hash_flags & SHV_RESTRICTED)
3066 && SvTRULYREADONLY(val))
3067 ? SHV_K_LOCKED : 0);
3071 if (val == &PL_sv_placeholder) {
3072 flags |= SHV_K_PLACEHOLDER;
3077 * Store value first.
3080 TRACEME(("(#%d) value 0x%" UVxf, (int)i, PTR2UV(val)));
3083 I32 len = HEK_LEN(hek);
3087 if ((ret = store(aTHX_ cxt, val)))
3089 if (len == HEf_SVKEY) {
3090 /* This is somewhat sick, but the internal APIs are
3091 * such that XS code could put one of these in
3093 * Maybe we should be capable of storing one if
3096 key_sv = (SV *)HEK_KEY(hek);
3097 flags |= SHV_K_ISSV;
3099 /* Regular string key. */
3100 #ifdef HAS_HASH_KEY_FLAGS
3102 flags |= SHV_K_UTF8;
3103 if (HEK_WASUTF8(hek))
3104 flags |= SHV_K_WASUTF8;
3110 * Keys are written after values to make sure retrieval
3111 * can be optimal in terms of memory usage, where keys are
3112 * read into a fixed unique buffer called kbuf.
3113 * See retrieve_hash() for details.
3118 TRACEME(("(#%d) key '%s' flags %x", (int)i, key, flags));
3120 /* This is a workaround for a bug in 5.8.0
3121 that causes the HEK_WASUTF8 flag to be
3122 set on an HEK without the hash being
3123 marked as having key flags. We just
3124 cross our fingers and drop the flag.
3126 assert (flags == 0 || flags == SHV_K_WASUTF8);
3127 TRACEME(("(#%d) key '%s'", (int)i, key));
3129 if (flags & SHV_K_ISSV) {
3130 if ((ret = store(aTHX_ cxt, key_sv)))
3146 * Store a overlong hash table, with >2G keys, which we cannot iterate
3147 * over with perl5. xhv_eiter is only I32 there. (only cperl can)
3148 * and we also do not want to sort it.
3149 * So we walk the buckets and chains manually.
3151 * type, len and flags are already written.
3154 static int store_lhash(pTHX_ stcxt_t *cxt, HV *hv, unsigned char hash_flags)
3162 UV len = (UV)HvTOTALKEYS(hv);
3164 SV * const recur_sv = cxt->recur_sv;
3166 TRACEME(("store_lhash (0x%" UVxf ") (flags %x)", PTR2UV(hv),
3169 TRACEME(("store_lhash (0x%" UVxf ")", PTR2UV(hv)));
3171 TRACEME(("size = %" UVuf ", used = %" UVuf, len, (UV)HvUSEDKEYS(hv)));
3173 TRACEME(("recur_depth %" IVdf ", recur_sv (0x%" UVxf ")", cxt->recur_depth,
3174 PTR2UV(cxt->recur_sv)));
3175 if (recur_sv != (SV*)hv && cxt->max_recur_depth_hash != -1) {
3178 if (RECURSION_TOO_DEEP_HASH()) {
3179 #if PERL_VERSION_LT(5,15,0)
3180 cleanup_recursive_data(aTHX_ (SV*)hv);
3182 CROAK((MAX_DEPTH_ERROR));
3185 array = HvARRAY(hv);
3186 for (i = 0; i <= (Size_t)HvMAX(hv); i++) {
3187 HE* entry = array[i];
3190 SV* val = hv_iterval(hv, entry);
3191 if ((ret = store_hentry(aTHX_ cxt, hv, ix++, HeKEY_hek(entry), val, hash_flags)))
3193 entry = HeNEXT(entry);
3196 if (recur_sv != (SV*)hv && cxt->max_recur_depth_hash != -1 && cxt->recur_depth > 0) {
3197 TRACEME(("recur_depth --%" IVdf, cxt->recur_depth));
3208 * Store a code reference.
3210 * Layout is SX_CODE <length> followed by a scalar containing the perl
3211 * source code of the code reference.
3213 static int store_code(pTHX_ stcxt_t *cxt, CV *cv)
3217 STRLEN count, reallen;
3218 SV *text, *bdeparse;
3220 TRACEME(("store_code (0x%" UVxf ")", PTR2UV(cv)));
3223 cxt->deparse == 0 ||
3224 (cxt->deparse < 0 &&
3226 SvTRUE(get_sv("Storable::Deparse", GV_ADD)) ? 1 : 0))
3228 return store_other(aTHX_ cxt, (SV*)cv);
3232 * Require B::Deparse. At least B::Deparse 0.61 is needed for
3233 * blessed code references.
3235 /* Ownership of both SVs is passed to load_module, which frees them. */
3236 load_module(PERL_LOADMOD_NOIMPORT, newSVpvs("B::Deparse"), newSVnv(0.61));
3243 * create the B::Deparse object
3247 XPUSHs(newSVpvs_flags("B::Deparse", SVs_TEMP));
3249 count = call_method("new", G_SCALAR);
3252 CROAK(("Unexpected return value from B::Deparse::new\n"));
3256 * call the coderef2text method
3260 XPUSHs(bdeparse); /* XXX is this already mortal? */
3261 XPUSHs(sv_2mortal(newRV_inc((SV*)cv)));
3263 count = call_method("coderef2text", G_SCALAR);
3266 CROAK(("Unexpected return value from B::Deparse::coderef2text\n"));
3270 reallen = strlen(SvPV_nolen(text));
3273 * Empty code references or XS functions are deparsed as
3274 * "(prototype) ;" or ";".
3277 if (len == 0 || *(SvPV_nolen(text)+reallen-1) == ';') {
3278 CROAK(("The result of B::Deparse::coderef2text was empty - maybe you're trying to serialize an XS function?\n"));
3282 * Signal code by emitting SX_CODE.
3286 cxt->tagnum++; /* necessary, as SX_CODE is a SEEN() candidate */
3287 TRACEME(("size = %d", (int)len));
3288 TRACEME(("code = %s", SvPV_nolen(text)));
3291 * Now store the source code.
3295 STORE_UTF8STR(SvPV_nolen(text), len);
3297 STORE_SCALAR(SvPV_nolen(text), len);
3302 TRACEME(("ok (code)"));
3307 #if PERL_VERSION_LT(5,8,0)
3308 # define PERL_MAGIC_qr 'r' /* precompiled qr// regex */
3309 # define BFD_Svs_SMG_OR_RMG SVs_RMG
3310 #elif PERL_VERSION_GE(5,8,1)
3311 # define BFD_Svs_SMG_OR_RMG SVs_SMG
3312 # define MY_PLACEHOLDER PL_sv_placeholder
3314 # define BFD_Svs_SMG_OR_RMG SVs_RMG
3315 # define MY_PLACEHOLDER PL_sv_undef
3318 static int get_regexp(pTHX_ stcxt_t *cxt, SV* sv, SV **re, SV **flags) {
3321 #if PERL_VERSION_GE(5,12,0)
3322 CV *cv = get_cv("re::regexp_pattern", 0);
3324 CV *cv = get_cv("Storable::_regexp_pattern", 0);
3332 rv = sv_2mortal((SV*)newRV_inc(sv));
3336 /* optimize to call the XS directly later */
3337 count = call_sv((SV*)cv, G_LIST);
3340 CROAK(("re::regexp_pattern returned only %d results", (int)count));
3342 SvREFCNT_inc(*flags);
3353 static int store_regexp(pTHX_ stcxt_t *cxt, SV *sv) {
3357 const char *flags_pv;
3362 if (!get_regexp(aTHX_ cxt, sv, &re, &flags))
3365 re_pv = SvPV(re, re_len);
3366 flags_pv = SvPV(flags, flags_len);
3368 if (re_len > 0xFF) {
3369 op_flags |= SHR_U32_RE_LEN;
3374 if (op_flags & SHR_U32_RE_LEN) {
3375 U32 re_len32 = re_len;
3380 WRITE(re_pv, re_len);
3382 WRITE(flags_pv, flags_len);
3390 * When storing a tied object (be it a tied scalar, array or hash), we lay out
3391 * a special mark, followed by the underlying tied object. For instance, when
3392 * dealing with a tied hash, we store SX_TIED_HASH <hash object>, where
3393 * <hash object> stands for the serialization of the tied hash.
3395 static int store_tied(pTHX_ stcxt_t *cxt, SV *sv)
3400 int svt = SvTYPE(sv);
3403 TRACEME(("store_tied (0x%" UVxf ")", PTR2UV(sv)));
3406 * We have a small run-time penalty here because we chose to factorise
3407 * all tieds objects into the same routine, and not have a store_tied_hash,
3408 * a store_tied_array, etc...
3410 * Don't use a switch() statement, as most compilers don't optimize that
3411 * well for 2/3 values. An if() else if() cascade is just fine. We put
3412 * tied hashes first, as they are the most likely beasts.
3415 if (svt == SVt_PVHV) {
3416 TRACEME(("tied hash"));
3417 PUTMARK(SX_TIED_HASH); /* Introduces tied hash */
3418 } else if (svt == SVt_PVAV) {
3419 TRACEME(("tied array"));
3420 PUTMARK(SX_TIED_ARRAY); /* Introduces tied array */
3422 TRACEME(("tied scalar"));
3423 PUTMARK(SX_TIED_SCALAR); /* Introduces tied scalar */
3427 if (!(mg = mg_find(sv, mtype)))
3428 CROAK(("No magic '%c' found while storing tied %s", mtype,
3429 (svt == SVt_PVHV) ? "hash" :
3430 (svt == SVt_PVAV) ? "array" : "scalar"));
3433 * The mg->mg_obj found by mg_find() above actually points to the
3434 * underlying tied Perl object implementation. For instance, if the
3435 * original SV was that of a tied array, then mg->mg_obj is an AV.
3437 * Note that we store the Perl object as-is. We don't call its FETCH
3438 * method along the way. At retrieval time, we won't call its STORE
3439 * method either, but the tieing magic will be re-installed. In itself,
3440 * that ensures that the tieing semantics are preserved since further
3441 * accesses on the retrieved object will indeed call the magic methods...
3444 /* [#17040] mg_obj is NULL for scalar self-ties. AMS 20030416 */
3445 obj = mg->mg_obj ? mg->mg_obj : newSV(0);
3446 if ((ret = store(aTHX_ cxt, obj)))
3449 TRACEME(("ok (tied)"));
3457 * Stores a reference to an item within a tied structure:
3459 * . \$h{key}, stores both the (tied %h) object and 'key'.
3460 * . \$a[idx], stores both the (tied @a) object and 'idx'.
3462 * Layout is therefore either:
3463 * SX_TIED_KEY <object> <key>
3464 * SX_TIED_IDX <object> <index>
3466 static int store_tied_item(pTHX_ stcxt_t *cxt, SV *sv)
3471 TRACEME(("store_tied_item (0x%" UVxf ")", PTR2UV(sv)));
3473 if (!(mg = mg_find(sv, 'p')))
3474 CROAK(("No magic 'p' found while storing reference to tied item"));
3477 * We discriminate between \$h{key} and \$a[idx] via mg_ptr.
3481 TRACEME(("store_tied_item: storing a ref to a tied hash item"));
3482 PUTMARK(SX_TIED_KEY);
3483 TRACEME(("store_tied_item: storing OBJ 0x%" UVxf, PTR2UV(mg->mg_obj)));
3485 if ((ret = store(aTHX_ cxt, mg->mg_obj))) /* Extra () for -Wall, grr... */
3488 TRACEME(("store_tied_item: storing PTR 0x%" UVxf, PTR2UV(mg->mg_ptr)));
3490 if ((ret = store(aTHX_ cxt, (SV *) mg->mg_ptr))) /* Idem, for -Wall */
3493 I32 idx = mg->mg_len;
3495 TRACEME(("store_tied_item: storing a ref to a tied array item "));
3496 PUTMARK(SX_TIED_IDX);
3497 TRACEME(("store_tied_item: storing OBJ 0x%" UVxf, PTR2UV(mg->mg_obj)));
3499 if ((ret = store(aTHX_ cxt, mg->mg_obj))) /* Idem, for -Wall */
3502 TRACEME(("store_tied_item: storing IDX %d", (int)idx));
3507 TRACEME(("ok (tied item)"));
3513 * store_hook -- dispatched manually, not via sv_store[]
3515 * The blessed SV is serialized by a hook.
3519 * SX_HOOK <flags> <len> <classname> <len2> <str> [<len3> <object-IDs>]
3521 * where <flags> indicates how long <len>, <len2> and <len3> are, whether
3522 * the trailing part [] is present, the type of object (scalar, array or hash).
3523 * There is also a bit which says how the classname is stored between:
3528 * and when the <index> form is used (classname already seen), the "large
3529 * classname" bit in <flags> indicates how large the <index> is.
3531 * The serialized string returned by the hook is of length <len2> and comes
3532 * next. It is an opaque string for us.
3534 * Those <len3> object IDs which are listed last represent the extra references
3535 * not directly serialized by the hook, but which are linked to the object.
3537 * When recursion is mandated to resolve object-IDs not yet seen, we have
3538 * instead, with <header> being flags with bits set to indicate the object type
3539 * and that recursion was indeed needed:
3541 * SX_HOOK <header> <object> <header> <object> <flags>
3543 * that same header being repeated between serialized objects obtained through
3544 * recursion, until we reach flags indicating no recursion, at which point
3545 * we know we've resynchronized with a single layout, after <flags>.
3547 * When storing a blessed ref to a tied variable, the following format is
3550 * SX_HOOK <flags> <extra> ... [<len3> <object-IDs>] <magic object>
3552 * The first <flags> indication carries an object of type SHT_EXTRA, and the
3553 * real object type is held in the <extra> flag. At the very end of the
3554 * serialization stream, the underlying magic object is serialized, just like
3555 * any other tied variable.
3557 static int store_hook(
3571 IV count; /* really len3 + 1 */
3572 unsigned char flags;
3575 int recursed = 0; /* counts recursion */
3576 int obj_type; /* object type, on 2 bits */
3579 int clone = cxt->optype & ST_CLONE;
3580 char mtype = '\0'; /* for blessed ref to tied structures */
3581 unsigned char eflags = '\0'; /* used when object type is SHT_EXTRA */
3583 int need_large_oids = 0;
3586 classname = HvNAME_get(pkg);
3587 len = strlen(classname);
3589 TRACEME(("store_hook, classname \"%s\", tagged #%d", classname, (int)cxt->tagnum));
3592 * Determine object type on 2 bits.
3599 obj_type = SHT_SCALAR;
3602 obj_type = SHT_ARRAY;
3605 obj_type = SHT_HASH;
3609 * Produced by a blessed ref to a tied data structure, $o in the
3610 * following Perl code.
3614 * my $o = bless \%h, 'BAR';
3616 * Signal the tie-ing magic by setting the object type as SHT_EXTRA
3617 * (since we have only 2 bits in <flags> to store the type), and an
3618 * <extra> byte flag will be emitted after the FIRST <flags> in the
3619 * stream, carrying what we put in 'eflags'.
3621 obj_type = SHT_EXTRA;
3622 switch (SvTYPE(sv)) {
3624 eflags = (unsigned char) SHT_THASH;
3628 eflags = (unsigned char) SHT_TARRAY;
3632 eflags = (unsigned char) SHT_TSCALAR;
3639 /* pkg_can() always returns a ref to a CV on success */
3640 CV *cv = (CV*)SvRV(hook);
3641 const GV * const gv = CvGV(cv);
3642 const char *gvname = GvNAME(gv);
3643 const HV * const stash = GvSTASH(gv);
3644 const char *hvname = stash ? HvNAME(stash) : NULL;
3646 CROAK(("Unexpected object type (%s) of class '%s' in store_hook() calling %s::%s",
3647 sv_reftype(sv, FALSE), classname, hvname, gvname));
3650 flags = SHF_NEED_RECURSE | obj_type;
3653 * To call the hook, we need to fake a call like:
3655 * $object->STORABLE_freeze($cloning);
3657 * but we don't have the $object here. For instance, if $object is
3658 * a blessed array, what we have in 'sv' is the array, and we can't
3659 * call a method on those.
3661 * Therefore, we need to create a temporary reference to the object and
3662 * make the call on that reference.
3665 TRACEME(("about to call STORABLE_freeze on class %s", classname));
3667 ref = newRV_inc(sv); /* Temporary reference */
3668 av = array_call(aTHX_ ref, hook, clone); /* @a = $object->STORABLE_freeze($c) */
3669 SvREFCNT_dec(ref); /* Reclaim temporary reference */
3671 count = AvFILLp(av) + 1;
3672 TRACEME(("store_hook, array holds %" IVdf " items", count));
3675 * If they return an empty list, it means they wish to ignore the
3676 * hook for this class (and not just this instance -- that's for them
3677 * to handle if they so wish).
3679 * Simply disable the cached entry for the hook (it won't be recomputed
3680 * since it's present in the cache) and recurse to store_blessed().
3684 /* free empty list returned by the hook */
3689 * They must not change their mind in the middle of a serialization.
3692 if (hv_fetch(cxt->hclass, classname, len, FALSE))
3693 CROAK(("Too late to ignore hooks for %s class \"%s\"",
3694 (cxt->optype & ST_CLONE) ? "cloning" : "storing",
3697 pkg_hide(aTHX_ cxt->hook, pkg, "STORABLE_freeze");
3699 ASSERT(!pkg_can(aTHX_ cxt->hook, pkg, "STORABLE_freeze"),
3700 ("hook invisible"));
3701 TRACEME(("ignoring STORABLE_freeze in class \"%s\"", classname));
3703 return store_blessed(aTHX_ cxt, sv, type, pkg);
3707 * Get frozen string.
3711 pv = SvPV(ary[0], len2);
3712 /* We can't use pkg_can here because it only caches one method per
3715 GV* gv = gv_fetchmethod_autoload(pkg, "STORABLE_attach", FALSE);
3716 if (gv && isGV(gv)) {
3718 CROAK(("Freeze cannot return references if %s class is using STORABLE_attach", classname));
3724 if (count > I32_MAX) {
3725 CROAK(("Too many references returned by STORABLE_freeze()"));
3730 * If they returned more than one item, we need to serialize some
3731 * extra references if not already done.
3733 * Loop over the array, starting at position #1, and for each item,
3734 * ensure it is a reference, serialize it if not already done, and
3735 * replace the entry with the tag ID of the corresponding serialized
3738 * We CHEAT by not calling av_fetch() and read directly within the
3742 for (i = 1; i < count; i++) {
3743 #ifdef USE_PTR_TABLE
3751 AV *av_hook = cxt->hook_seen;
3754 CROAK(("Item #%d returned by STORABLE_freeze "
3755 "for %s is not a reference", (int)i, classname));
3756 xsv = SvRV(rsv); /* Follow ref to know what to look for */
3759 * Look in hseen and see if we have a tag already.
3760 * Serialize entry if not done already, and get its tag.
3763 #ifdef USE_PTR_TABLE
3764 /* Fakery needed because ptr_table_fetch returns zero for a
3765 failure, whereas the existing code assumes that it can
3766 safely store a tag zero. So for ptr_tables we store tag+1
3768 if ((fake_tag = (char *)ptr_table_fetch(cxt->pseen, xsv)))
3769 goto sv_seen; /* Avoid moving code too far to the right */
3771 if ((svh = hv_fetch(cxt->hseen, (char *) &xsv, sizeof(xsv), FALSE)))
3772 goto sv_seen; /* Avoid moving code too far to the right */
3775 TRACEME(("listed object %d at 0x%" UVxf " is unknown", i-1,
3779 * We need to recurse to store that object and get it to be known
3780 * so that we can resolve the list of object-IDs at retrieve time.
3782 * The first time we do this, we need to emit the proper header
3783 * indicating that we recursed, and what the type of object is (the
3784 * object we're storing via a user-hook). Indeed, during retrieval,
3785 * we'll have to create the object before recursing to retrieve the
3786 * others, in case those would point back at that object.
3789 /* [SX_HOOK] <flags> [<extra>] <object>*/
3792 if (len2 > INT32_MAX)
3793 PUTMARK(SX_LOBJECT);
3797 if (obj_type == SHT_EXTRA)
3802 if ((ret = store(aTHX_ cxt, xsv))) /* Given by hook for us to store */
3805 #ifdef USE_PTR_TABLE
3806 fake_tag = (char *)ptr_table_fetch(cxt->pseen, xsv);
3808 CROAK(("Could not serialize item #%d from hook in %s",
3809 (int)i, classname));
3811 svh = hv_fetch(cxt->hseen, (char *) &xsv, sizeof(xsv), FALSE);
3813 CROAK(("Could not serialize item #%d from hook in %s",
3814 (int)i, classname));
3817 * It was the first time we serialized 'xsv'.
3819 * Keep this SV alive until the end of the serialization: if we
3820 * disposed of it right now by decrementing its refcount, and it was
3821 * a temporary value, some next temporary value allocated during
3822 * another STORABLE_freeze might take its place, and we'd wrongly
3823 * assume that new SV was already serialized, based on its presence
3826 * Therefore, push it away in cxt->hook_seen.
3829 av_store(av_hook, AvFILLp(av_hook)+1, SvREFCNT_inc(xsv));
3833 * Dispose of the REF they returned. If we saved the 'xsv' away
3834 * in the array of returned SVs, that will not cause the underlying
3835 * referenced SV to be reclaimed.
3838 ASSERT(SvREFCNT(xsv) > 1, ("SV will survive disposal of its REF"));
3839 SvREFCNT_dec(rsv); /* Dispose of reference */
3842 * Replace entry with its tag (not a real SV, so no refcnt increment)
3845 #ifdef USE_PTR_TABLE
3846 tag = (SV *)--fake_tag;
3851 TRACEME(("listed object %d at 0x%" UVxf " is tag #%" UVuf,
3852 i-1, PTR2UV(xsv), PTR2UV(tag)));
3854 if ((U32)PTR2TAG(tag) != PTR2TAG(tag))
3855 need_large_oids = 1;
3860 * Allocate a class ID if not already done.
3862 * This needs to be done after the recursion above, since at retrieval
3863 * time, we'll see the inner objects first. Many thanks to
3864 * Salvador Ortiz Garcia <sog@msg.com.mx> who spot that bug and
3865 * proposed the right fix. -- RAM, 15/09/2000
3869 if (!known_class(aTHX_ cxt, classname, len, &classnum)) {
3870 TRACEME(("first time we see class %s, ID = %d", classname, (int)classnum));
3871 classnum = -1; /* Mark: we must store classname */
3873 TRACEME(("already seen class %s, ID = %d", classname, (int)classnum));
3877 * Compute leading flags.
3881 if (((classnum == -1) ? len : classnum) > LG_SCALAR)
3882 flags |= SHF_LARGE_CLASSLEN;
3884 flags |= SHF_IDX_CLASSNAME;
3885 if (len2 > LG_SCALAR)
3886 flags |= SHF_LARGE_STRLEN;
3888 flags |= SHF_HAS_LIST;
3889 if (count > (LG_SCALAR + 1))
3890 flags |= SHF_LARGE_LISTLEN;
3892 if (need_large_oids)
3893 flags |= SHF_LARGE_LISTLEN;
3897 * We're ready to emit either serialized form:
3899 * SX_HOOK <flags> <len> <classname> <len2> <str> [<len3> <object-IDs>]
3900 * SX_HOOK <flags> <index> <len2> <str> [<len3> <object-IDs>]
3902 * If we recursed, the SX_HOOK has already been emitted.
3905 TRACEME(("SX_HOOK (recursed=%d) flags=0x%x "
3906 "class=%" IVdf " len=%" IVdf " len2=%" IVdf " len3=%" IVdf,
3907 recursed, flags, (IV)classnum, (IV)len, (IV)len2, count-1));
3909 /* SX_HOOK <flags> [<extra>] */
3912 if (len2 > INT32_MAX)
3913 PUTMARK(SX_LOBJECT);
3917 if (obj_type == SHT_EXTRA)
3922 /* <len> <classname> or <index> */
3923 if (flags & SHF_IDX_CLASSNAME) {
3924 if (flags & SHF_LARGE_CLASSLEN)
3927 unsigned char cnum = (unsigned char) classnum;
3931 if (flags & SHF_LARGE_CLASSLEN)
3934 unsigned char clen = (unsigned char) len;
3937 WRITE(classname, len); /* Final \0 is omitted */
3940 /* <len2> <frozen-str> */
3942 if (len2 > INT32_MAX) {
3947 if (flags & SHF_LARGE_STRLEN) {
3948 U32 wlen2 = len2; /* STRLEN might be 8 bytes */
3949 WLEN(wlen2); /* Must write an I32 for 64-bit machines */
3951 unsigned char clen = (unsigned char) len2;
3955 WRITE(pv, (SSize_t)len2); /* Final \0 is omitted */
3957 /* [<len3> <object-IDs>] */
3958 if (flags & SHF_HAS_LIST) {
3959 int len3 = count - 1;
3960 if (flags & SHF_LARGE_LISTLEN) {
3962 int tlen3 = need_large_oids ? -len3 : len3;
3969 unsigned char clen = (unsigned char) len3;
3974 * NOTA BENE, for 64-bit machines: the ary[i] below does not yield a
3975 * real pointer, rather a tag number, well under the 32-bit limit.
3976 * Which is wrong... if we have more than 2**32 SVs we can get ids over
3980 for (i = 1; i < count; i++) {
3982 if (need_large_oids) {
3983 ntag_t tag = PTR2TAG(ary[i]);
3985 TRACEME(("object %d, tag #%" UVuf, i-1, (UV)tag));
3990 I32 tagval = htonl(LOW_32BITS(ary[i]));
3992 TRACEME(("object %d, tag #%d", i-1, ntohl(tagval)));
3998 * Free the array. We need extra care for indices after 0, since they
3999 * don't hold real SVs but integers cast.
4003 AvFILLp(av) = 0; /* Cheat, nothing after 0 interests us */
4008 * If object was tied, need to insert serialization of the magic object.
4011 if (obj_type == SHT_EXTRA) {
4014 if (!(mg = mg_find(sv, mtype))) {
4015 int svt = SvTYPE(sv);
4016 CROAK(("No magic '%c' found while storing ref to tied %s with hook",
4017 mtype, (svt == SVt_PVHV) ? "hash" :
4018 (svt == SVt_PVAV) ? "array" : "scalar"));
4021 TRACEME(("handling the magic object 0x%" UVxf " part of 0x%" UVxf,
4022 PTR2UV(mg->mg_obj), PTR2UV(sv)));
4027 if ((ret = store(aTHX_ cxt, mg->mg_obj)))
4035 * store_blessed -- dispatched manually, not via sv_store[]
4037 * Check whether there is a STORABLE_xxx hook defined in the class or in one
4038 * of its ancestors. If there is, then redispatch to store_hook();
4040 * Otherwise, the blessed SV is stored using the following layout:
4042 * SX_BLESS <flag> <len> <classname> <object>
4044 * where <flag> indicates whether <len> is stored on 0 or 4 bytes, depending
4045 * on the high-order bit in flag: if 1, then length follows on 4 bytes.
4046 * Otherwise, the low order bits give the length, thereby giving a compact
4047 * representation for class names less than 127 chars long.
4049 * Each <classname> seen is remembered and indexed, so that the next time
4050 * an object in the blessed in the same <classname> is stored, the following
4053 * SX_IX_BLESS <flag> <index> <object>
4055 * where <index> is the classname index, stored on 0 or 4 bytes depending
4056 * on the high-order bit in flag (same encoding as above for <len>).
4058 static int store_blessed(
4070 TRACEME(("store_blessed, type %d, class \"%s\"", type, HvNAME_get(pkg)));
4073 * Look for a hook for this blessed SV and redirect to store_hook()
4077 hook = pkg_can(aTHX_ cxt->hook, pkg, "STORABLE_freeze");
4079 return store_hook(aTHX_ cxt, sv, type, pkg, hook);
4082 * This is a blessed SV without any serialization hook.
4085 classname = HvNAME_get(pkg);
4086 len = strlen(classname);
4088 TRACEME(("blessed 0x%" UVxf " in %s, no hook: tagged #%d",
4089 PTR2UV(sv), classname, (int)cxt->tagnum));
4092 * Determine whether it is the first time we see that class name (in which
4093 * case it will be stored in the SX_BLESS form), or whether we already
4094 * saw that class name before (in which case the SX_IX_BLESS form will be
4098 if (known_class(aTHX_ cxt, classname, len, &classnum)) {
4099 TRACEME(("already seen class %s, ID = %d", classname, (int)classnum));
4100 PUTMARK(SX_IX_BLESS);
4101 if (classnum <= LG_BLESS) {
4102 unsigned char cnum = (unsigned char) classnum;
4105 unsigned char flag = (unsigned char) 0x80;
4110 TRACEME(("first time we see class %s, ID = %d", classname,
4113 if (len <= LG_BLESS) {
4114 unsigned char clen = (unsigned char) len;
4117 unsigned char flag = (unsigned char) 0x80;
4119 WLEN(len); /* Don't BER-encode, this should be rare */
4121 WRITE(classname, len); /* Final \0 is omitted */
4125 * Now emit the <object> part.
4128 return SV_STORE(type)(aTHX_ cxt, sv);
4134 * We don't know how to store the item we reached, so return an error condition.
4135 * (it's probably a GLOB, some CODE reference, etc...)
4137 * If they defined the 'forgive_me' variable at the Perl level to some
4138 * true value, then don't croak, just warn, and store a placeholder string
4141 static int store_other(pTHX_ stcxt_t *cxt, SV *sv)
4146 TRACEME(("store_other"));
4149 * Fetch the value from perl only once per store() operation.
4153 cxt->forgive_me == 0 ||
4154 (cxt->forgive_me < 0 &&
4155 !(cxt->forgive_me = SvTRUE
4156 (get_sv("Storable::forgive_me", GV_ADD)) ? 1 : 0))
4158 CROAK(("Can't store %s items", sv_reftype(sv, FALSE)));
4160 warn("Can't store item %s(0x%" UVxf ")",
4161 sv_reftype(sv, FALSE), PTR2UV(sv));
4164 * Store placeholder string as a scalar instead...
4167 (void) sprintf(buf, "You lost %s(0x%" UVxf ")%c", sv_reftype(sv, FALSE),
4168 PTR2UV(sv), (char) 0);
4172 STORE_SCALAR(buf, len);
4173 TRACEME(("ok (dummy \"%s\", length = %" IVdf ")", buf, (IV) len));
4179 *** Store driving routines
4185 * WARNING: partially duplicates Perl's sv_reftype for speed.
4187 * Returns the type of the SV, identified by an integer. That integer
4188 * may then be used to index the dynamic routine dispatch table.
4190 static int sv_type(pTHX_ SV *sv)
4192 switch (SvTYPE(sv)) {
4194 #if PERL_VERSION_LT(5,11,0)
4199 * No need to check for ROK, that can't be set here since there
4200 * is no field capable of hodling the xrv_rv reference.
4204 #if PERL_VERSION_LT(5,11,0)
4212 * Starting from SVt_PV, it is possible to have the ROK flag
4213 * set, the pointer to the other SV being either stored in
4214 * the xrv_rv (in the case of a pure SVt_RV), or as the
4215 * xpv_pv field of an SVt_PV and its heirs.
4217 * However, those SV cannot be magical or they would be an
4218 * SVt_PVMG at least.
4220 return SvROK(sv) ? svis_REF : svis_SCALAR;
4222 #if PERL_VERSION_LT(5,11,0)
4223 if ((SvFLAGS(sv) & (SVs_OBJECT|SVf_OK|SVs_GMG|SVs_SMG|SVs_RMG))
4224 == (SVs_OBJECT|BFD_Svs_SMG_OR_RMG)
4225 && mg_find(sv, PERL_MAGIC_qr)) {
4229 case SVt_PVLV: /* Workaround for perl5.004_04 "LVALUE" bug */
4230 if ((SvFLAGS(sv) & (SVs_GMG|SVs_SMG|SVs_RMG)) ==
4231 (SVs_GMG|SVs_SMG|SVs_RMG) &&
4233 return svis_TIED_ITEM;
4235 #if PERL_VERSION_LT(5,9,0)
4238 if ((SvFLAGS(sv) & (SVs_GMG|SVs_SMG|SVs_RMG)) ==
4239 (SVs_GMG|SVs_SMG|SVs_RMG) &&
4242 return SvROK(sv) ? svis_REF : svis_SCALAR;
4244 if (SvRMAGICAL(sv) && (mg_find(sv, 'P')))
4248 if (SvRMAGICAL(sv) && (mg_find(sv, 'P')))
4253 #if PERL_VERSION_GE(5,9,0)
4254 /* case SVt_INVLIST: */
4256 #if PERL_VERSION_GE(5,11,0)
4270 * Recursively store objects pointed to by the sv to the specified file.
4272 * Layout is <content> or SX_OBJECT <tagnum> if we reach an already stored
4273 * object (one for which storage has started -- it may not be over if we have
4274 * a self-referenced structure). This data set forms a stored <object>.
4276 static int store(pTHX_ stcxt_t *cxt, SV *sv)
4281 #ifdef USE_PTR_TABLE
4282 struct ptr_tbl *pseen = cxt->pseen;
4284 HV *hseen = cxt->hseen;
4287 TRACEME(("store (0x%" UVxf ")", PTR2UV(sv)));
4290 * If object has already been stored, do not duplicate data.
4291 * Simply emit the SX_OBJECT marker followed by its tag data.
4292 * The tag is always written in network order.
4294 * NOTA BENE, for 64-bit machines: the "*svh" below does not yield a
4295 * real pointer, rather a tag number (watch the insertion code below).
4296 * That means it probably safe to assume it is well under the 32-bit
4297 * limit, and makes the truncation safe.
4298 * -- RAM, 14/09/1999
4301 #ifdef USE_PTR_TABLE
4302 svh = (SV **)ptr_table_fetch(pseen, sv);
4304 svh = hv_fetch(hseen, (char *) &sv, sizeof(sv), FALSE);
4308 if (sv == &PL_sv_undef) {
4309 /* We have seen PL_sv_undef before, but fake it as
4312 Not the simplest solution to making restricted
4313 hashes work on 5.8.0, but it does mean that
4314 repeated references to the one true undef will
4315 take up less space in the output file.
4317 /* Need to jump past the next hv_store, because on the
4318 second store of undef the old hash value will be
4319 SvREFCNT_dec()ed, and as Storable cheats horribly
4320 by storing non-SVs in the hash a SEGV will ensure.
4321 Need to increase the tag number so that the
4322 receiver has no idea what games we're up to. This
4323 special casing doesn't affect hooks that store
4324 undef, as the hook routine does its own lookup into
4325 hseen. Also this means that any references back
4326 to PL_sv_undef (from the pathological case of hooks
4327 storing references to it) will find the seen hash
4328 entry for the first time, as if we didn't have this
4329 hackery here. (That hseen lookup works even on 5.8.0
4330 because it's a key of &PL_sv_undef and a value
4331 which is a tag number, not a value which is
4335 goto undef_special_case;
4338 #ifdef USE_PTR_TABLE
4339 tagval = PTR2TAG(((char *)svh)-1);
4341 tagval = PTR2TAG(*svh);
4345 /* older versions of Storable streat the tag as a signed value
4346 used in an array lookup, corrupting the data structure.
4347 Ensure only a newer Storable will be able to parse this tag id
4348 if it's over the 2G mark.
4350 if (tagval > I32_MAX) {
4352 TRACEME(("object 0x%" UVxf " seen as #%" UVuf, PTR2UV(sv),
4355 PUTMARK(SX_LOBJECT);
4365 ltagval = htonl((I32)tagval);
4367 TRACEME(("object 0x%" UVxf " seen as #%d", PTR2UV(sv),
4377 * Allocate a new tag and associate it with the address of the sv being
4378 * stored, before recursing...
4380 * In order to avoid creating new SvIVs to hold the tagnum we just
4381 * cast the tagnum to an SV pointer and store that in the hash. This
4382 * means that we must clean up the hash manually afterwards, but gives
4383 * us a 15% throughput increase.
4388 #ifdef USE_PTR_TABLE
4389 ptr_table_store(pseen, sv, INT2PTR(SV*, 1 + cxt->tagnum));
4391 if (!hv_store(hseen,
4392 (char *) &sv, sizeof(sv), INT2PTR(SV*, cxt->tagnum), 0))
4397 * Store 'sv' and everything beneath it, using appropriate routine.
4398 * Abort immediately if we get a non-zero status back.
4401 type = sv_type(aTHX_ sv);
4404 TRACEME(("storing 0x%" UVxf " tag #%d, type %d...",
4405 PTR2UV(sv), (int)cxt->tagnum, (int)type));
4408 HV *pkg = SvSTASH(sv);
4409 ret = store_blessed(aTHX_ cxt, sv, type, pkg);
4411 ret = SV_STORE(type)(aTHX_ cxt, sv);
4413 TRACEME(("%s (stored 0x%" UVxf ", refcnt=%d, %s)",
4414 ret ? "FAILED" : "ok", PTR2UV(sv),
4415 (int)SvREFCNT(sv), sv_reftype(sv, FALSE)));
4423 * Write magic number and system information into the file.
4424 * Layout is <magic> <network> [<len> <byteorder> <sizeof int> <sizeof long>
4425 * <sizeof ptr>] where <len> is the length of the byteorder hexa string.
4426 * All size and lengths are written as single characters here.
4428 * Note that no byte ordering info is emitted when <network> is true, since
4429 * integers will be emitted in network order in that case.
4431 static int magic_write(pTHX_ stcxt_t *cxt)
4434 * Starting with 0.6, the "use_network_order" byte flag is also used to
4435 * indicate the version number of the binary image, encoded in the upper
4436 * bits. The bit 0 is always used to indicate network order.
4439 * Starting with 0.7, a full byte is dedicated to the minor version of
4440 * the binary format, which is incremented only when new markers are
4441 * introduced, for instance, but when backward compatibility is preserved.
4444 /* Make these at compile time. The WRITE() macro is sufficiently complex
4445 that it saves about 200 bytes doing it this way and only using it
4447 static const unsigned char network_file_header[] = {
4449 (STORABLE_BIN_MAJOR << 1) | 1,
4450 STORABLE_BIN_WRITE_MINOR
4452 static const unsigned char file_header[] = {
4454 (STORABLE_BIN_MAJOR << 1) | 0,
4455 STORABLE_BIN_WRITE_MINOR,
4456 /* sizeof the array includes the 0 byte at the end: */
4457 (char) sizeof (byteorderstr) - 1,
4459 (unsigned char) sizeof(int),
4460 (unsigned char) sizeof(long),
4461 (unsigned char) sizeof(char *),
4462 (unsigned char) sizeof(NV)
4464 #ifdef USE_56_INTERWORK_KLUDGE
4465 static const unsigned char file_header_56[] = {
4467 (STORABLE_BIN_MAJOR << 1) | 0,
4468 STORABLE_BIN_WRITE_MINOR,
4469 /* sizeof the array includes the 0 byte at the end: */
4470 (char) sizeof (byteorderstr_56) - 1,
4472 (unsigned char) sizeof(int),
4473 (unsigned char) sizeof(long),
4474 (unsigned char) sizeof(char *),
4475 (unsigned char) sizeof(NV)
4478 const unsigned char *header;
4481 TRACEME(("magic_write on fd=%d", cxt->fio ? PerlIO_fileno(cxt->fio) : -1));
4483 if (cxt->netorder) {
4484 header = network_file_header;
4485 length = sizeof (network_file_header);
4487 #ifdef USE_56_INTERWORK_KLUDGE
4488 if (SvTRUE(get_sv("Storable::interwork_56_64bit", GV_ADD))) {
4489 header = file_header_56;
4490 length = sizeof (file_header_56);
4494 header = file_header;
4495 length = sizeof (file_header);
4500 /* sizeof the array includes the 0 byte at the end. */
4501 header += sizeof (magicstr) - 1;
4502 length -= sizeof (magicstr) - 1;
4505 WRITE( (unsigned char*) header, length);
4507 if (!cxt->netorder) {
4508 TRACEME(("ok (magic_write byteorder = 0x%lx [%d], I%d L%d P%d D%d)",
4509 (unsigned long) BYTEORDER, (int) sizeof (byteorderstr) - 1,
4510 (int) sizeof(int), (int) sizeof(long),
4511 (int) sizeof(char *), (int) sizeof(NV)));
4519 * Common code for store operations.
4521 * When memory store is requested (f = NULL) and a non null SV* is given in
4522 * 'res', it is filled with a new SV created out of the memory buffer.
4524 * It is required to provide a non-null 'res' when the operation type is not
4525 * dclone() and store() is performed to memory.
4527 static int do_store(pTHX_
4537 ASSERT(!(f == 0 && !(optype & ST_CLONE)) || res,
4538 ("must supply result SV pointer for real recursion to memory"));
4540 TRACEMED(("do_store (optype=%d, netorder=%d)",
4541 optype, network_order));
4546 * Workaround for CROAK leak: if they enter with a "dirty" context,
4547 * free up memory for them now.
4552 clean_context(aTHX_ cxt);
4555 * Now that STORABLE_xxx hooks exist, it is possible that they try to
4556 * re-enter store() via the hooks. We need to stack contexts.
4560 cxt = allocate_context(aTHX_ cxt);
4566 ASSERT(cxt->entry == 1, ("starting new recursion"));
4567 ASSERT(!cxt->s_dirty, ("clean context"));
4570 * Ensure sv is actually a reference. From perl, we called something
4572 * pstore(aTHX_ FILE, \@array);
4573 * so we must get the scalar value behind that reference.
4577 CROAK(("Not a reference"));
4578 sv = SvRV(sv); /* So follow it to know what to store */
4581 * If we're going to store to memory, reset the buffer.
4588 * Prepare context and emit headers.
4591 init_store_context(aTHX_ cxt, f, optype, network_order);
4593 if (-1 == magic_write(aTHX_ cxt)) /* Emit magic and ILP info */
4594 return 0; /* Error */
4597 * Recursively store object...
4600 ASSERT(is_storing(aTHX), ("within store operation"));
4602 status = store(aTHX_ cxt, sv); /* Just do it! */
4605 * If they asked for a memory store and they provided an SV pointer,
4606 * make an SV string out of the buffer and fill their pointer.
4608 * When asking for ST_REAL, it's MANDATORY for the caller to provide
4609 * an SV, since context cleanup might free the buffer if we did recurse.
4610 * (unless caller is dclone(), which is aware of that).
4613 if (!cxt->fio && res)
4614 *res = mbuf2sv(aTHX);
4616 TRACEME(("do_store returns %d", status));
4621 * The "root" context is never freed, since it is meant to be always
4622 * handy for the common case where no recursion occurs at all (i.e.
4623 * we enter store() outside of any Storable code and leave it, period).
4624 * We know it's the "root" context because there's nothing stacked
4629 * When deep cloning, we don't free the context: doing so would force
4630 * us to copy the data in the memory buffer. Sicne we know we're
4631 * about to enter do_retrieve...
4634 clean_store_context(aTHX_ cxt);
4635 if (cxt->prev && !(cxt->optype & ST_CLONE))
4636 free_context(aTHX_ cxt);
4648 * Build a new SV out of the content of the internal memory buffer.
4650 static SV *mbuf2sv(pTHX)
4655 return newSVpv(mbase, MBUF_SIZE());
4659 *** Specific retrieve callbacks.
4665 * Return an error via croak, since it is not possible that we get here
4666 * under normal conditions, when facing a file produced via pstore().
4668 static SV *retrieve_other(pTHX_ stcxt_t *cxt, const char *cname)
4670 PERL_UNUSED_ARG(cname);
4672 cxt->ver_major != STORABLE_BIN_MAJOR &&
4673 cxt->ver_minor != STORABLE_BIN_MINOR
4675 CROAK(("Corrupted storable %s (binary v%d.%d), current is v%d.%d",
4676 cxt->fio ? "file" : "string",
4677 cxt->ver_major, cxt->ver_minor,
4678 STORABLE_BIN_MAJOR, STORABLE_BIN_MINOR));
4680 CROAK(("Corrupted storable %s (binary v%d.%d)",
4681 cxt->fio ? "file" : "string",
4682 cxt->ver_major, cxt->ver_minor));
4685 return (SV *) 0; /* Just in case */
4689 * retrieve_idx_blessed
4691 * Layout is SX_IX_BLESS <index> <object> with SX_IX_BLESS already read.
4692 * <index> can be coded on either 1 or 5 bytes.
4694 static SV *retrieve_idx_blessed(pTHX_ stcxt_t *cxt, const char *cname)
4697 const char *classname;
4701 PERL_UNUSED_ARG(cname);
4702 TRACEME(("retrieve_idx_blessed (#%d)", (int)cxt->tagnum));
4703 ASSERT(!cname, ("no bless-into class given here, got %s", cname));
4705 GETMARK(idx); /* Index coded on a single char? */
4710 * Fetch classname in 'aclass'
4713 sva = av_fetch(cxt->aclass, idx, FALSE);
4715 CROAK(("Class name #%" IVdf " should have been seen already",
4718 classname = SvPVX(*sva); /* We know it's a PV, by construction */
4720 TRACEME(("class ID %d => %s", (int)idx, classname));
4723 * Retrieve object and bless it.
4726 sv = retrieve(aTHX_ cxt, classname); /* First SV which is SEEN
4735 * Layout is SX_BLESS <len> <classname> <object> with SX_BLESS already read.
4736 * <len> can be coded on either 1 or 5 bytes.
4738 static SV *retrieve_blessed(pTHX_ stcxt_t *cxt, const char *cname)
4742 char buf[LG_BLESS + 1]; /* Avoid malloc() if possible */
4743 char *classname = buf;
4744 char *malloced_classname = NULL;
4746 PERL_UNUSED_ARG(cname);
4747 TRACEME(("retrieve_blessed (#%d)", (int)cxt->tagnum));
4748 ASSERT(!cname, ("no bless-into class given here, got %s", cname));
4751 * Decode class name length and read that name.
4753 * Short classnames have two advantages: their length is stored on one
4754 * single byte, and the string can be read on the stack.
4757 GETMARK(len); /* Length coded on a single char? */
4760 TRACEME(("** allocating %ld bytes for class name", (long)len+1));
4762 CROAK(("Corrupted classname length %lu", (long)len));
4763 PL_nomemok = TRUE; /* handle error by ourselves */
4764 New(10003, classname, len+1, char);
4767 CROAK(("Out of memory with len %ld", (long)len));
4769 malloced_classname = classname;
4771 SAFEPVREAD(classname, (I32)len, malloced_classname);
4772 classname[len] = '\0'; /* Mark string end */
4775 * It's a new classname, otherwise it would have been an SX_IX_BLESS.
4778 TRACEME(("new class name \"%s\" will bear ID = %d", classname,
4779 (int)cxt->classnum));
4781 if (!av_store(cxt->aclass, cxt->classnum++, newSVpvn(classname, len))) {
4782 Safefree(malloced_classname);
4787 * Retrieve object and bless it.
4790 sv = retrieve(aTHX_ cxt, classname); /* First SV which is SEEN will be blessed */
4791 if (malloced_classname)
4792 Safefree(malloced_classname);
4800 * Layout: SX_HOOK <flags> <len> <classname> <len2> <str> [<len3> <object-IDs>]
4801 * with leading mark already read, as usual.
4803 * When recursion was involved during serialization of the object, there
4804 * is an unknown amount of serialized objects after the SX_HOOK mark. Until
4805 * we reach a <flags> marker with the recursion bit cleared.
4807 * If the first <flags> byte contains a type of SHT_EXTRA, then the real type
4808 * is held in the <extra> byte, and if the object is tied, the serialized
4809 * magic object comes at the very end:
4811 * SX_HOOK <flags> <extra> ... [<len3> <object-IDs>] <magic object>
4813 * This means the STORABLE_thaw hook will NOT get a tied variable during its
4814 * processing (since we won't have seen the magic object by the time the hook
4815 * is called). See comments below for why it was done that way.
4817 static SV *retrieve_hook_common(pTHX_ stcxt_t *cxt, const char *cname, int large)
4820 char buf[LG_BLESS + 1]; /* Avoid malloc() if possible */
4821 char *classname = buf;
4833 int clone = cxt->optype & ST_CLONE;
4835 unsigned int extra_type = 0;
4837 int has_large_oids = 0;
4840 PERL_UNUSED_ARG(cname);
4841 TRACEME(("retrieve_hook (#%d)", (int)cxt->tagnum));
4842 ASSERT(!cname, ("no bless-into class given here, got %s", cname));
4846 PERL_UNUSED_ARG(large);
4850 * Read flags, which tell us about the type, and whether we need
4857 * Create the (empty) object, and mark it as seen.
4859 * This must be done now, because tags are incremented, and during
4860 * serialization, the object tag was affected before recursion could
4864 obj_type = flags & SHF_TYPE_MASK;
4870 sv = (SV *) newAV();
4873 sv = (SV *) newHV();
4877 * Read <extra> flag to know the type of the object.
4878 * Record associated magic type for later.
4880 GETMARK(extra_type);
4881 switch (extra_type) {
4887 sv = (SV *) newAV();
4891 sv = (SV *) newHV();
4895 return retrieve_other(aTHX_ cxt, 0);/* Let it croak */
4899 return retrieve_other(aTHX_ cxt, 0); /* Let it croak */
4901 SEEN0_NN(sv, 0); /* Don't bless yet */
4904 * Whilst flags tell us to recurse, do so.
4906 * We don't need to remember the addresses returned by retrieval, because
4907 * all the references will be obtained through indirection via the object
4908 * tags in the object-ID list.
4910 * We need to decrement the reference count for these objects
4911 * because, if the user doesn't save a reference to them in the hook,
4912 * they must be freed when this context is cleaned.
4915 while (flags & SHF_NEED_RECURSE) {
4916 TRACEME(("retrieve_hook recursing..."));
4917 rv = retrieve(aTHX_ cxt, 0);
4921 TRACEME(("retrieve_hook back with rv=0x%" UVxf,
4926 if (flags & SHF_IDX_CLASSNAME) {
4931 * Fetch index from 'aclass'
4934 if (flags & SHF_LARGE_CLASSLEN)
4939 sva = av_fetch(cxt->aclass, idx, FALSE);
4941 CROAK(("Class name #%" IVdf " should have been seen already",
4944 classname = SvPVX(*sva); /* We know it's a PV, by construction */
4945 TRACEME(("class ID %d => %s", (int)idx, classname));
4949 * Decode class name length and read that name.
4951 * NOTA BENE: even if the length is stored on one byte, we don't read
4952 * on the stack. Just like retrieve_blessed(), we limit the name to
4953 * LG_BLESS bytes. This is an arbitrary decision.
4955 char *malloced_classname = NULL;
4957 if (flags & SHF_LARGE_CLASSLEN)
4962 TRACEME(("** allocating %ld bytes for class name", (long)len+1));
4963 if (len > I32_MAX) /* security */
4964 CROAK(("Corrupted classname length %lu", (long)len));
4965 else if (len > LG_BLESS) { /* security: signed len */
4966 PL_nomemok = TRUE; /* handle error by ourselves */
4967 New(10003, classname, len+1, char);
4970 CROAK(("Out of memory with len %u", (unsigned)len+1));
4971 malloced_classname = classname;
4974 SAFEPVREAD(classname, (I32)len, malloced_classname);
4975 classname[len] = '\0'; /* Mark string end */
4978 * Record new classname.
4981 if (!av_store(cxt->aclass, cxt->classnum++,
4982 newSVpvn(classname, len))) {
4983 Safefree(malloced_classname);
4988 TRACEME(("class name: %s", classname));
4991 * Decode user-frozen string length and read it in an SV.
4993 * For efficiency reasons, we read data directly into the SV buffer.
4994 * To understand that code, read retrieve_scalar()
5003 if (flags & SHF_LARGE_STRLEN) {
5011 frozen = NEWSV(10002, len2 ? len2 : 1);
5013 SAFEREAD(SvPVX(frozen), len2, frozen);
5015 SvCUR_set(frozen, len2);
5016 *SvEND(frozen) = '\0';
5017 (void) SvPOK_only(frozen); /* Validates string pointer */
5018 if (cxt->s_tainted) /* Is input source tainted? */
5021 TRACEME(("frozen string: %d bytes", (int)len2));
5024 * Decode object-ID list length, if present.
5027 if (flags & SHF_HAS_LIST) {
5028 if (flags & SHF_LARGE_LISTLEN) {
5035 CROAK(("Large object ids in hook data not supported on 32-bit platforms"));
5044 av_extend(av, len3 + 1); /* Leave room for [0] */
5045 AvFILLp(av) = len3; /* About to be filled anyway */
5049 TRACEME(("has %d object IDs to link", (int)len3));
5052 * Read object-ID list into array.
5053 * Because we pre-extended it, we can cheat and fill it manually.
5055 * We read object tags and we can convert them into SV* on the fly
5056 * because we know all the references listed in there (as tags)
5057 * have been already serialized, hence we have a valid correspondence
5058 * between each of those tags and the recreated SV.
5062 SV **ary = AvARRAY(av);
5064 for (i = 1; i <= len3; i++) { /* We leave [0] alone */
5070 if (has_large_oids) {
5083 svh = av_fetch(cxt->aseen, tag, FALSE);
5085 if (tag == cxt->where_is_undef) {
5086 /* av_fetch uses PL_sv_undef internally, hence this
5087 somewhat gruesome hack. */
5091 CROAK(("Object #%" IVdf
5092 " should have been retrieved already",
5097 ary[i] = SvREFCNT_inc(xsv);
5102 * Look up the STORABLE_attach hook
5103 * If blessing is disabled, just return what we've got.
5105 if (!(cxt->flags & FLAG_BLESS_OK)) {
5106 TRACEME(("skipping bless because flags is %d", cxt->flags));
5111 * Bless the object and look up the STORABLE_thaw hook.
5113 stash = gv_stashpv(classname, GV_ADD);
5115 /* Handle attach case; again can't use pkg_can because it only
5116 * caches one method */
5117 attach = gv_fetchmethod_autoload(stash, "STORABLE_attach", FALSE);
5118 if (attach && isGV(attach)) {
5120 SV* attach_hook = newRV_inc((SV*) GvCV(attach));
5123 CROAK(("STORABLE_attach called with unexpected references"));
5127 AvARRAY(av)[0] = SvREFCNT_inc(frozen);
5128 rv = newSVpv(classname, 0);
5129 attached = scalar_call(aTHX_ rv, attach_hook, clone, av, G_SCALAR);
5130 /* Free memory after a call */
5132 SvREFCNT_dec(frozen);
5135 SvREFCNT_dec(attach_hook);
5138 sv_derived_from(attached, classname)
5141 /* refcnt of unneeded sv is 2 at this point
5142 (one from newHV, second from SEEN call) */
5145 /* we need to free RV but preserve value that RV point to */
5146 sv = SvRV(attached);
5148 SvRV_set(attached, NULL);
5149 SvREFCNT_dec(attached);
5150 if (!(flags & SHF_IDX_CLASSNAME) && classname != buf)
5151 Safefree(classname);
5154 CROAK(("STORABLE_attach did not return a %s object", classname));
5158 * Bless the object and look up the STORABLE_thaw hook.
5163 hook = pkg_can(aTHX_ cxt->hook, stash, "STORABLE_thaw");
5166 * Hook not found. Maybe they did not require the module where this
5167 * hook is defined yet?
5169 * If the load below succeeds, we'll be able to find the hook.
5170 * Still, it only works reliably when each class is defined in a
5174 TRACEME(("No STORABLE_thaw defined for objects of class %s", classname));
5175 TRACEME(("Going to load module '%s'", classname));
5176 load_module(PERL_LOADMOD_NOIMPORT, newSVpv(classname, 0), Nullsv);
5179 * We cache results of pkg_can, so we need to uncache before attempting
5183 pkg_uncache(aTHX_ cxt->hook, SvSTASH(sv), "STORABLE_thaw");
5184 hook = pkg_can(aTHX_ cxt->hook, SvSTASH(sv), "STORABLE_thaw");
5187 CROAK(("No STORABLE_thaw defined for objects of class %s "
5188 "(even after a \"require %s;\")", classname, classname));
5192 * If we don't have an 'av' yet, prepare one.
5193 * Then insert the frozen string as item [0].
5201 AvARRAY(av)[0] = SvREFCNT_inc(frozen);
5206 * $object->STORABLE_thaw($cloning, $frozen, @refs);
5208 * where $object is our blessed (empty) object, $cloning is a boolean
5209 * telling whether we're running a deep clone, $frozen is the frozen
5210 * string the user gave us in his serializing hook, and @refs, which may
5211 * be empty, is the list of extra references he returned along for us
5214 * In effect, the hook is an alternate creation routine for the class,
5215 * the object itself being already created by the runtime.
5218 TRACEME(("calling STORABLE_thaw on %s at 0x%" UVxf " (%" IVdf " args)",
5219 classname, PTR2UV(sv), (IV) AvFILLp(av) + 1));
5222 (void) scalar_call(aTHX_ rv, hook, clone, av, G_SCALAR|G_DISCARD);
5229 SvREFCNT_dec(frozen);
5232 if (!(flags & SHF_IDX_CLASSNAME) && classname != buf)
5233 Safefree(classname);
5236 * If we had an <extra> type, then the object was not as simple, and
5237 * we need to restore extra magic now.
5243 TRACEME(("retrieving magic object for 0x%" UVxf "...", PTR2UV(sv)));
5245 rv = retrieve(aTHX_ cxt, 0); /* Retrieve <magic object> */
5247 TRACEME(("restoring the magic object 0x%" UVxf " part of 0x%" UVxf,
5248 PTR2UV(rv), PTR2UV(sv)));
5250 switch (extra_type) {
5252 sv_upgrade(sv, SVt_PVMG);
5255 sv_upgrade(sv, SVt_PVAV);
5256 AvREAL_off((AV *)sv);
5259 sv_upgrade(sv, SVt_PVHV);
5262 CROAK(("Forgot to deal with extra type %d", extra_type));
5267 * Adding the magic only now, well after the STORABLE_thaw hook was called
5268 * means the hook cannot know it deals with an object whose variable is
5269 * tied. But this is happening when retrieving $o in the following case:
5273 * my $o = bless \%h, 'BAR';
5275 * The 'BAR' class is NOT the one where %h is tied into. Therefore, as
5276 * far as the 'BAR' class is concerned, the fact that %h is not a REAL
5277 * hash but a tied one should not matter at all, and remain transparent.
5278 * This means the magic must be restored by Storable AFTER the hook is
5281 * That looks very reasonable to me, but then I've come up with this
5282 * after a bug report from David Nesting, who was trying to store such
5283 * an object and caused Storable to fail. And unfortunately, it was
5284 * also the easiest way to retrofit support for blessed ref to tied objects
5285 * into the existing design. -- RAM, 17/02/2001
5288 sv_magic(sv, rv, mtype, (char *)NULL, 0);
5289 SvREFCNT_dec(rv); /* Undo refcnt inc from sv_magic() */
5294 static SV *retrieve_hook(pTHX_ stcxt_t *cxt, const char *cname) {
5295 return retrieve_hook_common(aTHX_ cxt, cname, FALSE);
5301 * Retrieve reference to some other scalar.
5302 * Layout is SX_REF <object>, with SX_REF already read.
5304 static SV *retrieve_ref(pTHX_ stcxt_t *cxt, const char *cname)
5310 TRACEME(("retrieve_ref (#%d)", (int)cxt->tagnum));
5313 * We need to create the SV that holds the reference to the yet-to-retrieve
5314 * object now, so that we may record the address in the seen table.
5315 * Otherwise, if the object to retrieve references us, we won't be able
5316 * to resolve the SX_OBJECT we'll see at that point! Hence we cannot
5317 * do the retrieve first and use rv = newRV(sv) since it will be too late
5318 * for SEEN() recording.
5321 rv = NEWSV(10002, 0);
5323 stash = gv_stashpv(cname, GV_ADD);
5326 SEEN_NN(rv, stash, 0); /* Will return if rv is null */
5327 sv = retrieve(aTHX_ cxt, 0);/* Retrieve <object> */
5329 return (SV *) 0; /* Failed */
5332 * WARNING: breaks RV encapsulation.
5334 * Now for the tricky part. We have to upgrade our existing SV, so that
5335 * it is now an RV on sv... Again, we cheat by duplicating the code
5336 * held in newSVrv(), since we already got our SV from retrieve().
5340 * SvRV(rv) = SvREFCNT_inc(sv);
5342 * here because the reference count we got from retrieve() above is
5343 * already correct: if the object was retrieved from the file, then
5344 * its reference count is one. Otherwise, if it was retrieved via
5345 * an SX_OBJECT indication, a ref count increment was done.
5349 /* No need to do anything, as rv will already be PVMG. */
5350 assert (SvTYPE(rv) == SVt_RV || SvTYPE(rv) >= SVt_PV);
5352 sv_upgrade(rv, SVt_RV);
5355 SvRV_set(rv, sv); /* $rv = \$sv */
5357 /*if (cxt->entry && ++cxt->ref_cnt > MAX_REF_CNT) {
5358 CROAK(("Max. recursion depth with nested refs exceeded"));
5361 TRACEME(("ok (retrieve_ref at 0x%" UVxf ")", PTR2UV(rv)));
5369 * Retrieve weak reference to some other scalar.
5370 * Layout is SX_WEAKREF <object>, with SX_WEAKREF already read.
5372 static SV *retrieve_weakref(pTHX_ stcxt_t *cxt, const char *cname)
5376 TRACEME(("retrieve_weakref (#%d)", (int)cxt->tagnum));
5378 sv = retrieve_ref(aTHX_ cxt, cname);
5390 * retrieve_overloaded
5392 * Retrieve reference to some other scalar with overloading.
5393 * Layout is SX_OVERLOAD <object>, with SX_OVERLOAD already read.
5395 static SV *retrieve_overloaded(pTHX_ stcxt_t *cxt, const char *cname)
5401 TRACEME(("retrieve_overloaded (#%d)", (int)cxt->tagnum));
5404 * Same code as retrieve_ref(), duplicated to avoid extra call.
5407 rv = NEWSV(10002, 0);
5408 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5409 SEEN_NN(rv, stash, 0); /* Will return if rv is null */
5410 cxt->in_retrieve_overloaded = 1; /* so sv_bless doesn't call S_reset_amagic */
5411 sv = retrieve(aTHX_ cxt, 0); /* Retrieve <object> */
5412 cxt->in_retrieve_overloaded = 0;
5414 return (SV *) 0; /* Failed */
5417 * WARNING: breaks RV encapsulation.
5420 SvUPGRADE(rv, SVt_RV);
5421 SvRV_set(rv, sv); /* $rv = \$sv */
5425 * Restore overloading magic.
5428 stash = SvTYPE(sv) ? (HV *) SvSTASH (sv) : 0;
5430 CROAK(("Cannot restore overloading on %s(0x%" UVxf
5431 ") (package <unknown>)",
5432 sv_reftype(sv, FALSE),
5435 if (!Gv_AMG(stash)) {
5436 const char *package = HvNAME_get(stash);
5437 TRACEME(("No overloading defined for package %s", package));
5438 TRACEME(("Going to load module '%s'", package));
5439 load_module(PERL_LOADMOD_NOIMPORT, newSVpv(package, 0), Nullsv);
5440 if (!Gv_AMG(stash)) {
5441 CROAK(("Cannot restore overloading on %s(0x%" UVxf
5442 ") (package %s) (even after a \"require %s;\")",
5443 sv_reftype(sv, FALSE),
5451 TRACEME(("ok (retrieve_overloaded at 0x%" UVxf ")", PTR2UV(rv)));
5457 * retrieve_weakoverloaded
5459 * Retrieve weak overloaded reference to some other scalar.
5460 * Layout is SX_WEAKOVERLOADED <object>, with SX_WEAKOVERLOADED already read.
5462 static SV *retrieve_weakoverloaded(pTHX_ stcxt_t *cxt, const char *cname)
5466 TRACEME(("retrieve_weakoverloaded (#%d)", (int)cxt->tagnum));
5468 sv = retrieve_overloaded(aTHX_ cxt, cname);
5480 * retrieve_tied_array
5482 * Retrieve tied array
5483 * Layout is SX_TIED_ARRAY <object>, with SX_TIED_ARRAY already read.
5485 static SV *retrieve_tied_array(pTHX_ stcxt_t *cxt, const char *cname)
5491 TRACEME(("retrieve_tied_array (#%d)", (int)cxt->tagnum));
5493 if (!(cxt->flags & FLAG_TIE_OK)) {
5494 CROAK(("Tying is disabled."));
5497 tv = NEWSV(10002, 0);
5498 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5499 SEEN_NN(tv, stash, 0); /* Will return if tv is null */
5500 sv = retrieve(aTHX_ cxt, 0); /* Retrieve <object> */
5502 return (SV *) 0; /* Failed */
5504 sv_upgrade(tv, SVt_PVAV);
5505 sv_magic(tv, sv, 'P', (char *)NULL, 0);
5506 SvREFCNT_dec(sv); /* Undo refcnt inc from sv_magic() */
5508 TRACEME(("ok (retrieve_tied_array at 0x%" UVxf ")", PTR2UV(tv)));
5514 * retrieve_tied_hash
5516 * Retrieve tied hash
5517 * Layout is SX_TIED_HASH <object>, with SX_TIED_HASH already read.
5519 static SV *retrieve_tied_hash(pTHX_ stcxt_t *cxt, const char *cname)
5525 TRACEME(("retrieve_tied_hash (#%d)", (int)cxt->tagnum));
5527 if (!(cxt->flags & FLAG_TIE_OK)) {
5528 CROAK(("Tying is disabled."));
5531 tv = NEWSV(10002, 0);
5532 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5533 SEEN_NN(tv, stash, 0); /* Will return if tv is null */
5534 sv = retrieve(aTHX_ cxt, 0); /* Retrieve <object> */
5536 return (SV *) 0; /* Failed */
5538 sv_upgrade(tv, SVt_PVHV);
5539 sv_magic(tv, sv, 'P', (char *)NULL, 0);
5540 SvREFCNT_dec(sv); /* Undo refcnt inc from sv_magic() */
5542 TRACEME(("ok (retrieve_tied_hash at 0x%" UVxf ")", PTR2UV(tv)));
5548 * retrieve_tied_scalar
5550 * Retrieve tied scalar
5551 * Layout is SX_TIED_SCALAR <object>, with SX_TIED_SCALAR already read.
5553 static SV *retrieve_tied_scalar(pTHX_ stcxt_t *cxt, const char *cname)
5556 SV *sv, *obj = NULL;
5559 TRACEME(("retrieve_tied_scalar (#%d)", (int)cxt->tagnum));
5561 if (!(cxt->flags & FLAG_TIE_OK)) {
5562 CROAK(("Tying is disabled."));
5565 tv = NEWSV(10002, 0);
5566 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5567 SEEN_NN(tv, stash, 0); /* Will return if rv is null */
5568 sv = retrieve(aTHX_ cxt, 0); /* Retrieve <object> */
5570 return (SV *) 0; /* Failed */
5572 else if (SvTYPE(sv) != SVt_NULL) {
5576 sv_upgrade(tv, SVt_PVMG);
5577 sv_magic(tv, obj, 'q', (char *)NULL, 0);
5580 /* Undo refcnt inc from sv_magic() */
5584 TRACEME(("ok (retrieve_tied_scalar at 0x%" UVxf ")", PTR2UV(tv)));
5592 * Retrieve reference to value in a tied hash.
5593 * Layout is SX_TIED_KEY <object> <key>, with SX_TIED_KEY already read.
5595 static SV *retrieve_tied_key(pTHX_ stcxt_t *cxt, const char *cname)
5602 TRACEME(("retrieve_tied_key (#%d)", (int)cxt->tagnum));
5604 if (!(cxt->flags & FLAG_TIE_OK)) {
5605 CROAK(("Tying is disabled."));
5608 tv = NEWSV(10002, 0);
5609 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5610 SEEN_NN(tv, stash, 0); /* Will return if tv is null */
5611 sv = retrieve(aTHX_ cxt, 0); /* Retrieve <object> */
5613 return (SV *) 0; /* Failed */
5615 key = retrieve(aTHX_ cxt, 0); /* Retrieve <key> */
5617 return (SV *) 0; /* Failed */
5619 sv_upgrade(tv, SVt_PVMG);
5620 sv_magic(tv, sv, 'p', (char *)key, HEf_SVKEY);
5621 SvREFCNT_dec(key); /* Undo refcnt inc from sv_magic() */
5622 SvREFCNT_dec(sv); /* Undo refcnt inc from sv_magic() */
5630 * Retrieve reference to value in a tied array.
5631 * Layout is SX_TIED_IDX <object> <idx>, with SX_TIED_IDX already read.
5633 static SV *retrieve_tied_idx(pTHX_ stcxt_t *cxt, const char *cname)
5640 TRACEME(("retrieve_tied_idx (#%d)", (int)cxt->tagnum));
5642 if (!(cxt->flags & FLAG_TIE_OK)) {
5643 CROAK(("Tying is disabled."));
5646 tv = NEWSV(10002, 0);
5647 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5648 SEEN_NN(tv, stash, 0); /* Will return if tv is null */
5649 sv = retrieve(aTHX_ cxt, 0); /* Retrieve <object> */
5651 return (SV *) 0; /* Failed */
5653 RLEN(idx); /* Retrieve <idx> */
5655 sv_upgrade(tv, SVt_PVMG);
5656 sv_magic(tv, sv, 'p', (char *)NULL, idx);
5657 SvREFCNT_dec(sv); /* Undo refcnt inc from sv_magic() */
5665 * Helper to read a string
5667 static SV *get_lstring(pTHX_ stcxt_t *cxt, UV len, int isutf8, const char *cname)
5672 TRACEME(("get_lstring (#%d), len = %" UVuf, (int)cxt->tagnum, len));
5675 * Allocate an empty scalar of the suitable length.
5678 sv = NEWSV(10002, len);
5679 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5680 SEEN_NN(sv, stash, 0); /* Associate this new scalar with tag "tagnum" */
5688 * WARNING: duplicates parts of sv_setpv and breaks SV data encapsulation.
5690 * Now, for efficiency reasons, read data directly inside the SV buffer,
5691 * and perform the SV final settings directly by duplicating the final
5692 * work done by sv_setpv. Since we're going to allocate lots of scalars
5693 * this way, it's worth the hassle and risk.
5696 SAFEREAD(SvPVX(sv), len, sv);
5697 SvCUR_set(sv, len); /* Record C string length */
5698 *SvEND(sv) = '\0'; /* Ensure it's null terminated anyway */
5699 (void) SvPOK_only(sv); /* Validate string pointer */
5700 if (cxt->s_tainted) /* Is input source tainted? */
5701 SvTAINT(sv); /* External data cannot be trusted */
5703 /* Check for CVE-215-1592 */
5704 if (cname && len == 13 && strEQc(cname, "CGITempFile")
5705 && strEQc(SvPVX(sv), "mt-config.cgi")) {
5706 #if defined(USE_CPERL) && defined(WARN_SECURITY)
5707 Perl_warn_security(aTHX_
5708 "Movable-Type CVE-2015-1592 Storable metasploit attack");
5711 "SECURITY: Movable-Type CVE-2015-1592 Storable metasploit attack");
5716 TRACEME(("large utf8 string len %" UVuf " '%s'", len,
5717 len >= 2048 ? "<string too long>" : SvPVX(sv)));
5718 #ifdef HAS_UTF8_SCALARS
5721 if (cxt->use_bytes < 0)
5723 = (SvTRUE(get_sv("Storable::drop_utf8", GV_ADD))
5725 if (cxt->use_bytes == 0)
5729 TRACEME(("large string len %" UVuf " '%s'", len,
5730 len >= 2048 ? "<string too long>" : SvPVX(sv)));
5732 TRACEME(("ok (get_lstring at 0x%" UVxf ")", PTR2UV(sv)));
5740 * Retrieve defined long (string) scalar.
5742 * Layout is SX_LSCALAR <length> <data>, with SX_LSCALAR already read.
5743 * The scalar is "long" in that <length> is larger than LG_SCALAR so it
5744 * was not stored on a single byte, but in 4 bytes. For strings longer than
5745 * 4 byte (>2GB) see retrieve_lobject.
5747 static SV *retrieve_lscalar(pTHX_ stcxt_t *cxt, const char *cname)
5751 return get_lstring(aTHX_ cxt, len, 0, cname);
5757 * Retrieve defined short (string) scalar.
5759 * Layout is SX_SCALAR <length> <data>, with SX_SCALAR already read.
5760 * The scalar is "short" so <length> is single byte. If it is 0, there
5761 * is no <data> section.
5763 static SV *retrieve_scalar(pTHX_ stcxt_t *cxt, const char *cname)
5770 TRACEME(("retrieve_scalar (#%d), len = %d", (int)cxt->tagnum, len));
5771 return get_lstring(aTHX_ cxt, (UV)len, 0, cname);
5777 * Like retrieve_scalar(), but tag result as utf8.
5778 * If we're retrieving UTF8 data in a non-UTF8 perl, croaks.
5780 static SV *retrieve_utf8str(pTHX_ stcxt_t *cxt, const char *cname)
5785 TRACEME(("retrieve_utf8str"));
5787 return get_lstring(aTHX_ cxt, (UV)len, 1, cname);
5793 * Like retrieve_lscalar(), but tag result as utf8.
5794 * If we're retrieving UTF8 data in a non-UTF8 perl, croaks.
5796 static SV *retrieve_lutf8str(pTHX_ stcxt_t *cxt, const char *cname)
5800 TRACEME(("retrieve_lutf8str"));
5803 return get_lstring(aTHX_ cxt, (UV)len, 1, cname);
5809 * Retrieve a vstring, and then retrieve the stringy scalar following it,
5810 * attaching the vstring to the scalar via magic.
5811 * If we're retrieving a vstring in a perl without vstring magic, croaks.
5813 * The vstring layout mirrors an SX_SCALAR string:
5814 * SX_VSTRING <length> <data> with SX_VSTRING already read.
5816 static SV *retrieve_vstring(pTHX_ stcxt_t *cxt, const char *cname)
5824 TRACEME(("retrieve_vstring (#%d), len = %d", (int)cxt->tagnum, len));
5827 sv = retrieve(aTHX_ cxt, cname);
5829 return (SV *) 0; /* Failed */
5830 sv_magic(sv,NULL,PERL_MAGIC_vstring,s,len);
5831 /* 5.10.0 and earlier seem to need this */
5834 TRACEME(("ok (retrieve_vstring at 0x%" UVxf ")", PTR2UV(sv)));
5845 * Like retrieve_vstring, but for longer vstrings.
5847 static SV *retrieve_lvstring(pTHX_ stcxt_t *cxt, const char *cname)
5855 TRACEME(("retrieve_lvstring (#%d), len = %" UVuf,
5856 (int)cxt->tagnum, (UV)len));
5858 /* Since we'll no longer produce such large vstrings, reject them
5861 if (len >= I32_MAX) {
5862 CROAK(("vstring too large to fetch"));
5865 New(10003, s, len+1, char);
5866 SAFEPVREAD(s, (I32)len, s);
5868 sv = retrieve(aTHX_ cxt, cname);
5871 return (SV *) 0; /* Failed */
5873 sv_magic(sv,NULL,PERL_MAGIC_vstring,s,len);
5874 /* 5.10.0 and earlier seem to need this */
5879 TRACEME(("ok (retrieve_lvstring at 0x%" UVxf ")", PTR2UV(sv)));
5890 * Retrieve defined integer.
5891 * Layout is SX_INTEGER <data>, whith SX_INTEGER already read.
5893 static SV *retrieve_integer(pTHX_ stcxt_t *cxt, const char *cname)
5899 TRACEME(("retrieve_integer (#%d)", (int)cxt->tagnum));
5901 READ(&iv, sizeof(iv));
5903 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5904 SEEN_NN(sv, stash, 0); /* Associate this new scalar with tag "tagnum" */
5906 TRACEME(("integer %" IVdf, iv));
5907 TRACEME(("ok (retrieve_integer at 0x%" UVxf ")", PTR2UV(sv)));
5913 * retrieve_boolean_true
5915 * Retrieve boolean true copy.
5917 static SV *retrieve_boolean_true(pTHX_ stcxt_t *cxt, const char *cname)
5922 TRACEME(("retrieve_boolean_true (#%d)", (int)cxt->tagnum));
5924 sv = newSVsv(&PL_sv_yes);
5925 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5926 SEEN_NN(sv, stash, 0); /* Associate this new scalar with tag "tagnum" */
5928 TRACEME(("boolean true"));
5929 TRACEME(("ok (retrieve_boolean_true at 0x%" UVxf ")", PTR2UV(sv)));
5935 * retrieve_boolean_false
5937 * Retrieve boolean false copy.
5939 static SV *retrieve_boolean_false(pTHX_ stcxt_t *cxt, const char *cname)
5944 TRACEME(("retrieve_boolean_false (#%d)", (int)cxt->tagnum));
5946 sv = newSVsv(&PL_sv_no);
5947 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5948 SEEN_NN(sv, stash, 0); /* Associate this new scalar with tag "tagnum" */
5950 TRACEME(("boolean false"));
5951 TRACEME(("ok (retrieve_boolean_false at 0x%" UVxf ")", PTR2UV(sv)));
5959 * Retrieve overlong scalar, array or hash.
5960 * Layout is SX_LOBJECT type U64_len ...
5962 static SV *retrieve_lobject(pTHX_ stcxt_t *cxt, const char *cname)
5971 TRACEME(("retrieve_lobject (#%d)", (int)cxt->tagnum));
5974 TRACEME(("object type %d", type));
5977 if (type == SX_FLAG_HASH) {
5978 /* we write the flags immediately after the op. I could have
5979 changed the writer, but this may allow someone to recover
5980 data they're already frozen, though such a very large hash
5983 GETMARK(hash_flags);
5985 else if (type == SX_HOOK) {
5986 return retrieve_hook_common(aTHX_ cxt, cname, TRUE);
5990 TRACEME(("wlen %" UVuf, len));
5994 /* not a large object, just a large index */
5995 SV **svh = av_fetch(cxt->aseen, len, FALSE);
5997 CROAK(("Object #%" UVuf " should have been retrieved already",
6000 TRACEME(("had retrieved #%" UVuf " at 0x%" UVxf, len, PTR2UV(sv)));
6005 sv = get_lstring(aTHX_ cxt, len, 0, cname);
6008 sv = get_lstring(aTHX_ cxt, len, 1, cname);
6011 sv = get_larray(aTHX_ cxt, len, cname);
6013 /* <5.12 you could store larger hashes, but cannot iterate over them.
6014 So we reject them, it's a bug. */
6016 sv = get_lhash(aTHX_ cxt, len, hash_flags, cname);
6019 sv = get_lhash(aTHX_ cxt, len, 0, cname);
6022 CROAK(("Unexpected type %d in retrieve_lobject\n", type));
6025 TRACEME(("ok (retrieve_lobject at 0x%" UVxf ")", PTR2UV(sv)));
6028 PERL_UNUSED_ARG(cname);
6030 /* previously this (brokenly) checked the length value and only failed if
6031 the length was over 4G.
6032 Since this op should only occur with objects over 4GB (or 2GB) we can just
6035 CROAK(("Invalid large object op for this 32bit system"));
6042 * Retrieve defined integer in network order.
6043 * Layout is SX_NETINT <data>, whith SX_NETINT already read.
6045 static SV *retrieve_netint(pTHX_ stcxt_t *cxt, const char *cname)
6051 TRACEME(("retrieve_netint (#%d)", (int)cxt->tagnum));
6055 sv = newSViv((int) ntohl(iv));
6056 TRACEME(("network integer %d", (int) ntohl(iv)));
6059 TRACEME(("network integer (as-is) %d", iv));
6061 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
6062 SEEN_NN(sv, stash, 0); /* Associate this new scalar with tag "tagnum" */
6064 TRACEME(("ok (retrieve_netint at 0x%" UVxf ")", PTR2UV(sv)));
6072 * Retrieve defined double.
6073 * Layout is SX_DOUBLE <data>, whith SX_DOUBLE already read.
6075 static SV *retrieve_double(pTHX_ stcxt_t *cxt, const char *cname)
6081 TRACEME(("retrieve_double (#%d)", (int)cxt->tagnum));
6083 READ(&nv, sizeof(nv));
6085 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
6086 SEEN_NN(sv, stash, 0); /* Associate this new scalar with tag "tagnum" */
6088 TRACEME(("double %" NVff, nv));
6089 TRACEME(("ok (retrieve_double at 0x%" UVxf ")", PTR2UV(sv)));
6097 * Retrieve defined byte (small integer within the [-128, +127] range).
6098 * Layout is SX_BYTE <data>, whith SX_BYTE already read.
6100 static SV *retrieve_byte(pTHX_ stcxt_t *cxt, const char *cname)
6106 /* MSVC 2017 doesn't handle the AIX workaround well */
6109 signed char tmp; /* Workaround for AIX cc bug --H.Merijn Brand */
6112 TRACEME(("retrieve_byte (#%d)", (int)cxt->tagnum));
6115 TRACEME(("small integer read as %d", (unsigned char) siv));
6116 tmp = (unsigned char) siv - 128;
6118 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
6119 SEEN_NN(sv, stash, 0); /* Associate this new scalar with tag "tagnum" */
6121 TRACEME(("byte %d", tmp));
6122 TRACEME(("ok (retrieve_byte at 0x%" UVxf ")", PTR2UV(sv)));
6130 * Return the undefined value.
6132 static SV *retrieve_undef(pTHX_ stcxt_t *cxt, const char *cname)
6137 TRACEME(("retrieve_undef"));
6140 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
6141 SEEN_NN(sv, stash, 0);
6149 * Return the immortal undefined value.
6151 static SV *retrieve_sv_undef(pTHX_ stcxt_t *cxt, const char *cname)
6153 SV *sv = &PL_sv_undef;
6156 TRACEME(("retrieve_sv_undef"));
6158 /* Special case PL_sv_undef, as av_fetch uses it internally to mark
6159 deleted elements, and will return NULL (fetch failed) whenever it
6161 if (cxt->where_is_undef == UNSET_NTAG_T) {
6162 cxt->where_is_undef = cxt->tagnum;
6164 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
6165 SEEN_NN(sv, stash, 1);
6172 * Return the immortal yes value.
6174 static SV *retrieve_sv_yes(pTHX_ stcxt_t *cxt, const char *cname)
6176 SV *sv = &PL_sv_yes;
6179 TRACEME(("retrieve_sv_yes"));
6181 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
6182 SEEN_NN(sv, stash, 1);
6189 * Return the immortal no value.
6191 static SV *retrieve_sv_no(pTHX_ stcxt_t *cxt, const char *cname)
6196 TRACEME(("retrieve_sv_no"));
6198 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
6199 SEEN_NN(sv, stash, 1);
6204 * retrieve_svundef_elem
6206 * Return &PL_sv_placeholder, representing &PL_sv_undef in an array. This
6207 * is a bit of a hack, but we already use SX_SV_UNDEF to mean a nonexistent
6208 * element, for historical reasons.
6210 static SV *retrieve_svundef_elem(pTHX_ stcxt_t *cxt, const char *cname)
6212 TRACEME(("retrieve_svundef_elem"));
6214 /* SEEN reads the contents of its SV argument, which we are not
6215 supposed to do with &PL_sv_placeholder. */
6216 SEEN_NN(&PL_sv_undef, cname, 1);
6218 return &PL_sv_placeholder;
6224 * Retrieve a whole array.
6225 * Layout is SX_ARRAY <size> followed by each item, in increasing index order.
6226 * Each item is stored as <object>.
6228 * When we come here, SX_ARRAY has been read already.
6230 static SV *retrieve_array(pTHX_ stcxt_t *cxt, const char *cname)
6236 bool seen_null = FALSE;
6238 TRACEME(("retrieve_array (#%d)", (int)cxt->tagnum));
6241 * Read length, and allocate array, then pre-extend it.
6245 TRACEME(("size = %d", (int)len));
6247 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
6248 SEEN_NN(av, stash, 0); /* Will return if array not allocated nicely */
6252 return (SV *) av; /* No data follow if array is empty */
6255 * Now get each item in turn...
6258 for (i = 0; i < len; i++) {
6259 TRACEME(("(#%d) item", (int)i));
6260 sv = retrieve(aTHX_ cxt, 0); /* Retrieve item */
6263 if (sv == &PL_sv_undef) {
6267 if (sv == &PL_sv_placeholder)
6269 if (av_store(av, i, sv) == 0)
6272 if (seen_null) av_fill(av, len-1);
6274 TRACEME(("ok (retrieve_array at 0x%" UVxf ")", PTR2UV(av)));
6281 /* internal method with len already read */
6283 static SV *get_larray(pTHX_ stcxt_t *cxt, UV len, const char *cname)
6289 bool seen_null = FALSE;
6291 TRACEME(("get_larray (#%d) %lu", (int)cxt->tagnum, (unsigned long)len));
6294 * allocate array, then pre-extend it.
6298 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
6299 SEEN_NN(av, stash, 0); /* Will return if array not allocated nicely */
6304 * Now get each item in turn...
6307 for (i = 0; i < len; i++) {
6308 TRACEME(("(#%d) item", (int)i));
6309 sv = retrieve(aTHX_ cxt, 0); /* Retrieve item */
6312 if (sv == &PL_sv_undef) {
6316 if (sv == &PL_sv_placeholder)
6318 if (av_store(av, i, sv) == 0)
6321 if (seen_null) av_fill(av, len-1);
6323 TRACEME(("ok (get_larray at 0x%" UVxf ")", PTR2UV(av)));
6331 * Retrieve a overlong hash table.
6332 * <len> is already read. What follows is each key/value pair, in random order.
6333 * Keys are stored as <length> <data>, the <data> section being omitted
6335 * Values are stored as <object>.
6338 static SV *get_lhash(pTHX_ stcxt_t *cxt, UV len, int hash_flags, const char *cname)
6346 TRACEME(("get_lhash (#%d)", (int)cxt->tagnum));
6348 #ifdef HAS_RESTRICTED_HASHES
6349 PERL_UNUSED_ARG(hash_flags);
6351 if (hash_flags & SHV_RESTRICTED) {
6352 if (cxt->derestrict < 0)
6353 cxt->derestrict = (SvTRUE
6354 (get_sv("Storable::downgrade_restricted", GV_ADD))
6356 if (cxt->derestrict == 0)
6357 RESTRICTED_HASH_CROAK();
6361 TRACEME(("size = %lu", (unsigned long)len));
6363 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
6364 SEEN_NN(hv, stash, 0); /* Will return if table not allocated properly */
6366 return (SV *) hv; /* No data follow if table empty */
6367 TRACEME(("split %lu", (unsigned long)len+1));
6368 hv_ksplit(hv, len+1); /* pre-extend hash to save multiple splits */
6371 * Now get each key/value pair in turn...
6374 for (i = 0; i < len; i++) {
6379 TRACEME(("(#%d) value", (int)i));
6380 sv = retrieve(aTHX_ cxt, 0);
6386 * Since we're reading into kbuf, we must ensure we're not
6387 * recursing between the read and the hv_store() where it's used.
6388 * Hence the key comes after the value.
6391 RLEN(size); /* Get key size */
6392 KBUFCHK((STRLEN)size); /* Grow hash key read pool if needed */
6395 kbuf[size] = '\0'; /* Mark string end, just in case */
6396 TRACEME(("(#%d) key '%s'", (int)i, kbuf));
6399 * Enter key/value pair into hash table.
6402 if (hv_store(hv, kbuf, (U32) size, sv, 0) == 0)
6406 TRACEME(("ok (get_lhash at 0x%" UVxf ")", PTR2UV(hv)));
6414 * Retrieve a whole hash table.
6415 * Layout is SX_HASH <size> followed by each key/value pair, in random order.
6416 * Keys are stored as <length> <data>, the <data> section being omitted
6418 * Values are stored as <object>.
6420 * When we come here, SX_HASH has been read already.
6422 static SV *retrieve_hash(pTHX_ stcxt_t *cxt, const char *cname)
6431 TRACEME(("retrieve_hash (#%d)", (int)cxt->tagnum));
6434 * Read length, allocate table.
6438 TRACEME(("size = %d", (int)len));
6440 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
6441 SEEN_NN(hv, stash, 0); /* Will return if table not allocated properly */
6443 return (SV *) hv; /* No data follow if table empty */
6444 TRACEME(("split %d", (int)len+1));
6445 hv_ksplit(hv, len+1); /* pre-extend hash to save multiple splits */
6448 * Now get each key/value pair in turn...
6451 for (i = 0; i < len; i++) {
6456 TRACEME(("(#%d) value", (int)i));
6457 sv = retrieve(aTHX_ cxt, 0);
6463 * Since we're reading into kbuf, we must ensure we're not
6464 * recursing between the read and the hv_store() where it's used.
6465 * Hence the key comes after the value.
6468 RLEN(size); /* Get key size */
6469 KBUFCHK((STRLEN)size); /* Grow hash key read pool if needed */
6472 kbuf[size] = '\0'; /* Mark string end, just in case */
6473 TRACEME(("(#%d) key '%s'", (int)i, kbuf));
6476 * Enter key/value pair into hash table.
6479 if (hv_store(hv, kbuf, (U32) size, sv, 0) == 0)
6483 TRACEME(("ok (retrieve_hash at 0x%" UVxf ")", PTR2UV(hv)));
6491 * Retrieve a whole hash table.
6492 * Layout is SX_HASH <size> followed by each key/value pair, in random order.
6493 * Keys are stored as <length> <data>, the <data> section being omitted
6495 * Values are stored as <object>.
6497 * When we come here, SX_HASH has been read already.
6499 static SV *retrieve_flag_hash(pTHX_ stcxt_t *cxt, const char *cname)
6510 GETMARK(hash_flags);
6511 TRACEME(("retrieve_flag_hash (#%d)", (int)cxt->tagnum));
6513 * Read length, allocate table.
6516 #ifndef HAS_RESTRICTED_HASHES
6517 if (hash_flags & SHV_RESTRICTED) {
6518 if (cxt->derestrict < 0)
6519 cxt->derestrict = (SvTRUE
6520 (get_sv("Storable::downgrade_restricted", GV_ADD))
6522 if (cxt->derestrict == 0)
6523 RESTRICTED_HASH_CROAK();
6528 TRACEME(("size = %d, flags = %d", (int)len, hash_flags));
6530 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
6531 SEEN_NN(hv, stash, 0); /* Will return if table not allocated properly */
6533 return (SV *) hv; /* No data follow if table empty */
6534 TRACEME(("split %d", (int)len+1));
6535 hv_ksplit(hv, len+1); /* pre-extend hash to save multiple splits */
6538 * Now get each key/value pair in turn...
6541 for (i = 0; i < len; i++) {
6543 int store_flags = 0;
6548 TRACEME(("(#%d) value", (int)i));
6549 sv = retrieve(aTHX_ cxt, 0);
6554 #ifdef HAS_RESTRICTED_HASHES
6555 if ((hash_flags & SHV_RESTRICTED) && (flags & SHV_K_LOCKED))
6559 if (flags & SHV_K_ISSV) {
6560 /* XXX you can't set a placeholder with an SV key.
6561 Then again, you can't get an SV key.
6562 Without messing around beyond what the API is supposed to do.
6565 TRACEME(("(#%d) keysv, flags=%d", (int)i, flags));
6566 keysv = retrieve(aTHX_ cxt, 0);
6570 if (!hv_store_ent(hv, keysv, sv, 0))
6575 * Since we're reading into kbuf, we must ensure we're not
6576 * recursing between the read and the hv_store() where it's used.
6577 * Hence the key comes after the value.
6580 if (flags & SHV_K_PLACEHOLDER) {
6582 sv = &PL_sv_placeholder;
6583 store_flags |= HVhek_PLACEHOLD;
6585 if (flags & SHV_K_UTF8) {
6586 #ifdef HAS_UTF8_HASHES
6587 store_flags |= HVhek_UTF8;
6589 if (cxt->use_bytes < 0)
6591 = (SvTRUE(get_sv("Storable::drop_utf8", GV_ADD))
6593 if (cxt->use_bytes == 0)
6597 #ifdef HAS_UTF8_HASHES
6598 if (flags & SHV_K_WASUTF8)
6599 store_flags |= HVhek_WASUTF8;
6602 RLEN(size); /* Get key size */
6603 KBUFCHK((STRLEN)size);/* Grow hash key read pool if needed */
6606 kbuf[size] = '\0'; /* Mark string end, just in case */
6607 TRACEME(("(#%d) key '%s' flags %X store_flags %X", (int)i, kbuf,
6608 flags, store_flags));
6611 * Enter key/value pair into hash table.
6614 #ifdef HAS_RESTRICTED_HASHES
6615 if (hv_store_flags(hv, kbuf, size, sv, 0, store_flags) == 0)
6618 if (!(store_flags & HVhek_PLACEHOLD))
6619 if (hv_store(hv, kbuf, size, sv, 0) == 0)
6624 #ifdef HAS_RESTRICTED_HASHES
6625 if (hash_flags & SHV_RESTRICTED)
6629 TRACEME(("ok (retrieve_hash at 0x%" UVxf ")", PTR2UV(hv)));
6637 * Return a code reference.
6639 static SV *retrieve_code(pTHX_ stcxt_t *cxt, const char *cname)
6645 SV *sv, *text, *sub, *errsv;
6648 TRACEME(("retrieve_code (#%d)", (int)cxt->tagnum));
6651 * Insert dummy SV in the aseen array so that we don't screw
6652 * up the tag numbers. We would just make the internal
6653 * scalar an untagged item in the stream, but
6654 * retrieve_scalar() calls SEEN(). So we just increase the
6657 tagnum = cxt->tagnum;
6659 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
6660 SEEN_NN(sv, stash, 0);
6663 * Retrieve the source of the code reference
6664 * as a small or large scalar
6670 text = retrieve_scalar(aTHX_ cxt, cname);
6673 text = retrieve_lscalar(aTHX_ cxt, cname);
6676 text = retrieve_utf8str(aTHX_ cxt, cname);
6679 text = retrieve_lutf8str(aTHX_ cxt, cname);
6682 CROAK(("Unexpected type %d in retrieve_code\n", (int)type));
6686 CROAK(("Unable to retrieve code\n"));
6690 * prepend "sub " to the source
6693 sub = newSVpvs("sub ");
6696 sv_catpv(sub, SvPV_nolen(text)); /* XXX no sv_catsv! */
6700 * evaluate the source to a code reference and use the CV value
6703 if (cxt->eval == NULL) {
6704 cxt->eval = get_sv("Storable::Eval", GV_ADD);
6705 SvREFCNT_inc(cxt->eval);
6707 if (!SvTRUE(cxt->eval)) {
6708 if (cxt->forgive_me == 0 ||
6709 (cxt->forgive_me < 0 &&
6710 !(cxt->forgive_me = SvTRUE
6711 (get_sv("Storable::forgive_me", GV_ADD)) ? 1 : 0))
6713 CROAK(("Can't eval, please set $Storable::Eval to a true value"));
6716 /* fix up the dummy entry... */
6717 av_store(cxt->aseen, tagnum, SvREFCNT_inc(sv));
6725 errsv = get_sv("@", GV_ADD);
6726 SvPVCLEAR(errsv); /* clear $@ */
6727 if (SvROK(cxt->eval) && SvTYPE(SvRV(cxt->eval)) == SVt_PVCV) {
6729 XPUSHs(sv_2mortal(newSVsv(sub)));
6731 count = call_sv(cxt->eval, G_SCALAR);
6733 CROAK(("Unexpected return value from $Storable::Eval callback\n"));
6735 eval_sv(sub, G_SCALAR);
6741 if (SvTRUE(errsv)) {
6742 CROAK(("code %s caused an error: %s",
6743 SvPV_nolen(sub), SvPV_nolen(errsv)));
6746 if (cv && SvROK(cv) && SvTYPE(SvRV(cv)) == SVt_PVCV) {
6749 CROAK(("code %s did not evaluate to a subroutine reference\n",
6753 SvREFCNT_inc(sv); /* XXX seems to be necessary */
6758 /* fix up the dummy entry... */
6759 av_store(cxt->aseen, tagnum, SvREFCNT_inc(sv));
6764 static SV *retrieve_regexp(pTHX_ stcxt_t *cxt, const char *cname) {
6765 #if PERL_VERSION_GE(5,8,0)
6781 if (op_flags & SHR_U32_RE_LEN) {
6787 re = sv_2mortal(NEWSV(10002, re_len ? re_len : 1));
6788 READ(SvPVX(re), re_len);
6789 SvCUR_set(re, re_len);
6794 flags = sv_2mortal(NEWSV(10002, flags_len ? flags_len : 1));
6795 READ(SvPVX(flags), flags_len);
6796 SvCUR_set(flags, flags_len);
6797 *SvEND(flags) = '\0';
6807 count = call_pv("Storable::_make_re", G_SCALAR);
6812 CROAK(("Bad count %d calling _make_re", (int)count));
6819 CROAK(("_make_re didn't return a reference"));
6823 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
6824 SEEN_NN(sv, stash, 0);
6831 CROAK(("retrieve_regexp does not work with 5.6 or earlier"));
6836 * old_retrieve_array
6838 * Retrieve a whole array in pre-0.6 binary format.
6840 * Layout is SX_ARRAY <size> followed by each item, in increasing index order.
6841 * Each item is stored as SX_ITEM <object> or SX_IT_UNDEF for "holes".
6843 * When we come here, SX_ARRAY has been read already.
6845 static SV *old_retrieve_array(pTHX_ stcxt_t *cxt, const char *cname)
6853 PERL_UNUSED_ARG(cname);
6854 TRACEME(("old_retrieve_array (#%d)", (int)cxt->tagnum));
6857 * Read length, and allocate array, then pre-extend it.
6861 TRACEME(("size = %d", (int)len));
6863 SEEN0_NN(av, 0); /* Will return if array not allocated nicely */
6867 return (SV *) av; /* No data follow if array is empty */
6870 * Now get each item in turn...
6873 for (i = 0; i < len; i++) {
6875 if (c == SX_IT_UNDEF) {
6876 TRACEME(("(#%d) undef item", (int)i));
6877 continue; /* av_extend() already filled us with undef */
6880 (void) retrieve_other(aTHX_ cxt, 0);/* Will croak out */
6881 TRACEME(("(#%d) item", (int)i));
6882 sv = retrieve(aTHX_ cxt, 0); /* Retrieve item */
6885 if (av_store(av, i, sv) == 0)
6889 TRACEME(("ok (old_retrieve_array at 0x%" UVxf ")", PTR2UV(av)));
6897 * Retrieve a whole hash table in pre-0.6 binary format.
6899 * Layout is SX_HASH <size> followed by each key/value pair, in random order.
6900 * Keys are stored as SX_KEY <length> <data>, the <data> section being omitted
6902 * Values are stored as SX_VALUE <object> or SX_VL_UNDEF for "holes".
6904 * When we come here, SX_HASH has been read already.
6906 static SV *old_retrieve_hash(pTHX_ stcxt_t *cxt, const char *cname)
6914 SV *sv_h_undef = (SV *) 0; /* hv_store() bug */
6916 PERL_UNUSED_ARG(cname);
6917 TRACEME(("old_retrieve_hash (#%d)", (int)cxt->tagnum));
6920 * Read length, allocate table.
6924 TRACEME(("size = %d", (int)len));
6926 SEEN0_NN(hv, 0); /* Will return if table not allocated properly */
6928 return (SV *) hv; /* No data follow if table empty */
6929 TRACEME(("split %d", (int)len+1));
6930 hv_ksplit(hv, len+1); /* pre-extend hash to save multiple splits */
6933 * Now get each key/value pair in turn...
6936 for (i = 0; i < len; i++) {
6942 if (c == SX_VL_UNDEF) {
6943 TRACEME(("(#%d) undef value", (int)i));
6945 * Due to a bug in hv_store(), it's not possible to pass
6946 * &PL_sv_undef to hv_store() as a value, otherwise the
6947 * associated key will not be creatable any more. -- RAM, 14/01/97
6950 sv_h_undef = newSVsv(&PL_sv_undef);
6951 sv = SvREFCNT_inc(sv_h_undef);
6952 } else if (c == SX_VALUE) {
6953 TRACEME(("(#%d) value", (int)i));
6954 sv = retrieve(aTHX_ cxt, 0);
6958 (void) retrieve_other(aTHX_ cxt, 0); /* Will croak out */
6962 * Since we're reading into kbuf, we must ensure we're not
6963 * recursing between the read and the hv_store() where it's used.
6964 * Hence the key comes after the value.
6969 (void) retrieve_other(aTHX_ cxt, 0); /* Will croak out */
6970 RLEN(size); /* Get key size */
6971 KBUFCHK((STRLEN)size); /* Grow hash key read pool if needed */
6974 kbuf[size] = '\0'; /* Mark string end, just in case */
6975 TRACEME(("(#%d) key '%s'", (int)i, kbuf));
6978 * Enter key/value pair into hash table.
6981 if (hv_store(hv, kbuf, (U32) size, sv, 0) == 0)
6985 TRACEME(("ok (retrieve_hash at 0x%" UVxf ")", PTR2UV(hv)));
6991 *** Retrieval engine.
6997 * Make sure the stored data we're trying to retrieve has been produced
6998 * on an ILP compatible system with the same byteorder. It croaks out in
6999 * case an error is detected. [ILP = integer-long-pointer sizes]
7000 * Returns null if error is detected, &PL_sv_undef otherwise.
7002 * Note that there's no byte ordering info emitted when network order was
7003 * used at store time.
7005 static SV *magic_check(pTHX_ stcxt_t *cxt)
7007 /* The worst case for a malicious header would be old magic (which is
7008 longer), major, minor, byteorder length byte of 255, 255 bytes of
7009 garbage, sizeof int, long, pointer, NV.
7010 So the worse of that we can read is 255 bytes of garbage plus 4.
7011 Err, I am assuming 8 bit bytes here. Please file a bug report if you're
7012 compiling perl on a system with chars that are larger than 8 bits.
7013 (Even Crays aren't *that* perverse).
7015 unsigned char buf[4 + 255];
7016 unsigned char *current;
7019 int use_network_order;
7023 int version_minor = 0;
7025 TRACEME(("magic_check"));
7028 * The "magic number" is only for files, not when freezing in memory.
7032 /* This includes the '\0' at the end. I want to read the extra byte,
7033 which is usually going to be the major version number. */
7034 STRLEN len = sizeof(magicstr);
7037 READ(buf, (SSize_t)(len)); /* Not null-terminated */
7039 /* Point at the byte after the byte we read. */
7040 current = buf + --len; /* Do the -- outside of macros. */
7042 if (memNE(buf, magicstr, len)) {
7044 * Try to read more bytes to check for the old magic number, which
7048 TRACEME(("trying for old magic number"));
7050 old_len = sizeof(old_magicstr) - 1;
7051 READ(current + 1, (SSize_t)(old_len - len));
7053 if (memNE(buf, old_magicstr, old_len))
7054 CROAK(("File is not a perl storable"));
7056 current = buf + old_len;
7058 use_network_order = *current;
7060 GETMARK(use_network_order);
7064 * Starting with 0.6, the "use_network_order" byte flag is also used to
7065 * indicate the version number of the binary, and therefore governs the
7066 * setting of sv_retrieve_vtbl. See magic_write().
7068 if (old_magic && use_network_order > 1) {
7069 /* 0.1 dump - use_network_order is really byte order length */
7073 version_major = use_network_order >> 1;
7075 cxt->retrieve_vtbl = (SV*(**)(pTHX_ stcxt_t *cxt, const char *cname)) (version_major > 0 ? sv_retrieve : sv_old_retrieve);
7077 TRACEME(("magic_check: netorder = 0x%x", use_network_order));
7081 * Starting with 0.7 (binary major 2), a full byte is dedicated to the
7082 * minor version of the protocol. See magic_write().
7085 if (version_major > 1)
7086 GETMARK(version_minor);
7088 cxt->ver_major = version_major;
7089 cxt->ver_minor = version_minor;
7091 TRACEME(("binary image version is %d.%d", version_major, version_minor));
7094 * Inter-operability sanity check: we can't retrieve something stored
7095 * using a format more recent than ours, because we have no way to
7096 * know what has changed, and letting retrieval go would mean a probable
7097 * failure reporting a "corrupted" storable file.
7101 version_major > STORABLE_BIN_MAJOR ||
7102 (version_major == STORABLE_BIN_MAJOR &&
7103 version_minor > STORABLE_BIN_MINOR)
7106 TRACEME(("but I am version is %d.%d", STORABLE_BIN_MAJOR,
7107 STORABLE_BIN_MINOR));
7109 if (version_major == STORABLE_BIN_MAJOR) {
7110 TRACEME(("cxt->accept_future_minor is %d",
7111 cxt->accept_future_minor));
7112 if (cxt->accept_future_minor < 0)
7113 cxt->accept_future_minor
7114 = (SvTRUE(get_sv("Storable::accept_future_minor",
7117 if (cxt->accept_future_minor == 1)
7118 croak_now = 0; /* Don't croak yet. */
7121 CROAK(("Storable binary image v%d.%d more recent than I am (v%d.%d)",
7122 version_major, version_minor,
7123 STORABLE_BIN_MAJOR, STORABLE_BIN_MINOR));
7128 * If they stored using network order, there's no byte ordering
7129 * information to check.
7132 if ((cxt->netorder = (use_network_order & 0x1))) /* Extra () for -Wall */
7133 return &PL_sv_undef; /* No byte ordering info */
7135 /* In C truth is 1, falsehood is 0. Very convenient. */
7136 use_NV_size = version_major >= 2 && version_minor >= 2;
7138 if (version_major >= 0) {
7142 c = use_network_order;
7144 length = c + 3 + use_NV_size;
7145 READ(buf, length); /* Not null-terminated */
7147 TRACEME(("byte order '%.*s' %d", c, buf, c));
7149 #ifdef USE_56_INTERWORK_KLUDGE
7150 /* No point in caching this in the context as we only need it once per
7151 retrieve, and we need to recheck it each read. */
7152 if (SvTRUE(get_sv("Storable::interwork_56_64bit", GV_ADD))) {
7153 if ((c != (sizeof (byteorderstr_56) - 1))
7154 || memNE(buf, byteorderstr_56, c))
7155 CROAK(("Byte order is not compatible"));
7159 if ((c != (sizeof (byteorderstr) - 1))
7160 || memNE(buf, byteorderstr, c))
7161 CROAK(("Byte order is not compatible"));
7167 if ((int) *current++ != sizeof(int))
7168 CROAK(("Integer size is not compatible"));
7171 if ((int) *current++ != sizeof(long))
7172 CROAK(("Long integer size is not compatible"));
7174 /* sizeof(char *) */
7175 if ((int) *current != sizeof(char *))
7176 CROAK(("Pointer size is not compatible"));
7180 if ((int) *++current != sizeof(NV))
7181 CROAK(("Double size is not compatible"));
7184 return &PL_sv_undef; /* OK */
7190 * Recursively retrieve objects from the specified file and return their
7191 * root SV (which may be an AV or an HV for what we care).
7192 * Returns null if there is a problem.
7194 static SV *retrieve(pTHX_ stcxt_t *cxt, const char *cname)
7200 TRACEME(("retrieve"));
7203 * Grab address tag which identifies the object if we are retrieving
7204 * an older format. Since the new binary format counts objects and no
7205 * longer explicitly tags them, we must keep track of the correspondence
7208 * The following section will disappear one day when the old format is
7209 * no longer supported, hence the final "goto" in the "if" block.
7212 if (cxt->hseen) { /* Retrieving old binary */
7214 if (cxt->netorder) {
7216 READ(&nettag, sizeof(I32)); /* Ordered sequence of I32 */
7217 tag = (stag_t) nettag;
7219 READ(&tag, sizeof(stag_t)); /* Original address of the SV */
7222 if (type == SX_OBJECT) {
7224 svh = hv_fetch(cxt->hseen, (char *) &tag, sizeof(tag), FALSE);
7226 CROAK(("Old tag 0x%" UVxf " should have been mapped already",
7228 tagn = SvIV(*svh); /* Mapped tag number computed earlier below */
7231 * The following code is common with the SX_OBJECT case below.
7234 svh = av_fetch(cxt->aseen, tagn, FALSE);
7236 CROAK(("Object #%" IVdf " should have been retrieved already",
7239 TRACEME(("has retrieved #%d at 0x%" UVxf, (int)tagn, PTR2UV(sv)));
7240 SvREFCNT_inc(sv); /* One more reference to this same sv */
7241 return sv; /* The SV pointer where object was retrieved */
7245 * Map new object, but don't increase tagnum. This will be done
7246 * by each of the retrieve_* functions when they call SEEN().
7248 * The mapping associates the "tag" initially present with a unique
7249 * tag number. See test for SX_OBJECT above to see how this is perused.
7252 if (!hv_store(cxt->hseen, (char *) &tag, sizeof(tag),
7253 newSViv(cxt->tagnum), 0))
7260 * Regular post-0.6 binary format.
7265 TRACEME(("retrieve type = %d", type));
7268 * Are we dealing with an object we should have already retrieved?
7271 if (type == SX_OBJECT) {
7276 /* A 32-bit system can't have over 2**31 objects anyway */
7278 CROAK(("Object #%" IVdf " out of range", (IV)tag));
7280 /* Older versions of Storable on with 64-bit support on 64-bit
7281 systems can produce values above the 2G boundary (or wrapped above
7282 the 4G boundary, which we can't do much about), treat those as
7284 This same commit stores tag ids over the 2G boundary as long tags
7285 since older Storables will mis-handle them as short tags.
7287 svh = av_fetch(cxt->aseen, (U32)tag, FALSE);
7289 CROAK(("Object #%" IVdf " should have been retrieved already",
7292 TRACEME(("had retrieved #%d at 0x%" UVxf, (int)tag, PTR2UV(sv)));
7293 SvREFCNT_inc(sv); /* One more reference to this same sv */
7294 return sv; /* The SV pointer where object was retrieved */
7295 } else if (type >= SX_LAST && cxt->ver_minor > STORABLE_BIN_MINOR) {
7296 if (cxt->accept_future_minor < 0)
7297 cxt->accept_future_minor
7298 = (SvTRUE(get_sv("Storable::accept_future_minor",
7301 if (cxt->accept_future_minor == 1) {
7302 CROAK(("Storable binary image v%d.%d contains data of type %d. "
7303 "This Storable is v%d.%d and can only handle data types up to %d",
7304 cxt->ver_major, cxt->ver_minor, type,
7305 STORABLE_BIN_MAJOR, STORABLE_BIN_MINOR, SX_LAST - 1));
7309 first_time: /* Will disappear when support for old format is dropped */
7312 * Okay, first time through for this one.
7315 sv = RETRIEVE(cxt, type)(aTHX_ cxt, cname);
7317 return (SV *) 0; /* Failed */
7320 * Old binary formats (pre-0.7).
7322 * Final notifications, ended by SX_STORED may now follow.
7323 * Currently, the only pertinent notification to apply on the
7324 * freshly retrieved object is either:
7325 * SX_CLASS <char-len> <classname> for short classnames.
7326 * SX_LG_CLASS <int-len> <classname> for larger one (rare!).
7327 * Class name is then read into the key buffer pool used by
7328 * hash table key retrieval.
7331 if (cxt->ver_major < 2) {
7332 while ((type = GETCHAR()) != SX_STORED) {
7337 GETMARK(len); /* Length coded on a single char */
7339 case SX_LG_CLASS: /* Length coded on a regular integer */
7344 return (SV *) 0; /* Failed */
7346 KBUFCHK((STRLEN)len); /* Grow buffer as necessary */
7349 kbuf[len] = '\0'; /* Mark string end */
7350 stash = gv_stashpvn(kbuf, len, GV_ADD);
7355 TRACEME(("ok (retrieved 0x%" UVxf ", refcnt=%d, %s)", PTR2UV(sv),
7356 (int)SvREFCNT(sv) - 1, sv_reftype(sv, FALSE)));
7364 * Retrieve data held in file and return the root object.
7365 * Common routine for pretrieve and mretrieve.
7367 static SV *do_retrieve(
7376 int is_tainted; /* Is input source tainted? */
7377 int pre_06_fmt = 0; /* True with pre Storable 0.6 formats */
7379 TRACEMED(("do_retrieve (optype = 0x%x, flags=0x%x)",
7380 (unsigned)optype, (unsigned)flags));
7382 optype |= ST_RETRIEVE;
7386 * Sanity assertions for retrieve dispatch tables.
7389 ASSERT(sizeof(sv_old_retrieve) == sizeof(sv_retrieve),
7390 ("old and new retrieve dispatch table have same size"));
7391 ASSERT(sv_old_retrieve[(int)SX_LAST] == retrieve_other,
7392 ("SX_LAST entry correctly initialized in old dispatch table"));
7393 ASSERT(sv_retrieve[(int)SX_LAST] == retrieve_other,
7394 ("SX_LAST entry correctly initialized in new dispatch table"));
7397 * Workaround for CROAK leak: if they enter with a "dirty" context,
7398 * free up memory for them now.
7403 clean_context(aTHX_ cxt);
7406 * Now that STORABLE_xxx hooks exist, it is possible that they try to
7407 * re-enter retrieve() via the hooks.
7411 cxt = allocate_context(aTHX_ cxt);
7418 ASSERT(cxt->entry == 1, ("starting new recursion"));
7419 ASSERT(!cxt->s_dirty, ("clean context"));
7424 * Data is loaded into the memory buffer when f is NULL, unless 'in' is
7425 * also NULL, in which case we're expecting the data to already lie
7426 * in the buffer (dclone case).
7429 KBUFINIT(); /* Allocate hash key reading pool once */
7435 const char *orig = SvPV(in, length);
7437 /* This is quite deliberate. I want the UTF8 routines
7438 to encounter the '\0' which perl adds at the end
7439 of all scalars, so that any new string also has
7442 STRLEN klen_tmp = length + 1;
7443 bool is_utf8 = TRUE;
7445 /* Just casting the &klen to (STRLEN) won't work
7446 well if STRLEN and I32 are of different widths.
7448 asbytes = (char*)bytes_from_utf8((U8*)orig,
7452 CROAK(("Frozen string corrupt - contains characters outside 0-255"));
7454 if (asbytes != orig) {
7455 /* String has been converted.
7456 There is no need to keep any reference to
7458 in = sv_newmortal();
7459 /* We donate the SV the malloc()ed string
7460 bytes_from_utf8 returned us. */
7461 SvUPGRADE(in, SVt_PV);
7463 SvPV_set(in, asbytes);
7464 SvLEN_set(in, klen_tmp);
7465 SvCUR_set(in, klen_tmp - 1);
7469 MBUF_SAVE_AND_LOAD(in);
7473 * Magic number verifications.
7475 * This needs to be done before calling init_retrieve_context()
7476 * since the format indication in the file are necessary to conduct
7477 * some of the initializations.
7480 cxt->fio = f; /* Where I/O are performed */
7482 if (!magic_check(aTHX_ cxt))
7483 CROAK(("Magic number checking on storable %s failed",
7484 cxt->fio ? "file" : "string"));
7486 TRACEME(("data stored in %s format",
7487 cxt->netorder ? "net order" : "native"));
7490 * Check whether input source is tainted, so that we don't wrongly
7491 * taint perfectly good values...
7493 * We assume file input is always tainted. If both 'f' and 'in' are
7494 * NULL, then we come from dclone, and tainted is already filled in
7495 * the context. That's a kludge, but the whole dclone() thing is
7496 * already quite a kludge anyway! -- RAM, 15/09/2000.
7499 is_tainted = f ? 1 : (in ? SvTAINTED(in) : cxt->s_tainted);
7500 TRACEME(("input source is %s", is_tainted ? "tainted" : "trusted"));
7501 init_retrieve_context(aTHX_ cxt, optype, is_tainted);
7503 ASSERT(is_retrieving(aTHX), ("within retrieve operation"));
7505 sv = retrieve(aTHX_ cxt, 0); /* Recursively retrieve object, get root SV */
7514 pre_06_fmt = cxt->hseen != NULL; /* Before we clean context */
7517 * The "root" context is never freed.
7520 clean_retrieve_context(aTHX_ cxt);
7521 if (cxt->prev) /* This context was stacked */
7522 free_context(aTHX_ cxt); /* It was not the "root" context */
7525 * Prepare returned value.
7529 TRACEMED(("retrieve ERROR"));
7530 return &PL_sv_undef; /* Something went wrong, return undef */
7533 TRACEMED(("retrieve got %s(0x%" UVxf ")",
7534 sv_reftype(sv, FALSE), PTR2UV(sv)));
7537 * Backward compatibility with Storable-0.5@9 (which we know we
7538 * are retrieving if hseen is non-null): don't create an extra RV
7539 * for objects since we special-cased it at store time.
7541 * Build a reference to the SV returned by pretrieve even if it is
7542 * already one and not a scalar, for consistency reasons.
7545 if (pre_06_fmt) { /* Was not handling overloading by then */
7547 TRACEMED(("fixing for old formats -- pre 0.6"));
7548 if (sv_type(aTHX_ sv) == svis_REF && (rv = SvRV(sv)) && SvOBJECT(rv)) {
7549 TRACEME(("ended do_retrieve() with an object -- pre 0.6"));
7555 * If reference is overloaded, restore behaviour.
7557 * NB: minor glitch here: normally, overloaded refs are stored specially
7558 * so that we can croak when behaviour cannot be re-installed, and also
7559 * avoid testing for overloading magic at each reference retrieval.
7561 * Unfortunately, the root reference is implicitly stored, so we must
7562 * check for possible overloading now. Furthermore, if we don't restore
7563 * overloading, we cannot croak as if the original ref was, because we
7564 * have no way to determine whether it was an overloaded ref or not in
7567 * It's a pity that overloading magic is attached to the rv, and not to
7568 * the underlying sv as blessing is.
7572 HV *stash = (HV *) SvSTASH(sv);
7573 SV *rv = newRV_noinc(sv);
7574 if (stash && Gv_AMG(stash)) {
7576 TRACEMED(("restored overloading on root reference"));
7578 TRACEMED(("ended do_retrieve() with an object"));
7582 TRACEMED(("regular do_retrieve() end"));
7584 return newRV_noinc(sv);
7590 * Retrieve data held in file and return the root object, undef on error.
7592 static SV *pretrieve(pTHX_ PerlIO *f, IV flag)
7594 TRACEMED(("pretrieve"));
7595 return do_retrieve(aTHX_ f, Nullsv, 0, (int)flag);
7601 * Retrieve data held in scalar and return the root object, undef on error.
7603 static SV *mretrieve(pTHX_ SV *sv, IV flag)
7605 TRACEMED(("mretrieve"));
7606 return do_retrieve(aTHX_ (PerlIO*) 0, sv, 0, (int)flag);
7616 * Deep clone: returns a fresh copy of the original referenced SV tree.
7618 * This is achieved by storing the object in memory and restoring from
7619 * there. Not that efficient, but it should be faster than doing it from
7622 static SV *dclone(pTHX_ SV *sv)
7626 stcxt_t *real_context;
7629 TRACEMED(("dclone"));
7632 * Workaround for CROAK leak: if they enter with a "dirty" context,
7633 * free up memory for them now.
7638 clean_context(aTHX_ cxt);
7641 * Tied elements seem to need special handling.
7644 if ((SvTYPE(sv) == SVt_PVLV
7645 #if PERL_VERSION_LT(5,8,0)
7646 || SvTYPE(sv) == SVt_PVMG
7648 ) && (SvFLAGS(sv) & (SVs_GMG|SVs_SMG|SVs_RMG)) ==
7649 (SVs_GMG|SVs_SMG|SVs_RMG) &&
7655 * do_store() optimizes for dclone by not freeing its context, should
7656 * we need to allocate one because we're deep cloning from a hook.
7659 if (!do_store(aTHX_ (PerlIO*) 0, sv, ST_CLONE, FALSE, (SV**) 0))
7660 return &PL_sv_undef; /* Error during store */
7663 * Because of the above optimization, we have to refresh the context,
7664 * since a new one could have been allocated and stacked by do_store().
7667 { dSTCXT; real_context = cxt; } /* Sub-block needed for macro */
7668 cxt = real_context; /* And we need this temporary... */
7671 * Now, 'cxt' may refer to a new context.
7675 ASSERT(!cxt->s_dirty, ("clean context"));
7676 ASSERT(!cxt->entry, ("entry will not cause new context allocation"));
7679 TRACEME(("dclone stored %ld bytes", (long)size));
7683 * Since we're passing do_retrieve() both a NULL file and sv, we need
7684 * to pre-compute the taintedness of the input by setting cxt->tainted
7685 * to whatever state our own input string was. -- RAM, 15/09/2000
7687 * do_retrieve() will free non-root context.
7690 cxt->s_tainted = SvTAINTED(sv);
7691 out = do_retrieve(aTHX_ (PerlIO*) 0, Nullsv, ST_CLONE, FLAG_BLESS_OK | FLAG_TIE_OK);
7693 TRACEMED(("dclone returns 0x%" UVxf, PTR2UV(out)));
7703 * The Perl IO GV object distinguishes between input and output for sockets
7704 * but not for plain files. To allow Storable to transparently work on
7705 * plain files and sockets transparently, we have to ask xsubpp to fetch the
7706 * right object for us. Hence the OutputStream and InputStream declarations.
7708 * Before perl 5.004_05, those entries in the standard typemap are not
7709 * defined in perl include files, so we do that here.
7712 #ifndef OutputStream
7713 #define OutputStream PerlIO *
7714 #define InputStream PerlIO *
7715 #endif /* !OutputStream */
7718 storable_free(pTHX_ SV *sv, MAGIC* mg) {
7719 stcxt_t *cxt = (stcxt_t *)SvPVX(sv);
7721 PERL_UNUSED_ARG(mg);
7722 #ifdef USE_PTR_TABLE
7724 ptr_table_free(cxt->pseen);
7728 if (!cxt->membuf_ro && mbase)
7730 if (cxt->membuf_ro && (cxt->msaved).arena)
7731 Safefree((cxt->msaved).arena);
7735 MODULE = Storable PACKAGE = Storable
7741 HV *stash = gv_stashpvn("Storable", 8, GV_ADD);
7742 newCONSTSUB(stash, "BIN_MAJOR", newSViv(STORABLE_BIN_MAJOR));
7743 newCONSTSUB(stash, "BIN_MINOR", newSViv(STORABLE_BIN_MINOR));
7744 newCONSTSUB(stash, "BIN_WRITE_MINOR", newSViv(STORABLE_BIN_WRITE_MINOR));
7746 newCONSTSUB(stash, "CAN_FLOCK", CAN_FLOCK);
7748 init_perinterp(aTHX);
7749 gv_fetchpv("Storable::drop_utf8", GV_ADDMULTI, SVt_PV);
7751 /* Only disable the used only once warning if we are in debugging mode. */
7752 gv_fetchpv("Storable::DEBUGME", GV_ADDMULTI, SVt_PV);
7754 #ifdef USE_56_INTERWORK_KLUDGE
7755 gv_fetchpv("Storable::interwork_56_64bit", GV_ADDMULTI, SVt_PV);
7762 init_perinterp(aTHX);
7766 # Store the transitive data closure of given object to disk.
7767 # Returns undef on error, a true value otherwise.
7771 # Same as pstore(), but network order is used for integers and doubles are
7772 # emitted as strings.
7781 RETVAL = do_store(aTHX_ f, obj, 0, ix, (SV **)0) ? &PL_sv_yes : &PL_sv_undef;
7782 /* do_store() can reallocate the stack, so need a sequence point to ensure
7783 that ST(0) knows about it. Hence using two statements. */
7789 # Store the transitive data closure of given object to memory.
7790 # Returns undef on error, a scalar value containing the data otherwise.
7794 # Same as mstore(), but network order is used for integers and doubles are
7795 # emitted as strings.
7803 RETVAL = &PL_sv_undef;
7804 if (!do_store(aTHX_ (PerlIO*) 0, obj, 0, ix, &RETVAL))
7805 RETVAL = &PL_sv_undef;
7810 pretrieve(f, flag = 6)
7814 RETVAL = pretrieve(aTHX_ f, flag);
7819 mretrieve(sv, flag = 6)
7823 RETVAL = mretrieve(aTHX_ sv, flag);
7831 RETVAL = dclone(aTHX_ sv);
7836 last_op_in_netorder()
7838 is_storing = ST_STORE
7839 is_retrieving = ST_RETRIEVE
7846 result = cxt->entry && (cxt->optype & ix) ? TRUE : FALSE;
7848 result = cBOOL(last_op_in_netorder(aTHX));
7850 ST(0) = boolSV(result);
7856 RETVAL = SvIV(get_sv("Storable::recursion_limit", GV_ADD));
7863 RETVAL = SvIV(get_sv("Storable::recursion_limit_hash", GV_ADD));