2 * Store and retrieve mechanism.
4 * Copyright (c) 1995-2000, Raphael Manfredi
6 * You may redistribute only under the same terms as Perl 5, as specified
7 * in the README file that comes with the distribution.
11 #define PERL_NO_GET_CONTEXT /* we want efficiency */
17 #include <patchlevel.h> /* Perl's one, needed since 5.6 */
20 #if !defined(PERL_VERSION) || PERL_VERSION < 10 || (PERL_VERSION == 10 && PERL_SUBVERSION < 1)
21 #define NEED_load_module
22 #define NEED_vload_module
23 #define NEED_newCONSTSUB
24 #define NEED_newSVpvn_flags
25 #define NEED_newRV_noinc
26 #include "ppport.h" /* handle old perls */
30 #define DEBUGME /* Debug mode, turns assertions on as well */
31 #define DASSERT /* Assertion mode */
35 * Pre PerlIO time when none of USE_PERLIO and PERLIO_IS_STDIO is defined
36 * Provide them with the necessary defines so they can build with pre-5.004.
39 #ifndef PERLIO_IS_STDIO
41 #define PerlIO_getc(x) getc(x)
42 #define PerlIO_putc(f,x) putc(x,f)
43 #define PerlIO_read(x,y,z) fread(y,1,z,x)
44 #define PerlIO_write(x,y,z) fwrite(y,1,z,x)
45 #define PerlIO_stdoutf printf
46 #endif /* PERLIO_IS_STDIO */
47 #endif /* USE_PERLIO */
50 * Earlier versions of perl might be used, we can't assume they have the latest!
53 #ifndef HvSHAREKEYS_off
54 #define HvSHAREKEYS_off(hv) /* Ignore */
57 /* perl <= 5.8.2 needs this */
59 # define SvIsCOW(sv) 0
63 # define HvRITER_set(hv,r) (HvRITER(hv) = r)
66 # define HvEITER_set(hv,r) (HvEITER(hv) = r)
70 # define HvRITER_get HvRITER
73 # define HvEITER_get HvEITER
76 #ifndef HvPLACEHOLDERS_get
77 # define HvPLACEHOLDERS_get HvPLACEHOLDERS
81 # define HvTOTALKEYS(hv) HvKEYS(hv)
85 # define SvTRULYREADONLY(sv) SvREADONLY(sv)
87 # define SvTRULYREADONLY(sv) (SvREADONLY(sv) && !SvIsCOW(sv))
97 * TRACEME() will only output things when the $Storable::DEBUGME is true.
102 if (SvTRUE(perl_get_sv("Storable::DEBUGME", GV_ADD))) \
103 { PerlIO_stdoutf x; PerlIO_stdoutf("\n"); } \
110 #define ASSERT(x,y) \
113 PerlIO_stdoutf("ASSERT FAILED (\"%s\", line %d): ", \
114 __FILE__, __LINE__); \
115 PerlIO_stdoutf y; PerlIO_stdoutf("\n"); \
126 #define C(x) ((char) (x)) /* For markers with dynamic retrieval handling */
128 #define SX_OBJECT C(0) /* Already stored object */
129 #define SX_LSCALAR C(1) /* Scalar (large binary) follows (length, data) */
130 #define SX_ARRAY C(2) /* Array forthcoming (size, item list) */
131 #define SX_HASH C(3) /* Hash forthcoming (size, key/value pair list) */
132 #define SX_REF C(4) /* Reference to object forthcoming */
133 #define SX_UNDEF C(5) /* Undefined scalar */
134 #define SX_INTEGER C(6) /* Integer forthcoming */
135 #define SX_DOUBLE C(7) /* Double forthcoming */
136 #define SX_BYTE C(8) /* (signed) byte forthcoming */
137 #define SX_NETINT C(9) /* Integer in network order forthcoming */
138 #define SX_SCALAR C(10) /* Scalar (binary, small) follows (length, data) */
139 #define SX_TIED_ARRAY C(11) /* Tied array forthcoming */
140 #define SX_TIED_HASH C(12) /* Tied hash forthcoming */
141 #define SX_TIED_SCALAR C(13) /* Tied scalar forthcoming */
142 #define SX_SV_UNDEF C(14) /* Perl's immortal PL_sv_undef */
143 #define SX_SV_YES C(15) /* Perl's immortal PL_sv_yes */
144 #define SX_SV_NO C(16) /* Perl's immortal PL_sv_no */
145 #define SX_BLESS C(17) /* Object is blessed */
146 #define SX_IX_BLESS C(18) /* Object is blessed, classname given by index */
147 #define SX_HOOK C(19) /* Stored via hook, user-defined */
148 #define SX_OVERLOAD C(20) /* Overloaded reference */
149 #define SX_TIED_KEY C(21) /* Tied magic key forthcoming */
150 #define SX_TIED_IDX C(22) /* Tied magic index forthcoming */
151 #define SX_UTF8STR C(23) /* UTF-8 string forthcoming (small) */
152 #define SX_LUTF8STR C(24) /* UTF-8 string forthcoming (large) */
153 #define SX_FLAG_HASH C(25) /* Hash with flags forthcoming (size, flags, key/flags/value triplet list) */
154 #define SX_CODE C(26) /* Code references as perl source code */
155 #define SX_WEAKREF C(27) /* Weak reference to object forthcoming */
156 #define SX_WEAKOVERLOAD C(28) /* Overloaded weak reference */
157 #define SX_VSTRING C(29) /* vstring forthcoming (small) */
158 #define SX_LVSTRING C(30) /* vstring forthcoming (large) */
159 #define SX_SVUNDEF_ELEM C(31) /* array element set to &PL_sv_undef */
160 #define SX_ERROR C(32) /* Error */
163 * Those are only used to retrieve "old" pre-0.6 binary images.
165 #define SX_ITEM 'i' /* An array item introducer */
166 #define SX_IT_UNDEF 'I' /* Undefined array item */
167 #define SX_KEY 'k' /* A hash key introducer */
168 #define SX_VALUE 'v' /* A hash value introducer */
169 #define SX_VL_UNDEF 'V' /* Undefined hash value */
172 * Those are only used to retrieve "old" pre-0.7 binary images
175 #define SX_CLASS 'b' /* Object is blessed, class name length <255 */
176 #define SX_LG_CLASS 'B' /* Object is blessed, class name length >255 */
177 #define SX_STORED 'X' /* End of object */
180 * Limits between short/long length representation.
183 #define LG_SCALAR 255 /* Large scalar length limit */
184 #define LG_BLESS 127 /* Large classname bless limit */
190 #define ST_STORE 0x1 /* Store operation */
191 #define ST_RETRIEVE 0x2 /* Retrieval operation */
192 #define ST_CLONE 0x4 /* Deep cloning operation */
195 * The following structure is used for hash table key retrieval. Since, when
196 * retrieving objects, we'll be facing blessed hash references, it's best
197 * to pre-allocate that buffer once and resize it as the need arises, never
198 * freeing it (keys will be saved away someplace else anyway, so even large
199 * keys are not enough a motivation to reclaim that space).
201 * This structure is also used for memory store/retrieve operations which
202 * happen in a fixed place before being malloc'ed elsewhere if persistence
203 * is required. Hence the aptr pointer.
206 char *arena; /* Will hold hash key strings, resized as needed */
207 STRLEN asiz; /* Size of aforementioned buffer */
208 char *aptr; /* Arena pointer, for in-place read/write ops */
209 char *aend; /* First invalid address */
214 * A hash table records the objects which have already been stored.
215 * Those are referred to as SX_OBJECT in the file, and their "tag" (i.e.
216 * an arbitrary sequence number) is used to identify them.
219 * An array table records the objects which have already been retrieved,
220 * as seen by the tag determined by counting the objects themselves. The
221 * reference to that retrieved object is kept in the table, and is returned
222 * when an SX_OBJECT is found bearing that same tag.
224 * The same processing is used to record "classname" for blessed objects:
225 * indexing by a hash at store time, and via an array at retrieve time.
228 typedef unsigned long stag_t; /* Used by pre-0.6 binary format */
231 * The following "thread-safe" related defines were contributed by
232 * Murray Nesbitt <murray@activestate.com> and integrated by RAM, who
233 * only renamed things a little bit to ensure consistency with surrounding
234 * code. -- RAM, 14/09/1999
236 * The original patch suffered from the fact that the stcxt_t structure
237 * was global. Murray tried to minimize the impact on the code as much as
240 * Starting with 0.7, Storable can be re-entrant, via the STORABLE_xxx hooks
241 * on objects. Therefore, the notion of context needs to be generalized,
245 #define MY_VERSION "Storable(" XS_VERSION ")"
249 * Conditional UTF8 support.
253 #define STORE_UTF8STR(pv, len) STORE_PV_LEN(pv, len, SX_UTF8STR, SX_LUTF8STR)
254 #define HAS_UTF8_SCALARS
256 #define HAS_UTF8_HASHES
259 /* 5.6 perl has utf8 scalars but not hashes */
263 #define STORE_UTF8STR(pv, len) CROAK(("panic: storing UTF8 in non-UTF8 perl"))
266 #define UTF8_CROAK() CROAK(("Cannot retrieve UTF8 data in non-UTF8 perl"))
269 #define WEAKREF_CROAK() CROAK(("Cannot retrieve weak references in this perl"))
272 #define VSTRING_CROAK() CROAK(("Cannot retrieve vstring in this perl"))
275 #ifdef HvPLACEHOLDERS
276 #define HAS_RESTRICTED_HASHES
278 #define HVhek_PLACEHOLD 0x200
279 #define RESTRICTED_HASH_CROAK() CROAK(("Cannot retrieve restricted hash"))
283 #define HAS_HASH_KEY_FLAGS
287 #define USE_PTR_TABLE
291 * Fields s_tainted and s_dirty are prefixed with s_ because Perl's include
292 * files remap tainted and dirty when threading is enabled. That's bad for
293 * perl to remap such common words. -- RAM, 29/09/00
297 typedef struct stcxt {
298 int entry; /* flags recursion */
299 int optype; /* type of traversal operation */
300 /* which objects have been seen, store time.
301 tags are numbers, which are cast to (SV *) and stored directly */
303 /* use pseen if we have ptr_tables. We have to store tag+1, because
304 tag numbers start at 0, and we can't store (SV *) 0 in a ptr_table
305 without it being confused for a fetch lookup failure. */
306 struct ptr_tbl *pseen;
307 /* Still need hseen for the 0.6 file format code. */
310 AV *hook_seen; /* which SVs were returned by STORABLE_freeze() */
311 AV *aseen; /* which objects have been seen, retrieve time */
312 IV where_is_undef; /* index in aseen of PL_sv_undef */
313 HV *hclass; /* which classnames have been seen, store time */
314 AV *aclass; /* which classnames have been seen, retrieve time */
315 HV *hook; /* cache for hook methods per class name */
316 IV tagnum; /* incremented at store time for each seen object */
317 IV classnum; /* incremented at store time for each seen classname */
318 int netorder; /* true if network order used */
319 int s_tainted; /* true if input source is tainted, at retrieve time */
320 int forgive_me; /* whether to be forgiving... */
321 int deparse; /* whether to deparse code refs */
322 SV *eval; /* whether to eval source code */
323 int canonical; /* whether to store hashes sorted by key */
324 #ifndef HAS_RESTRICTED_HASHES
325 int derestrict; /* whether to downgrade restricted hashes */
328 int use_bytes; /* whether to bytes-ify utf8 */
330 int accept_future_minor; /* croak immediately on future minor versions? */
331 int s_dirty; /* context is dirty due to CROAK() -- can be cleaned */
332 int membuf_ro; /* true means membuf is read-only and msaved is rw */
333 struct extendable keybuf; /* for hash key retrieval */
334 struct extendable membuf; /* for memory store/retrieve operations */
335 struct extendable msaved; /* where potentially valid mbuf is saved */
336 PerlIO *fio; /* where I/O are performed, NULL for memory */
337 int ver_major; /* major of version for retrieved object */
338 int ver_minor; /* minor of version for retrieved object */
339 SV *(**retrieve_vtbl)(pTHX_ struct stcxt *, const char *); /* retrieve dispatch table */
340 SV *prev; /* contexts chained backwards in real recursion */
341 SV *my_sv; /* the blessed scalar who's SvPVX() I am */
342 int in_retrieve_overloaded; /* performance hack for retrieving overloaded objects */
345 static int storable_free(pTHX_ SV *sv, MAGIC* mg);
347 static MGVTBL vtbl_storable = {
364 /* From Digest::MD5. */
366 # define sv_magicext(sv, obj, type, vtbl, name, namlen) \
367 THX_sv_magicext(aTHX_ sv, obj, type, vtbl, name, namlen)
368 static MAGIC *THX_sv_magicext(pTHX_ SV *sv, SV *obj, int type,
369 MGVTBL const *vtbl, char const *name, I32 namlen)
373 /* exceeded intended usage of this reserve implementation */
376 mg->mg_virtual = (MGVTBL*)vtbl;
378 mg->mg_ptr = (char *)name;
380 (void) SvUPGRADE(sv, SVt_PVMG);
381 mg->mg_moremagic = SvMAGIC(sv);
389 #define NEW_STORABLE_CXT_OBJ(cxt) \
391 SV *self = newSV(sizeof(stcxt_t) - 1); \
392 SV *my_sv = newRV_noinc(self); \
393 sv_magicext(self, NULL, PERL_MAGIC_ext, &vtbl_storable, NULL, 0); \
394 cxt = (stcxt_t *)SvPVX(self); \
395 Zero(cxt, 1, stcxt_t); \
396 cxt->my_sv = my_sv; \
399 #if defined(MULTIPLICITY) || defined(PERL_OBJECT) || defined(PERL_CAPI)
401 #if (PATCHLEVEL <= 4) && (SUBVERSION < 68)
403 SV *perinterp_sv = perl_get_sv(MY_VERSION, 0)
404 #else /* >= perl5.004_68 */
406 SV *perinterp_sv = *hv_fetch(PL_modglobal, \
407 MY_VERSION, sizeof(MY_VERSION)-1, TRUE)
408 #endif /* < perl5.004_68 */
410 #define dSTCXT_PTR(T,name) \
411 T name = ((perinterp_sv && SvIOK(perinterp_sv) && SvIVX(perinterp_sv) \
412 ? (T)SvPVX(SvRV(INT2PTR(SV*,SvIVX(perinterp_sv)))) : (T) 0))
415 dSTCXT_PTR(stcxt_t *, cxt)
419 NEW_STORABLE_CXT_OBJ(cxt); \
420 assert(perinterp_sv); \
421 sv_setiv(perinterp_sv, PTR2IV(cxt->my_sv))
423 #define SET_STCXT(x) \
426 sv_setiv(perinterp_sv, PTR2IV(x->my_sv)); \
429 #else /* !MULTIPLICITY && !PERL_OBJECT && !PERL_CAPI */
431 static stcxt_t *Context_ptr = NULL;
432 #define dSTCXT stcxt_t *cxt = Context_ptr
433 #define SET_STCXT(x) Context_ptr = x
436 NEW_STORABLE_CXT_OBJ(cxt); \
440 #endif /* MULTIPLICITY || PERL_OBJECT || PERL_CAPI */
444 * Croaking implies a memory leak, since we don't use setjmp/longjmp
445 * to catch the exit and free memory used during store or retrieve
446 * operations. This is not too difficult to fix, but I need to understand
447 * how Perl does it, and croaking is exceptional anyway, so I lack the
448 * motivation to do it.
450 * The current workaround is to mark the context as dirty when croaking,
451 * so that data structures can be freed whenever we renter Storable code
452 * (but only *then*: it's a workaround, not a fix).
454 * This is also imperfect, because we don't really know how far they trapped
455 * the croak(), and when we were recursing, we won't be able to clean anything
456 * but the topmost context stacked.
459 #define CROAK(x) STMT_START { cxt->s_dirty = 1; croak x; } STMT_END
462 * End of "thread-safe" related definitions.
468 * Keep only the low 32 bits of a pointer (used for tags, which are not
473 #define LOW_32BITS(x) ((I32) (x))
475 #define LOW_32BITS(x) ((I32) ((unsigned long) (x) & 0xffffffffUL))
481 * Hack for Crays, where sizeof(I32) == 8, and which are big-endians.
482 * Used in the WLEN and RLEN macros.
486 #define oI(x) ((I32 *) ((char *) (x) + 4))
487 #define oS(x) ((x) - 4)
488 #define oC(x) (x = 0)
497 * key buffer handling
499 #define kbuf (cxt->keybuf).arena
500 #define ksiz (cxt->keybuf).asiz
504 TRACEME(("** allocating kbuf of 128 bytes")); \
505 New(10003, kbuf, 128, char); \
512 TRACEME(("** extending kbuf to %d bytes (had %d)", x+1, ksiz)); \
513 Renew(kbuf, x+1, char); \
519 * memory buffer handling
521 #define mbase (cxt->membuf).arena
522 #define msiz (cxt->membuf).asiz
523 #define mptr (cxt->membuf).aptr
524 #define mend (cxt->membuf).aend
526 #define MGROW (1 << 13)
527 #define MMASK (MGROW - 1)
529 #define round_mgrow(x) \
530 ((unsigned long) (((unsigned long) (x) + MMASK) & ~MMASK))
531 #define trunc_int(x) \
532 ((unsigned long) ((unsigned long) (x) & ~(sizeof(int)-1)))
533 #define int_aligned(x) \
534 ((unsigned long) (x) == trunc_int(x))
536 #define MBUF_INIT(x) \
539 TRACEME(("** allocating mbase of %d bytes", MGROW)); \
540 New(10003, mbase, MGROW, char); \
541 msiz = (STRLEN)MGROW; \
547 mend = mbase + msiz; \
550 #define MBUF_TRUNC(x) mptr = mbase + x
551 #define MBUF_SIZE() (mptr - mbase)
557 * Those macros are used in do_retrieve() to save the current memory
558 * buffer into cxt->msaved, before MBUF_LOAD() can be used to retrieve
559 * data from a string.
561 #define MBUF_SAVE_AND_LOAD(in) \
563 ASSERT(!cxt->membuf_ro, ("mbase not already saved")); \
564 cxt->membuf_ro = 1; \
565 TRACEME(("saving mbuf")); \
566 StructCopy(&cxt->membuf, &cxt->msaved, struct extendable); \
570 #define MBUF_RESTORE() \
572 ASSERT(cxt->membuf_ro, ("mbase is read-only")); \
573 cxt->membuf_ro = 0; \
574 TRACEME(("restoring mbuf")); \
575 StructCopy(&cxt->msaved, &cxt->membuf, struct extendable); \
579 * Use SvPOKp(), because SvPOK() fails on tainted scalars.
580 * See store_scalar() for other usage of this workaround.
582 #define MBUF_LOAD(v) \
584 ASSERT(cxt->membuf_ro, ("mbase is read-only")); \
586 CROAK(("Not a scalar string")); \
587 mptr = mbase = SvPV(v, msiz); \
588 mend = mbase + msiz; \
591 #define MBUF_XTEND(x) \
593 int nsz = (int) round_mgrow((x)+msiz); \
594 int offset = mptr - mbase; \
595 ASSERT(!cxt->membuf_ro, ("mbase is not read-only")); \
596 TRACEME(("** extending mbase from %d to %d bytes (wants %d new)", \
598 Renew(mbase, nsz, char); \
600 mptr = mbase + offset; \
601 mend = mbase + nsz; \
604 #define MBUF_CHK(x) \
606 if ((mptr + (x)) > mend) \
610 #define MBUF_GETC(x) \
613 x = (int) (unsigned char) *mptr++; \
619 #define MBUF_GETINT(x) \
622 if ((mptr + 4) <= mend) { \
623 memcpy(oI(&x), mptr, 4); \
629 #define MBUF_GETINT(x) \
631 if ((mptr + sizeof(int)) <= mend) { \
632 if (int_aligned(mptr)) \
635 memcpy(&x, mptr, sizeof(int)); \
636 mptr += sizeof(int); \
642 #define MBUF_READ(x,s) \
644 if ((mptr + (s)) <= mend) { \
645 memcpy(x, mptr, s); \
651 #define MBUF_SAFEREAD(x,s,z) \
653 if ((mptr + (s)) <= mend) { \
654 memcpy(x, mptr, s); \
662 #define MBUF_SAFEPVREAD(x,s,z) \
664 if ((mptr + (s)) <= mend) { \
665 memcpy(x, mptr, s); \
673 #define MBUF_PUTC(c) \
676 *mptr++ = (char) c; \
679 *mptr++ = (char) c; \
684 #define MBUF_PUTINT(i) \
687 memcpy(mptr, oI(&i), 4); \
691 #define MBUF_PUTINT(i) \
693 MBUF_CHK(sizeof(int)); \
694 if (int_aligned(mptr)) \
697 memcpy(mptr, &i, sizeof(int)); \
698 mptr += sizeof(int); \
702 #define MBUF_WRITE(x,s) \
705 memcpy(mptr, x, s); \
710 * Possible return values for sv_type().
714 #define svis_SCALAR 1
718 #define svis_TIED_ITEM 5
726 #define SHF_TYPE_MASK 0x03
727 #define SHF_LARGE_CLASSLEN 0x04
728 #define SHF_LARGE_STRLEN 0x08
729 #define SHF_LARGE_LISTLEN 0x10
730 #define SHF_IDX_CLASSNAME 0x20
731 #define SHF_NEED_RECURSE 0x40
732 #define SHF_HAS_LIST 0x80
735 * Types for SX_HOOK (last 2 bits in flags).
741 #define SHT_EXTRA 3 /* Read extra byte for type */
744 * The following are held in the "extra byte"...
747 #define SHT_TSCALAR 4 /* 4 + 0 -- tied scalar */
748 #define SHT_TARRAY 5 /* 4 + 1 -- tied array */
749 #define SHT_THASH 6 /* 4 + 2 -- tied hash */
752 * per hash flags for flagged hashes
755 #define SHV_RESTRICTED 0x01
758 * per key flags for flagged hashes
761 #define SHV_K_UTF8 0x01
762 #define SHV_K_WASUTF8 0x02
763 #define SHV_K_LOCKED 0x04
764 #define SHV_K_ISSV 0x08
765 #define SHV_K_PLACEHOLDER 0x10
768 * Before 0.6, the magic string was "perl-store" (binary version number 0).
770 * Since 0.6 introduced many binary incompatibilities, the magic string has
771 * been changed to "pst0" to allow an old image to be properly retrieved by
772 * a newer Storable, but ensure a newer image cannot be retrieved with an
775 * At 0.7, objects are given the ability to serialize themselves, and the
776 * set of markers is extended, backward compatibility is not jeopardized,
777 * so the binary version number could have remained unchanged. To correctly
778 * spot errors if a file making use of 0.7-specific extensions is given to
779 * 0.6 for retrieval, the binary version was moved to "2". And I'm introducing
780 * a "minor" version, to better track this kind of evolution from now on.
783 static const char old_magicstr[] = "perl-store"; /* Magic number before 0.6 */
784 static const char magicstr[] = "pst0"; /* Used as a magic number */
786 #define MAGICSTR_BYTES 'p','s','t','0'
787 #define OLDMAGICSTR_BYTES 'p','e','r','l','-','s','t','o','r','e'
789 /* 5.6.x introduced the ability to have IVs as long long.
790 However, Configure still defined BYTEORDER based on the size of a long.
791 Storable uses the BYTEORDER value as part of the header, but doesn't
792 explicitly store sizeof(IV) anywhere in the header. Hence on 5.6.x built
793 with IV as long long on a platform that uses Configure (ie most things
794 except VMS and Windows) headers are identical for the different IV sizes,
795 despite the files containing some fields based on sizeof(IV)
797 5.8 is consistent - the following redefinition kludge is only needed on
798 5.6.x, but the interwork is needed on 5.8 while data survives in files
803 #if defined (IVSIZE) && (IVSIZE == 8) && (LONGSIZE == 4)
804 #ifndef NO_56_INTERWORK_KLUDGE
805 #define USE_56_INTERWORK_KLUDGE
807 #if BYTEORDER == 0x1234
809 #define BYTEORDER 0x12345678
811 #if BYTEORDER == 0x4321
813 #define BYTEORDER 0x87654321
818 #if BYTEORDER == 0x1234
819 #define BYTEORDER_BYTES '1','2','3','4'
821 #if BYTEORDER == 0x12345678
822 #define BYTEORDER_BYTES '1','2','3','4','5','6','7','8'
823 #ifdef USE_56_INTERWORK_KLUDGE
824 #define BYTEORDER_BYTES_56 '1','2','3','4'
827 #if BYTEORDER == 0x87654321
828 #define BYTEORDER_BYTES '8','7','6','5','4','3','2','1'
829 #ifdef USE_56_INTERWORK_KLUDGE
830 #define BYTEORDER_BYTES_56 '4','3','2','1'
833 #if BYTEORDER == 0x4321
834 #define BYTEORDER_BYTES '4','3','2','1'
836 #error Unknown byteorder. Please append your byteorder to Storable.xs
842 static const char byteorderstr[] = {BYTEORDER_BYTES, 0};
843 #ifdef USE_56_INTERWORK_KLUDGE
844 static const char byteorderstr_56[] = {BYTEORDER_BYTES_56, 0};
847 #define STORABLE_BIN_MAJOR 2 /* Binary major "version" */
848 #define STORABLE_BIN_MINOR 10 /* Binary minor "version" */
850 #if (PATCHLEVEL <= 5)
851 #define STORABLE_BIN_WRITE_MINOR 4
852 #elif !defined (SvVOK)
854 * Perl 5.6.0-5.8.0 can do weak references, but not vstring magic.
856 #define STORABLE_BIN_WRITE_MINOR 8
857 #elif PATCHLEVEL >= 19
858 /* Perl 5.19 takes away the special meaning of PL_sv_undef in arrays. */
859 #define STORABLE_BIN_WRITE_MINOR 10
861 #define STORABLE_BIN_WRITE_MINOR 9
862 #endif /* (PATCHLEVEL <= 5) */
864 #if (PATCHLEVEL < 8 || (PATCHLEVEL == 8 && SUBVERSION < 1))
865 #define PL_sv_placeholder PL_sv_undef
869 * Useful store shortcuts...
873 * Note that if you put more than one mark for storing a particular
874 * type of thing, *and* in the retrieve_foo() function you mark both
875 * the thingy's you get off with SEEN(), you *must* increase the
876 * tagnum with cxt->tagnum++ along with this macro!
883 else if (PerlIO_putc(cxt->fio, x) == EOF) \
887 #define WRITE_I32(x) \
889 ASSERT(sizeof(x) == sizeof(I32), ("writing an I32")); \
892 else if (PerlIO_write(cxt->fio, oI(&x), oS(sizeof(x))) != oS(sizeof(x))) \
899 ASSERT(sizeof(x) == sizeof(int), ("WLEN writing an int")); \
900 if (cxt->netorder) { \
901 int y = (int) htonl(x); \
904 else if (PerlIO_write(cxt->fio,oI(&y),oS(sizeof(y))) != oS(sizeof(y))) \
909 else if (PerlIO_write(cxt->fio,oI(&x),oS(sizeof(x))) != oS(sizeof(x))) \
914 #define WLEN(x) WRITE_I32(x)
921 else if (PerlIO_write(cxt->fio, x, y) != y) \
925 #define STORE_PV_LEN(pv, len, small, large) \
927 if (len <= LG_SCALAR) { \
928 unsigned char clen = (unsigned char) len; \
940 #define STORE_SCALAR(pv, len) STORE_PV_LEN(pv, len, SX_SCALAR, SX_LSCALAR)
943 * Store &PL_sv_undef in arrays without recursing through store(). We
944 * actually use this to represent nonexistent elements, for historical
947 #define STORE_SV_UNDEF() \
950 PUTMARK(SX_SV_UNDEF); \
954 * Useful retrieve shortcuts...
958 (cxt->fio ? PerlIO_getc(cxt->fio) : (mptr >= mend ? EOF : (int) *mptr++))
964 else if ((int) (x = PerlIO_getc(cxt->fio)) == EOF) \
968 #define READ_I32(x) \
970 ASSERT(sizeof(x) == sizeof(I32), ("reading an I32")); \
974 else if (PerlIO_read(cxt->fio, oI(&x), oS(sizeof(x))) != oS(sizeof(x))) \
984 else if (PerlIO_read(cxt->fio, oI(&x), oS(sizeof(x))) != oS(sizeof(x))) \
987 x = (int) ntohl(x); \
990 #define RLEN(x) READ_I32(x)
997 else if (PerlIO_read(cxt->fio, x, y) != y) \
1001 #define SAFEREAD(x,y,z) \
1004 MBUF_SAFEREAD(x,y,z); \
1005 else if (PerlIO_read(cxt->fio, x, y) != y) { \
1011 #define SAFEPVREAD(x,y,z) \
1014 MBUF_SAFEPVREAD(x,y,z); \
1015 else if (PerlIO_read(cxt->fio, x, y) != y) { \
1022 * SEEN() is used at retrieve time, to remember where object 'y', bearing a
1023 * given tag 'tagnum', has been retrieved. Next time we see an SX_OBJECT marker,
1024 * we'll therefore know where it has been retrieved and will be able to
1025 * share the same reference, as in the original stored memory image.
1027 * We also need to bless objects ASAP for hooks (which may compute "ref $x"
1028 * on the objects given to STORABLE_thaw and expect that to be defined), and
1029 * also for overloaded objects (for which we might not find the stash if the
1030 * object is not blessed yet--this might occur for overloaded objects that
1031 * refer to themselves indirectly: if we blessed upon return from a sub
1032 * retrieve(), the SX_OBJECT marker we'd found could not have overloading
1033 * restored on it because the underlying object would not be blessed yet!).
1035 * To achieve that, the class name of the last retrieved object is passed down
1036 * recursively, and the first SEEN() call for which the class name is not NULL
1037 * will bless the object.
1039 * i should be true iff sv is immortal (ie PL_sv_yes, PL_sv_no or PL_sv_undef)
1041 * SEEN0() is a short-cut where stash is always NULL.
1043 * The _NN variants dont check for y being null
1045 #define SEEN0_NN(y,i) \
1047 if (av_store(cxt->aseen, cxt->tagnum++, i ? (SV*)(y) : SvREFCNT_inc(y)) == 0) \
1049 TRACEME(("aseen(#%d) = 0x%" UVxf " (refcnt=%d)", cxt->tagnum-1, \
1050 PTR2UV(y), SvREFCNT(y)-1)); \
1053 #define SEEN0(y,i) \
1060 #define SEEN_NN(y,stash,i) \
1064 BLESS((SV *) (y), (HV *)(stash)); \
1067 #define SEEN(y,stash,i) \
1071 SEEN_NN(y,stash, i); \
1075 * Bless 's' in 'p', via a temporary reference, required by sv_bless().
1076 * "A" magic is added before the sv_bless for overloaded classes, this avoids
1077 * an expensive call to S_reset_amagic in sv_bless.
1079 #define BLESS(s,stash) \
1082 TRACEME(("blessing 0x%" UVxf " in %s", PTR2UV(s), (HvNAME_get(stash))));\
1083 ref = newRV_noinc(s); \
1084 if (cxt->in_retrieve_overloaded && Gv_AMG(stash)) \
1086 cxt->in_retrieve_overloaded = 0; \
1089 (void) sv_bless(ref, stash); \
1090 SvRV_set(ref, NULL); \
1091 SvREFCNT_dec(ref); \
1094 * sort (used in store_hash) - conditionally use qsort when
1095 * sortsv is not available ( <= 5.6.1 ).
1098 #if (PATCHLEVEL <= 6)
1100 #if defined(USE_ITHREADS)
1102 #define STORE_HASH_SORT \
1104 PerlInterpreter *orig_perl = PERL_GET_CONTEXT; \
1105 SAVESPTR(orig_perl); \
1106 PERL_SET_CONTEXT(aTHX); \
1107 qsort((char *) AvARRAY(av), len, sizeof(SV *), sortcmp); \
1110 #else /* ! USE_ITHREADS */
1112 #define STORE_HASH_SORT \
1113 qsort((char *) AvARRAY(av), len, sizeof(SV *), sortcmp);
1115 #endif /* USE_ITHREADS */
1117 #else /* PATCHLEVEL > 6 */
1119 #define STORE_HASH_SORT \
1120 sortsv(AvARRAY(av), len, Perl_sv_cmp);
1122 #endif /* PATCHLEVEL <= 6 */
1124 static int store(pTHX_ stcxt_t *cxt, SV *sv);
1125 static SV *retrieve(pTHX_ stcxt_t *cxt, const char *cname);
1129 av_pop(cxt->aseen); \
1134 * Dynamic dispatching table for SV store.
1137 static int store_ref(pTHX_ stcxt_t *cxt, SV *sv);
1138 static int store_scalar(pTHX_ stcxt_t *cxt, SV *sv);
1139 static int store_array(pTHX_ stcxt_t *cxt, AV *av);
1140 static int store_hash(pTHX_ stcxt_t *cxt, HV *hv);
1141 static int store_tied(pTHX_ stcxt_t *cxt, SV *sv);
1142 static int store_tied_item(pTHX_ stcxt_t *cxt, SV *sv);
1143 static int store_code(pTHX_ stcxt_t *cxt, CV *cv);
1144 static int store_other(pTHX_ stcxt_t *cxt, SV *sv);
1145 static int store_blessed(pTHX_ stcxt_t *cxt, SV *sv, int type, HV *pkg);
1147 typedef int (*sv_store_t)(pTHX_ stcxt_t *cxt, SV *sv);
1149 static const sv_store_t sv_store[] = {
1150 (sv_store_t)store_ref, /* svis_REF */
1151 (sv_store_t)store_scalar, /* svis_SCALAR */
1152 (sv_store_t)store_array, /* svis_ARRAY */
1153 (sv_store_t)store_hash, /* svis_HASH */
1154 (sv_store_t)store_tied, /* svis_TIED */
1155 (sv_store_t)store_tied_item, /* svis_TIED_ITEM */
1156 (sv_store_t)store_code, /* svis_CODE */
1157 (sv_store_t)store_other, /* svis_OTHER */
1160 #define SV_STORE(x) (*sv_store[x])
1163 * Dynamic dispatching tables for SV retrieval.
1166 static SV *retrieve_lscalar(pTHX_ stcxt_t *cxt, const char *cname);
1167 static SV *retrieve_lutf8str(pTHX_ stcxt_t *cxt, const char *cname);
1168 static SV *old_retrieve_array(pTHX_ stcxt_t *cxt, const char *cname);
1169 static SV *old_retrieve_hash(pTHX_ stcxt_t *cxt, const char *cname);
1170 static SV *retrieve_ref(pTHX_ stcxt_t *cxt, const char *cname);
1171 static SV *retrieve_undef(pTHX_ stcxt_t *cxt, const char *cname);
1172 static SV *retrieve_integer(pTHX_ stcxt_t *cxt, const char *cname);
1173 static SV *retrieve_double(pTHX_ stcxt_t *cxt, const char *cname);
1174 static SV *retrieve_byte(pTHX_ stcxt_t *cxt, const char *cname);
1175 static SV *retrieve_netint(pTHX_ stcxt_t *cxt, const char *cname);
1176 static SV *retrieve_scalar(pTHX_ stcxt_t *cxt, const char *cname);
1177 static SV *retrieve_utf8str(pTHX_ stcxt_t *cxt, const char *cname);
1178 static SV *retrieve_tied_array(pTHX_ stcxt_t *cxt, const char *cname);
1179 static SV *retrieve_tied_hash(pTHX_ stcxt_t *cxt, const char *cname);
1180 static SV *retrieve_tied_scalar(pTHX_ stcxt_t *cxt, const char *cname);
1181 static SV *retrieve_other(pTHX_ stcxt_t *cxt, const char *cname);
1183 typedef SV* (*sv_retrieve_t)(pTHX_ stcxt_t *cxt, const char *name);
1185 static const sv_retrieve_t sv_old_retrieve[] = {
1186 0, /* SX_OBJECT -- entry unused dynamically */
1187 (sv_retrieve_t)retrieve_lscalar, /* SX_LSCALAR */
1188 (sv_retrieve_t)old_retrieve_array, /* SX_ARRAY -- for pre-0.6 binaries */
1189 (sv_retrieve_t)old_retrieve_hash, /* SX_HASH -- for pre-0.6 binaries */
1190 (sv_retrieve_t)retrieve_ref, /* SX_REF */
1191 (sv_retrieve_t)retrieve_undef, /* SX_UNDEF */
1192 (sv_retrieve_t)retrieve_integer, /* SX_INTEGER */
1193 (sv_retrieve_t)retrieve_double, /* SX_DOUBLE */
1194 (sv_retrieve_t)retrieve_byte, /* SX_BYTE */
1195 (sv_retrieve_t)retrieve_netint, /* SX_NETINT */
1196 (sv_retrieve_t)retrieve_scalar, /* SX_SCALAR */
1197 (sv_retrieve_t)retrieve_tied_array, /* SX_TIED_ARRAY */
1198 (sv_retrieve_t)retrieve_tied_hash, /* SX_TIED_HASH */
1199 (sv_retrieve_t)retrieve_tied_scalar, /* SX_TIED_SCALAR */
1200 (sv_retrieve_t)retrieve_other, /* SX_SV_UNDEF not supported */
1201 (sv_retrieve_t)retrieve_other, /* SX_SV_YES not supported */
1202 (sv_retrieve_t)retrieve_other, /* SX_SV_NO not supported */
1203 (sv_retrieve_t)retrieve_other, /* SX_BLESS not supported */
1204 (sv_retrieve_t)retrieve_other, /* SX_IX_BLESS not supported */
1205 (sv_retrieve_t)retrieve_other, /* SX_HOOK not supported */
1206 (sv_retrieve_t)retrieve_other, /* SX_OVERLOADED not supported */
1207 (sv_retrieve_t)retrieve_other, /* SX_TIED_KEY not supported */
1208 (sv_retrieve_t)retrieve_other, /* SX_TIED_IDX not supported */
1209 (sv_retrieve_t)retrieve_other, /* SX_UTF8STR not supported */
1210 (sv_retrieve_t)retrieve_other, /* SX_LUTF8STR not supported */
1211 (sv_retrieve_t)retrieve_other, /* SX_FLAG_HASH not supported */
1212 (sv_retrieve_t)retrieve_other, /* SX_CODE not supported */
1213 (sv_retrieve_t)retrieve_other, /* SX_WEAKREF not supported */
1214 (sv_retrieve_t)retrieve_other, /* SX_WEAKOVERLOAD not supported */
1215 (sv_retrieve_t)retrieve_other, /* SX_VSTRING not supported */
1216 (sv_retrieve_t)retrieve_other, /* SX_LVSTRING not supported */
1217 (sv_retrieve_t)retrieve_other, /* SX_SVUNDEF_ELEM not supported */
1218 (sv_retrieve_t)retrieve_other, /* SX_ERROR */
1221 static SV *retrieve_array(pTHX_ stcxt_t *cxt, const char *cname);
1222 static SV *retrieve_hash(pTHX_ stcxt_t *cxt, const char *cname);
1223 static SV *retrieve_sv_undef(pTHX_ stcxt_t *cxt, const char *cname);
1224 static SV *retrieve_sv_yes(pTHX_ stcxt_t *cxt, const char *cname);
1225 static SV *retrieve_sv_no(pTHX_ stcxt_t *cxt, const char *cname);
1226 static SV *retrieve_blessed(pTHX_ stcxt_t *cxt, const char *cname);
1227 static SV *retrieve_idx_blessed(pTHX_ stcxt_t *cxt, const char *cname);
1228 static SV *retrieve_hook(pTHX_ stcxt_t *cxt, const char *cname);
1229 static SV *retrieve_overloaded(pTHX_ stcxt_t *cxt, const char *cname);
1230 static SV *retrieve_tied_key(pTHX_ stcxt_t *cxt, const char *cname);
1231 static SV *retrieve_tied_idx(pTHX_ stcxt_t *cxt, const char *cname);
1232 static SV *retrieve_flag_hash(pTHX_ stcxt_t *cxt, const char *cname);
1233 static SV *retrieve_code(pTHX_ stcxt_t *cxt, const char *cname);
1234 static SV *retrieve_weakref(pTHX_ stcxt_t *cxt, const char *cname);
1235 static SV *retrieve_weakoverloaded(pTHX_ stcxt_t *cxt, const char *cname);
1236 static SV *retrieve_vstring(pTHX_ stcxt_t *cxt, const char *cname);
1237 static SV *retrieve_lvstring(pTHX_ stcxt_t *cxt, const char *cname);
1238 static SV *retrieve_svundef_elem(pTHX_ stcxt_t *cxt, const char *cname);
1240 static const sv_retrieve_t sv_retrieve[] = {
1241 0, /* SX_OBJECT -- entry unused dynamically */
1242 (sv_retrieve_t)retrieve_lscalar, /* SX_LSCALAR */
1243 (sv_retrieve_t)retrieve_array, /* SX_ARRAY */
1244 (sv_retrieve_t)retrieve_hash, /* SX_HASH */
1245 (sv_retrieve_t)retrieve_ref, /* SX_REF */
1246 (sv_retrieve_t)retrieve_undef, /* SX_UNDEF */
1247 (sv_retrieve_t)retrieve_integer, /* SX_INTEGER */
1248 (sv_retrieve_t)retrieve_double, /* SX_DOUBLE */
1249 (sv_retrieve_t)retrieve_byte, /* SX_BYTE */
1250 (sv_retrieve_t)retrieve_netint, /* SX_NETINT */
1251 (sv_retrieve_t)retrieve_scalar, /* SX_SCALAR */
1252 (sv_retrieve_t)retrieve_tied_array, /* SX_TIED_ARRAY */
1253 (sv_retrieve_t)retrieve_tied_hash, /* SX_TIED_HASH */
1254 (sv_retrieve_t)retrieve_tied_scalar, /* SX_TIED_SCALAR */
1255 (sv_retrieve_t)retrieve_sv_undef, /* SX_SV_UNDEF */
1256 (sv_retrieve_t)retrieve_sv_yes, /* SX_SV_YES */
1257 (sv_retrieve_t)retrieve_sv_no, /* SX_SV_NO */
1258 (sv_retrieve_t)retrieve_blessed, /* SX_BLESS */
1259 (sv_retrieve_t)retrieve_idx_blessed, /* SX_IX_BLESS */
1260 (sv_retrieve_t)retrieve_hook, /* SX_HOOK */
1261 (sv_retrieve_t)retrieve_overloaded, /* SX_OVERLOAD */
1262 (sv_retrieve_t)retrieve_tied_key, /* SX_TIED_KEY */
1263 (sv_retrieve_t)retrieve_tied_idx, /* SX_TIED_IDX */
1264 (sv_retrieve_t)retrieve_utf8str, /* SX_UTF8STR */
1265 (sv_retrieve_t)retrieve_lutf8str, /* SX_LUTF8STR */
1266 (sv_retrieve_t)retrieve_flag_hash, /* SX_HASH */
1267 (sv_retrieve_t)retrieve_code, /* SX_CODE */
1268 (sv_retrieve_t)retrieve_weakref, /* SX_WEAKREF */
1269 (sv_retrieve_t)retrieve_weakoverloaded, /* SX_WEAKOVERLOAD */
1270 (sv_retrieve_t)retrieve_vstring, /* SX_VSTRING */
1271 (sv_retrieve_t)retrieve_lvstring, /* SX_LVSTRING */
1272 (sv_retrieve_t)retrieve_svundef_elem, /* SX_SVUNDEF_ELEM */
1273 (sv_retrieve_t)retrieve_other, /* SX_ERROR */
1276 #define RETRIEVE(c,x) (*(c)->retrieve_vtbl[(x) >= SX_ERROR ? SX_ERROR : (x)])
1278 static SV *mbuf2sv(pTHX);
1281 *** Context management.
1287 * Called once per "thread" (interpreter) to initialize some global context.
1289 static void init_perinterp(pTHX)
1293 cxt->netorder = 0; /* true if network order used */
1294 cxt->forgive_me = -1; /* whether to be forgiving... */
1295 cxt->accept_future_minor = -1; /* would otherwise occur too late */
1301 * Called at the end of every context cleaning, to perform common reset
1304 static void reset_context(stcxt_t *cxt)
1308 cxt->optype &= ~(ST_STORE|ST_RETRIEVE); /* Leave ST_CLONE alone */
1312 * init_store_context
1314 * Initialize a new store context for real recursion.
1316 static void init_store_context(
1323 TRACEME(("init_store_context"));
1325 cxt->netorder = network_order;
1326 cxt->forgive_me = -1; /* Fetched from perl if needed */
1327 cxt->deparse = -1; /* Idem */
1328 cxt->eval = NULL; /* Idem */
1329 cxt->canonical = -1; /* Idem */
1330 cxt->tagnum = -1; /* Reset tag numbers */
1331 cxt->classnum = -1; /* Reset class numbers */
1332 cxt->fio = f; /* Where I/O are performed */
1333 cxt->optype = optype; /* A store, or a deep clone */
1334 cxt->entry = 1; /* No recursion yet */
1337 * The 'hseen' table is used to keep track of each SV stored and their
1338 * associated tag numbers is special. It is "abused" because the
1339 * values stored are not real SV, just integers cast to (SV *),
1340 * which explains the freeing below.
1342 * It is also one possible bottleneck to achieve good storing speed,
1343 * so the "shared keys" optimization is turned off (unlikely to be
1344 * of any use here), and the hash table is "pre-extended". Together,
1345 * those optimizations increase the throughput by 12%.
1348 #ifdef USE_PTR_TABLE
1349 cxt->pseen = ptr_table_new();
1352 cxt->hseen = newHV(); /* Table where seen objects are stored */
1353 HvSHAREKEYS_off(cxt->hseen);
1356 * The following does not work well with perl5.004_04, and causes
1357 * a core dump later on, in a completely unrelated spot, which
1358 * makes me think there is a memory corruption going on.
1360 * Calling hv_ksplit(hseen, HBUCKETS) instead of manually hacking
1361 * it below does not make any difference. It seems to work fine
1362 * with perl5.004_68 but given the probable nature of the bug,
1363 * that does not prove anything.
1365 * It's a shame because increasing the amount of buckets raises
1366 * store() throughput by 5%, but until I figure this out, I can't
1367 * allow for this to go into production.
1369 * It is reported fixed in 5.005, hence the #if.
1371 #if PERL_VERSION >= 5
1372 #define HBUCKETS 4096 /* Buckets for %hseen */
1373 #ifndef USE_PTR_TABLE
1374 HvMAX(cxt->hseen) = HBUCKETS - 1; /* keys %hseen = $HBUCKETS; */
1379 * The 'hclass' hash uses the same settings as 'hseen' above, but it is
1380 * used to assign sequential tags (numbers) to class names for blessed
1383 * We turn the shared key optimization on.
1386 cxt->hclass = newHV(); /* Where seen classnames are stored */
1388 #if PERL_VERSION >= 5
1389 HvMAX(cxt->hclass) = HBUCKETS - 1; /* keys %hclass = $HBUCKETS; */
1393 * The 'hook' hash table is used to keep track of the references on
1394 * the STORABLE_freeze hook routines, when found in some class name.
1396 * It is assumed that the inheritance tree will not be changed during
1397 * storing, and that no new method will be dynamically created by the
1401 cxt->hook = newHV(); /* Table where hooks are cached */
1404 * The 'hook_seen' array keeps track of all the SVs returned by
1405 * STORABLE_freeze hooks for us to serialize, so that they are not
1406 * reclaimed until the end of the serialization process. Each SV is
1407 * only stored once, the first time it is seen.
1410 cxt->hook_seen = newAV(); /* Lists SVs returned by STORABLE_freeze */
1414 * clean_store_context
1416 * Clean store context by
1418 static void clean_store_context(pTHX_ stcxt_t *cxt)
1422 TRACEME(("clean_store_context"));
1424 ASSERT(cxt->optype & ST_STORE, ("was performing a store()"));
1427 * Insert real values into hashes where we stored faked pointers.
1430 #ifndef USE_PTR_TABLE
1432 hv_iterinit(cxt->hseen);
1433 while ((he = hv_iternext(cxt->hseen))) /* Extra () for -Wall, grr.. */
1434 HeVAL(he) = &PL_sv_undef;
1439 hv_iterinit(cxt->hclass);
1440 while ((he = hv_iternext(cxt->hclass))) /* Extra () for -Wall, grr.. */
1441 HeVAL(he) = &PL_sv_undef;
1445 * And now dispose of them...
1447 * The surrounding if() protection has been added because there might be
1448 * some cases where this routine is called more than once, during
1449 * exceptional events. This was reported by Marc Lehmann when Storable
1450 * is executed from mod_perl, and the fix was suggested by him.
1451 * -- RAM, 20/12/2000
1454 #ifdef USE_PTR_TABLE
1456 struct ptr_tbl *pseen = cxt->pseen;
1458 ptr_table_free(pseen);
1460 assert(!cxt->hseen);
1463 HV *hseen = cxt->hseen;
1466 sv_free((SV *) hseen);
1471 HV *hclass = cxt->hclass;
1474 sv_free((SV *) hclass);
1478 HV *hook = cxt->hook;
1481 sv_free((SV *) hook);
1484 if (cxt->hook_seen) {
1485 AV *hook_seen = cxt->hook_seen;
1487 av_undef(hook_seen);
1488 sv_free((SV *) hook_seen);
1491 cxt->forgive_me = -1; /* Fetched from perl if needed */
1492 cxt->deparse = -1; /* Idem */
1494 SvREFCNT_dec(cxt->eval);
1496 cxt->eval = NULL; /* Idem */
1497 cxt->canonical = -1; /* Idem */
1503 * init_retrieve_context
1505 * Initialize a new retrieve context for real recursion.
1507 static void init_retrieve_context(pTHX_ stcxt_t *cxt, int optype, int is_tainted)
1509 TRACEME(("init_retrieve_context"));
1512 * The hook hash table is used to keep track of the references on
1513 * the STORABLE_thaw hook routines, when found in some class name.
1515 * It is assumed that the inheritance tree will not be changed during
1516 * storing, and that no new method will be dynamically created by the
1520 cxt->hook = newHV(); /* Caches STORABLE_thaw */
1522 #ifdef USE_PTR_TABLE
1527 * If retrieving an old binary version, the cxt->retrieve_vtbl variable
1528 * was set to sv_old_retrieve. We'll need a hash table to keep track of
1529 * the correspondence between the tags and the tag number used by the
1530 * new retrieve routines.
1533 cxt->hseen = (((void*)cxt->retrieve_vtbl == (void*)sv_old_retrieve)
1536 cxt->aseen = newAV(); /* Where retrieved objects are kept */
1537 cxt->where_is_undef = -1; /* Special case for PL_sv_undef */
1538 cxt->aclass = newAV(); /* Where seen classnames are kept */
1539 cxt->tagnum = 0; /* Have to count objects... */
1540 cxt->classnum = 0; /* ...and class names as well */
1541 cxt->optype = optype;
1542 cxt->s_tainted = is_tainted;
1543 cxt->entry = 1; /* No recursion yet */
1544 #ifndef HAS_RESTRICTED_HASHES
1545 cxt->derestrict = -1; /* Fetched from perl if needed */
1547 #ifndef HAS_UTF8_ALL
1548 cxt->use_bytes = -1; /* Fetched from perl if needed */
1550 cxt->accept_future_minor = -1; /* Fetched from perl if needed */
1551 cxt->in_retrieve_overloaded = 0;
1555 * clean_retrieve_context
1557 * Clean retrieve context by
1559 static void clean_retrieve_context(pTHX_ stcxt_t *cxt)
1561 TRACEME(("clean_retrieve_context"));
1563 ASSERT(cxt->optype & ST_RETRIEVE, ("was performing a retrieve()"));
1566 AV *aseen = cxt->aseen;
1569 sv_free((SV *) aseen);
1571 cxt->where_is_undef = -1;
1574 AV *aclass = cxt->aclass;
1577 sv_free((SV *) aclass);
1581 HV *hook = cxt->hook;
1584 sv_free((SV *) hook);
1588 HV *hseen = cxt->hseen;
1591 sv_free((SV *) hseen); /* optional HV, for backward compat. */
1594 #ifndef HAS_RESTRICTED_HASHES
1595 cxt->derestrict = -1; /* Fetched from perl if needed */
1597 #ifndef HAS_UTF8_ALL
1598 cxt->use_bytes = -1; /* Fetched from perl if needed */
1600 cxt->accept_future_minor = -1; /* Fetched from perl if needed */
1602 cxt->in_retrieve_overloaded = 0;
1609 * A workaround for the CROAK bug: cleanup the last context.
1611 static void clean_context(pTHX_ stcxt_t *cxt)
1613 TRACEME(("clean_context"));
1615 ASSERT(cxt->s_dirty, ("dirty context"));
1620 ASSERT(!cxt->membuf_ro, ("mbase is not read-only"));
1622 if (cxt->optype & ST_RETRIEVE)
1623 clean_retrieve_context(aTHX_ cxt);
1624 else if (cxt->optype & ST_STORE)
1625 clean_store_context(aTHX_ cxt);
1629 ASSERT(!cxt->s_dirty, ("context is clean"));
1630 ASSERT(cxt->entry == 0, ("context is reset"));
1636 * Allocate a new context and push it on top of the parent one.
1637 * This new context is made globally visible via SET_STCXT().
1639 static stcxt_t *allocate_context(pTHX_ stcxt_t *parent_cxt)
1643 TRACEME(("allocate_context"));
1645 ASSERT(!parent_cxt->s_dirty, ("parent context clean"));
1647 NEW_STORABLE_CXT_OBJ(cxt);
1648 cxt->prev = parent_cxt->my_sv;
1651 ASSERT(!cxt->s_dirty, ("clean context"));
1659 * Free current context, which cannot be the "root" one.
1660 * Make the context underneath globally visible via SET_STCXT().
1662 static void free_context(pTHX_ stcxt_t *cxt)
1664 stcxt_t *prev = (stcxt_t *)(cxt->prev ? SvPVX(SvRV(cxt->prev)) : 0);
1666 TRACEME(("free_context"));
1668 ASSERT(!cxt->s_dirty, ("clean context"));
1669 ASSERT(prev, ("not freeing root context"));
1672 SvREFCNT_dec(cxt->my_sv);
1675 ASSERT(cxt, ("context not void"));
1682 /* these two functions are currently only used within asserts */
1687 * Tells whether we're in the middle of a store operation.
1689 static int is_storing(pTHX)
1693 return cxt->entry && (cxt->optype & ST_STORE);
1699 * Tells whether we're in the middle of a retrieve operation.
1701 static int is_retrieving(pTHX)
1705 return cxt->entry && (cxt->optype & ST_RETRIEVE);
1710 * last_op_in_netorder
1712 * Returns whether last operation was made using network order.
1714 * This is typically out-of-band information that might prove useful
1715 * to people wishing to convert native to network order data when used.
1717 static int last_op_in_netorder(pTHX)
1722 return cxt->netorder;
1726 *** Hook lookup and calling routines.
1732 * A wrapper on gv_fetchmethod_autoload() which caches results.
1734 * Returns the routine reference as an SV*, or null if neither the package
1735 * nor its ancestors know about the method.
1737 static SV *pkg_fetchmeth(
1745 const char *hvname = HvNAME_get(pkg);
1749 * The following code is the same as the one performed by UNIVERSAL::can
1753 gv = gv_fetchmethod_autoload(pkg, method, FALSE);
1754 if (gv && isGV(gv)) {
1755 sv = newRV((SV*) GvCV(gv));
1756 TRACEME(("%s->%s: 0x%" UVxf, hvname, method, PTR2UV(sv)));
1758 sv = newSVsv(&PL_sv_undef);
1759 TRACEME(("%s->%s: not found", hvname, method));
1763 * Cache the result, ignoring failure: if we can't store the value,
1764 * it just won't be cached.
1767 (void) hv_store(cache, hvname, strlen(hvname), sv, 0);
1769 return SvOK(sv) ? sv : (SV *) 0;
1775 * Force cached value to be undef: hook ignored even if present.
1777 static void pkg_hide(
1783 const char *hvname = HvNAME_get(pkg);
1784 PERL_UNUSED_ARG(method);
1785 (void) hv_store(cache,
1786 hvname, strlen(hvname), newSVsv(&PL_sv_undef), 0);
1792 * Discard cached value: a whole fetch loop will be retried at next lookup.
1794 static void pkg_uncache(
1800 const char *hvname = HvNAME_get(pkg);
1801 PERL_UNUSED_ARG(method);
1802 (void) hv_delete(cache, hvname, strlen(hvname), G_DISCARD);
1808 * Our own "UNIVERSAL::can", which caches results.
1810 * Returns the routine reference as an SV*, or null if the object does not
1811 * know about the method.
1821 const char *hvname = HvNAME_get(pkg);
1823 TRACEME(("pkg_can for %s->%s", hvname, method));
1826 * Look into the cache to see whether we already have determined
1827 * where the routine was, if any.
1829 * NOTA BENE: we don't use 'method' at all in our lookup, since we know
1830 * that only one hook (i.e. always the same) is cached in a given cache.
1833 svh = hv_fetch(cache, hvname, strlen(hvname), FALSE);
1837 TRACEME(("cached %s->%s: not found", hvname, method));
1840 TRACEME(("cached %s->%s: 0x%" UVxf,
1841 hvname, method, PTR2UV(sv)));
1846 TRACEME(("not cached yet"));
1847 return pkg_fetchmeth(aTHX_ cache, pkg, method); /* Fetch and cache */
1853 * Call routine as obj->hook(av) in scalar context.
1854 * Propagates the single returned value if not called in void context.
1856 static SV *scalar_call(
1868 TRACEME(("scalar_call (cloning=%d)", cloning));
1875 XPUSHs(sv_2mortal(newSViv(cloning))); /* Cloning flag */
1877 SV **ary = AvARRAY(av);
1878 int cnt = AvFILLp(av) + 1;
1880 XPUSHs(ary[0]); /* Frozen string */
1881 for (i = 1; i < cnt; i++) {
1882 TRACEME(("pushing arg #%d (0x%" UVxf ")...",
1883 i, PTR2UV(ary[i])));
1884 XPUSHs(sv_2mortal(newRV(ary[i])));
1889 TRACEME(("calling..."));
1890 count = perl_call_sv(hook, flags); /* Go back to Perl code */
1891 TRACEME(("count = %d", count));
1897 SvREFCNT_inc(sv); /* We're returning it, must stay alive! */
1910 * Call routine obj->hook(cloning) in list context.
1911 * Returns the list of returned values in an array.
1913 static AV *array_call(
1924 TRACEME(("array_call (cloning=%d)", cloning));
1930 XPUSHs(obj); /* Target object */
1931 XPUSHs(sv_2mortal(newSViv(cloning))); /* Cloning flag */
1934 count = perl_call_sv(hook, G_ARRAY); /* Go back to Perl code */
1939 for (i = count - 1; i >= 0; i--) {
1941 av_store(av, i, SvREFCNT_inc(sv));
1954 * Lookup the class name in the 'hclass' table and either assign it a new ID
1955 * or return the existing one, by filling in 'classnum'.
1957 * Return true if the class was known, false if the ID was just generated.
1959 static int known_class(
1962 char *name, /* Class name */
1963 int len, /* Name length */
1967 HV *hclass = cxt->hclass;
1969 TRACEME(("known_class (%s)", name));
1972 * Recall that we don't store pointers in this hash table, but tags.
1973 * Therefore, we need LOW_32BITS() to extract the relevant parts.
1976 svh = hv_fetch(hclass, name, len, FALSE);
1978 *classnum = LOW_32BITS(*svh);
1983 * Unknown classname, we need to record it.
1987 if (!hv_store(hclass, name, len, INT2PTR(SV*, cxt->classnum), 0))
1988 CROAK(("Unable to record new classname"));
1990 *classnum = cxt->classnum;
1995 *** Specific store routines.
2001 * Store a reference.
2002 * Layout is SX_REF <object> or SX_OVERLOAD <object>.
2004 static int store_ref(pTHX_ stcxt_t *cxt, SV *sv)
2007 TRACEME(("store_ref (0x%" UVxf ")", PTR2UV(sv)));
2010 * Follow reference, and check if target is overloaded.
2016 TRACEME(("ref (0x%" UVxf ") is%s weak", PTR2UV(sv), is_weak
2023 HV *stash = (HV *) SvSTASH(sv);
2024 if (stash && Gv_AMG(stash)) {
2025 TRACEME(("ref (0x%" UVxf ") is overloaded", PTR2UV(sv)));
2026 PUTMARK(is_weak ? SX_WEAKOVERLOAD : SX_OVERLOAD);
2028 PUTMARK(is_weak ? SX_WEAKREF : SX_REF);
2030 PUTMARK(is_weak ? SX_WEAKREF : SX_REF);
2032 return store(aTHX_ cxt, sv);
2040 * Layout is SX_LSCALAR <length> <data>, SX_SCALAR <length> <data> or SX_UNDEF.
2041 * SX_LUTF8STR and SX_UTF8STR are used for UTF-8 strings.
2042 * The <data> section is omitted if <length> is 0.
2044 * For vstrings, the vstring portion is stored first with
2045 * SX_LVSTRING <length> <data> or SX_VSTRING <length> <data>, followed by
2046 * SX_(L)SCALAR or SX_(L)UTF8STR with the actual PV.
2048 * If integer or double, the layout is SX_INTEGER <data> or SX_DOUBLE <data>.
2049 * Small integers (within [-127, +127]) are stored as SX_BYTE <byte>.
2051 static int store_scalar(pTHX_ stcxt_t *cxt, SV *sv)
2056 U32 flags = SvFLAGS(sv); /* "cc -O" may put it in register */
2058 TRACEME(("store_scalar (0x%" UVxf ")", PTR2UV(sv)));
2061 * For efficiency, break the SV encapsulation by peaking at the flags
2062 * directly without using the Perl macros to avoid dereferencing
2063 * sv->sv_flags each time we wish to check the flags.
2066 if (!(flags & SVf_OK)) { /* !SvOK(sv) */
2067 if (sv == &PL_sv_undef) {
2068 TRACEME(("immortal undef"));
2069 PUTMARK(SX_SV_UNDEF);
2071 TRACEME(("undef at 0x%" UVxf, PTR2UV(sv)));
2078 * Always store the string representation of a scalar if it exists.
2079 * Gisle Aas provided me with this test case, better than a long speach:
2081 * perl -MDevel::Peek -le '$a="abc"; $a+0; Dump($a)'
2082 * SV = PVNV(0x80c8520)
2084 * FLAGS = (NOK,POK,pNOK,pPOK)
2087 * PV = 0x80c83d0 "abc"\0
2091 * Write SX_SCALAR, length, followed by the actual data.
2093 * Otherwise, write an SX_BYTE, SX_INTEGER or an SX_DOUBLE as
2094 * appropriate, followed by the actual (binary) data. A double
2095 * is written as a string if network order, for portability.
2097 * NOTE: instead of using SvNOK(sv), we test for SvNOKp(sv).
2098 * The reason is that when the scalar value is tainted, the SvNOK(sv)
2101 * The test for a read-only scalar with both POK and NOK set is meant
2102 * to quickly detect &PL_sv_yes and &PL_sv_no without having to pay the
2103 * address comparison for each scalar we store.
2106 #define SV_MAYBE_IMMORTAL (SVf_READONLY|SVf_POK|SVf_NOK)
2108 if ((flags & SV_MAYBE_IMMORTAL) == SV_MAYBE_IMMORTAL) {
2109 if (sv == &PL_sv_yes) {
2110 TRACEME(("immortal yes"));
2112 } else if (sv == &PL_sv_no) {
2113 TRACEME(("immortal no"));
2116 pv = SvPV(sv, len); /* We know it's SvPOK */
2117 goto string; /* Share code below */
2119 } else if (flags & SVf_POK) {
2120 /* public string - go direct to string read. */
2121 goto string_readlen;
2123 #if (PATCHLEVEL <= 6)
2124 /* For 5.6 and earlier NV flag trumps IV flag, so only use integer
2125 direct if NV flag is off. */
2126 (flags & (SVf_NOK | SVf_IOK)) == SVf_IOK
2128 /* 5.7 rules are that if IV public flag is set, IV value is as
2129 good, if not better, than NV value. */
2135 * Will come here from below with iv set if double is an integer.
2139 /* Sorry. This isn't in 5.005_56 (IIRC) or earlier. */
2141 /* Need to do this out here, else 0xFFFFFFFF becomes iv of -1
2142 * (for example) and that ends up in the optimised small integer
2145 if ((flags & SVf_IVisUV) && SvUV(sv) > IV_MAX) {
2146 TRACEME(("large unsigned integer as string, value = %" UVuf,
2148 goto string_readlen;
2152 * Optimize small integers into a single byte, otherwise store as
2153 * a real integer (converted into network order if they asked).
2156 if (iv >= -128 && iv <= 127) {
2157 unsigned char siv = (unsigned char) (iv + 128); /* [0,255] */
2160 TRACEME(("small integer stored as %d", siv));
2161 } else if (cxt->netorder) {
2163 TRACEME(("no htonl, fall back to string for integer"));
2164 goto string_readlen;
2172 /* Sorry. This isn't in 5.005_56 (IIRC) or earlier. */
2173 ((flags & SVf_IVisUV) && SvUV(sv) > (UV)0x7FFFFFFF) ||
2175 (iv > (IV)0x7FFFFFFF) || (iv < -(IV)0x80000000)) {
2176 /* Bigger than 32 bits. */
2177 TRACEME(("large network order integer as string, value = %"
2179 goto string_readlen;
2183 niv = (I32) htonl((I32) iv);
2184 TRACEME(("using network order"));
2189 PUTMARK(SX_INTEGER);
2190 WRITE(&iv, sizeof(iv));
2193 TRACEME(("ok (integer 0x%" UVxf ", value = %" IVdf ")",
2195 } else if (flags & SVf_NOK) {
2197 #if (PATCHLEVEL <= 6)
2200 * Watch for number being an integer in disguise.
2202 if (nv == (NV) (iv = I_V(nv))) {
2203 TRACEME(("double %" NVff " is actually integer %" IVdf, nv, iv));
2204 goto integer; /* Share code above */
2209 if (SvIOK_notUV(sv)) {
2211 goto integer; /* Share code above */
2216 if (cxt->netorder) {
2217 TRACEME(("double %" NVff " stored as string", nv));
2218 goto string_readlen; /* Share code below */
2222 WRITE(&nv, sizeof(nv));
2224 TRACEME(("ok (double 0x%" UVxf ", value = %" NVff ")",
2227 } else if (flags & (SVp_POK | SVp_NOK | SVp_IOK)) {
2231 I32 wlen; /* For 64-bit machines */
2237 * Will come here from above if it was readonly, POK and NOK but
2238 * neither &PL_sv_yes nor &PL_sv_no.
2243 if (SvMAGICAL(sv) && (mg = mg_find(sv, 'V'))) {
2244 /* The macro passes this by address, not value, and a lot of
2245 called code assumes that it's 32 bits without checking. */
2246 const int len = mg->mg_len;
2247 STORE_PV_LEN((const char *)mg->mg_ptr,
2248 len, SX_VSTRING, SX_LVSTRING);
2252 wlen = (I32) len; /* WLEN via STORE_SCALAR expects I32 */
2254 STORE_UTF8STR(pv, wlen);
2256 STORE_SCALAR(pv, wlen);
2257 TRACEME(("ok (scalar 0x%" UVxf " '%s', length = %" IVdf ")",
2258 PTR2UV(sv), SvPVX(sv), (IV)len));
2260 CROAK(("Can't determine type of %s(0x%" UVxf ")",
2261 sv_reftype(sv, FALSE),
2263 return 0; /* Ok, no recursion on scalars */
2271 * Layout is SX_ARRAY <size> followed by each item, in increasing index order.
2272 * Each item is stored as <object>.
2274 static int store_array(pTHX_ stcxt_t *cxt, AV *av)
2277 I32 len = av_len(av) + 1;
2281 TRACEME(("store_array (0x%" UVxf ")", PTR2UV(av)));
2284 * Signal array by emitting SX_ARRAY, followed by the array length.
2289 TRACEME(("size = %d", len));
2292 * Now store each item recursively.
2295 for (i = 0; i < len; i++) {
2296 sav = av_fetch(av, i, 0);
2298 TRACEME(("(#%d) nonexistent item", i));
2302 #if PATCHLEVEL >= 19
2303 /* In 5.19.3 and up, &PL_sv_undef can actually be stored in
2304 * an array; it no longer represents nonexistent elements.
2305 * Historically, we have used SX_SV_UNDEF in arrays for
2306 * nonexistent elements, so we use SX_SVUNDEF_ELEM for
2307 * &PL_sv_undef itself. */
2308 if (*sav == &PL_sv_undef) {
2309 TRACEME(("(#%d) undef item", i));
2311 PUTMARK(SX_SVUNDEF_ELEM);
2315 TRACEME(("(#%d) item", i));
2316 if ((ret = store(aTHX_ cxt, *sav))) /* Extra () for -Wall, grr... */
2320 TRACEME(("ok (array)"));
2326 #if (PATCHLEVEL <= 6)
2332 * Borrowed from perl source file pp_ctl.c, where it is used by pp_sort.
2335 sortcmp(const void *a, const void *b)
2337 #if defined(USE_ITHREADS)
2339 #endif /* USE_ITHREADS */
2340 return sv_cmp(*(SV * const *) a, *(SV * const *) b);
2343 #endif /* PATCHLEVEL <= 6 */
2348 * Store a hash table.
2350 * For a "normal" hash (not restricted, no utf8 keys):
2352 * Layout is SX_HASH <size> followed by each key/value pair, in random order.
2353 * Values are stored as <object>.
2354 * Keys are stored as <length> <data>, the <data> section being omitted
2357 * For a "fancy" hash (restricted or utf8 keys):
2359 * Layout is SX_FLAG_HASH <size> <hash flags> followed by each key/value pair,
2361 * Values are stored as <object>.
2362 * Keys are stored as <flags> <length> <data>, the <data> section being omitted
2364 * Currently the only hash flag is "restricted"
2365 * Key flags are as for hv.h
2367 static int store_hash(pTHX_ stcxt_t *cxt, HV *hv)
2370 I32 len = HvTOTALKEYS(hv);
2375 int flagged_hash = ((SvREADONLY(hv)
2376 #ifdef HAS_HASH_KEY_FLAGS
2380 unsigned char hash_flags = (SvREADONLY(hv) ? SHV_RESTRICTED : 0);
2383 /* needs int cast for C++ compilers, doesn't it? */
2384 TRACEME(("store_hash (0x%" UVxf ") (flags %x)", PTR2UV(hv),
2387 TRACEME(("store_hash (0x%" UVxf ")", PTR2UV(hv)));
2391 * Signal hash by emitting SX_HASH, followed by the table length.
2395 PUTMARK(SX_FLAG_HASH);
2396 PUTMARK(hash_flags);
2401 TRACEME(("size = %d", len));
2404 * Save possible iteration state via each() on that table.
2407 riter = HvRITER_get(hv);
2408 eiter = HvEITER_get(hv);
2412 * Now store each item recursively.
2414 * If canonical is defined to some true value then store each
2415 * key/value pair in sorted order otherwise the order is random.
2416 * Canonical order is irrelevant when a deep clone operation is performed.
2418 * Fetch the value from perl only once per store() operation, and only
2423 !(cxt->optype & ST_CLONE) && (cxt->canonical == 1 ||
2424 (cxt->canonical < 0 && (cxt->canonical =
2425 (SvTRUE(perl_get_sv("Storable::canonical", GV_ADD)) ? 1 : 0))))
2428 * Storing in order, sorted by key.
2429 * Run through the hash, building up an array of keys in a
2430 * mortal array, sort the array and then run through the
2436 /*av_extend (av, len);*/
2438 TRACEME(("using canonical order"));
2440 for (i = 0; i < len; i++) {
2441 #ifdef HAS_RESTRICTED_HASHES
2442 HE *he = hv_iternext_flags(hv, HV_ITERNEXT_WANTPLACEHOLDERS);
2444 HE *he = hv_iternext(hv);
2449 CROAK(("Hash %p inconsistent - expected %d keys, %dth is NULL", hv, (int)len, (int)i));
2450 key = hv_iterkeysv(he);
2451 av_store(av, AvFILLp(av)+1, key); /* av_push(), really */
2456 for (i = 0; i < len; i++) {
2457 #ifdef HAS_RESTRICTED_HASHES
2458 int placeholders = (int)HvPLACEHOLDERS_get(hv);
2460 unsigned char flags = 0;
2464 SV *key = av_shift(av);
2465 /* This will fail if key is a placeholder.
2466 Track how many placeholders we have, and error if we
2468 HE *he = hv_fetch_ent(hv, key, 0, 0);
2472 if (!(val = HeVAL(he))) {
2473 /* Internal error, not I/O error */
2477 #ifdef HAS_RESTRICTED_HASHES
2478 /* Should be a placeholder. */
2479 if (placeholders-- < 0) {
2480 /* This should not happen - number of
2481 retrieves should be identical to
2482 number of placeholders. */
2485 /* Value is never needed, and PL_sv_undef is
2486 more space efficient to store. */
2489 ("Flags not 0 but %d", flags));
2490 flags = SHV_K_PLACEHOLDER;
2497 * Store value first.
2500 TRACEME(("(#%d) value 0x%" UVxf, i, PTR2UV(val)));
2502 if ((ret = store(aTHX_ cxt, val))) /* Extra () for -Wall, grr... */
2507 * Keys are written after values to make sure retrieval
2508 * can be optimal in terms of memory usage, where keys are
2509 * read into a fixed unique buffer called kbuf.
2510 * See retrieve_hash() for details.
2513 /* Implementation of restricted hashes isn't nicely
2515 if ((hash_flags & SHV_RESTRICTED)
2516 && SvTRULYREADONLY(val)) {
2517 flags |= SHV_K_LOCKED;
2520 keyval = SvPV(key, keylen_tmp);
2521 keylen = keylen_tmp;
2522 #ifdef HAS_UTF8_HASHES
2523 /* If you build without optimisation on pre 5.6
2524 then nothing spots that SvUTF8(key) is always 0,
2525 so the block isn't optimised away, at which point
2526 the linker dislikes the reference to
2529 const char *keysave = keyval;
2530 bool is_utf8 = TRUE;
2532 /* Just casting the &klen to (STRLEN) won't work
2533 well if STRLEN and I32 are of different widths.
2535 keyval = (char*)bytes_from_utf8((U8*)keyval,
2539 /* If we were able to downgrade here, then than
2540 means that we have a key which only had chars
2541 0-255, but was utf8 encoded. */
2543 if (keyval != keysave) {
2544 keylen = keylen_tmp;
2545 flags |= SHV_K_WASUTF8;
2547 /* keylen_tmp can't have changed, so no need
2548 to assign back to keylen. */
2549 flags |= SHV_K_UTF8;
2556 TRACEME(("(#%d) key '%s' flags %x %u", i, keyval, flags, *keyval));
2558 /* This is a workaround for a bug in 5.8.0
2559 that causes the HEK_WASUTF8 flag to be
2560 set on an HEK without the hash being
2561 marked as having key flags. We just
2562 cross our fingers and drop the flag.
2564 assert (flags == 0 || flags == SHV_K_WASUTF8);
2565 TRACEME(("(#%d) key '%s'", i, keyval));
2569 WRITE(keyval, keylen);
2570 if (flags & SHV_K_WASUTF8)
2575 * Free up the temporary array
2584 * Storing in "random" order (in the order the keys are stored
2585 * within the hash). This is the default and will be faster!
2588 for (i = 0; i < len; i++) {
2591 unsigned char flags;
2592 #ifdef HV_ITERNEXT_WANTPLACEHOLDERS
2593 HE *he = hv_iternext_flags(hv, HV_ITERNEXT_WANTPLACEHOLDERS);
2595 HE *he = hv_iternext(hv);
2597 SV *val = (he ? hv_iterval(hv, he) : 0);
2602 return 1; /* Internal error, not I/O error */
2604 /* Implementation of restricted hashes isn't nicely
2607 = (((hash_flags & SHV_RESTRICTED)
2608 && SvTRULYREADONLY(val))
2609 ? SHV_K_LOCKED : 0);
2611 if (val == &PL_sv_placeholder) {
2612 flags |= SHV_K_PLACEHOLDER;
2617 * Store value first.
2620 TRACEME(("(#%d) value 0x%" UVxf, i, PTR2UV(val)));
2622 if ((ret = store(aTHX_ cxt, val))) /* Extra () for -Wall, grr... */
2626 hek = HeKEY_hek(he);
2628 if (len == HEf_SVKEY) {
2629 /* This is somewhat sick, but the internal APIs are
2630 * such that XS code could put one of these in in
2632 * Maybe we should be capable of storing one if
2635 key_sv = HeKEY_sv(he);
2636 flags |= SHV_K_ISSV;
2638 /* Regular string key. */
2639 #ifdef HAS_HASH_KEY_FLAGS
2641 flags |= SHV_K_UTF8;
2642 if (HEK_WASUTF8(hek))
2643 flags |= SHV_K_WASUTF8;
2649 * Keys are written after values to make sure retrieval
2650 * can be optimal in terms of memory usage, where keys are
2651 * read into a fixed unique buffer called kbuf.
2652 * See retrieve_hash() for details.
2657 TRACEME(("(#%d) key '%s' flags %x", i, key, flags));
2659 /* This is a workaround for a bug in 5.8.0
2660 that causes the HEK_WASUTF8 flag to be
2661 set on an HEK without the hash being
2662 marked as having key flags. We just
2663 cross our fingers and drop the flag.
2665 assert (flags == 0 || flags == SHV_K_WASUTF8);
2666 TRACEME(("(#%d) key '%s'", i, key));
2668 if (flags & SHV_K_ISSV) {
2670 if ((ret = store(aTHX_ cxt, key_sv)))
2680 TRACEME(("ok (hash 0x%" UVxf ")", PTR2UV(hv)));
2683 HvRITER_set(hv, riter); /* Restore hash iterator state */
2684 HvEITER_set(hv, eiter);
2692 * Store a code reference.
2694 * Layout is SX_CODE <length> followed by a scalar containing the perl
2695 * source code of the code reference.
2697 static int store_code(pTHX_ stcxt_t *cxt, CV *cv)
2699 #if PERL_VERSION < 6
2701 * retrieve_code does not work with perl 5.005 or less
2703 return store_other(aTHX_ cxt, (SV*)cv);
2708 SV *text, *bdeparse;
2710 TRACEME(("store_code (0x%" UVxf ")", PTR2UV(cv)));
2713 cxt->deparse == 0 ||
2714 (cxt->deparse < 0 && !(cxt->deparse =
2715 SvTRUE(perl_get_sv("Storable::Deparse", GV_ADD)) ? 1 : 0))
2717 return store_other(aTHX_ cxt, (SV*)cv);
2721 * Require B::Deparse. At least B::Deparse 0.61 is needed for
2722 * blessed code references.
2724 /* Ownership of both SVs is passed to load_module, which frees them. */
2725 load_module(PERL_LOADMOD_NOIMPORT, newSVpvs("B::Deparse"), newSVnv(0.61));
2732 * create the B::Deparse object
2736 XPUSHs(newSVpvs_flags("B::Deparse", SVs_TEMP));
2738 count = call_method("new", G_SCALAR);
2741 CROAK(("Unexpected return value from B::Deparse::new\n"));
2745 * call the coderef2text method
2749 XPUSHs(bdeparse); /* XXX is this already mortal? */
2750 XPUSHs(sv_2mortal(newRV_inc((SV*)cv)));
2752 count = call_method("coderef2text", G_SCALAR);
2755 CROAK(("Unexpected return value from B::Deparse::coderef2text\n"));
2759 reallen = strlen(SvPV_nolen(text));
2762 * Empty code references or XS functions are deparsed as
2763 * "(prototype) ;" or ";".
2766 if (len == 0 || *(SvPV_nolen(text)+reallen-1) == ';') {
2767 CROAK(("The result of B::Deparse::coderef2text was empty - maybe you're trying to serialize an XS function?\n"));
2771 * Signal code by emitting SX_CODE.
2775 cxt->tagnum++; /* necessary, as SX_CODE is a SEEN() candidate */
2776 TRACEME(("size = %d", len));
2777 TRACEME(("code = %s", SvPV_nolen(text)));
2780 * Now store the source code.
2784 STORE_UTF8STR(SvPV_nolen(text), len);
2786 STORE_SCALAR(SvPV_nolen(text), len);
2791 TRACEME(("ok (code)"));
2800 * When storing a tied object (be it a tied scalar, array or hash), we lay out
2801 * a special mark, followed by the underlying tied object. For instance, when
2802 * dealing with a tied hash, we store SX_TIED_HASH <hash object>, where
2803 * <hash object> stands for the serialization of the tied hash.
2805 static int store_tied(pTHX_ stcxt_t *cxt, SV *sv)
2810 int svt = SvTYPE(sv);
2813 TRACEME(("store_tied (0x%" UVxf ")", PTR2UV(sv)));
2816 * We have a small run-time penalty here because we chose to factorise
2817 * all tieds objects into the same routine, and not have a store_tied_hash,
2818 * a store_tied_array, etc...
2820 * Don't use a switch() statement, as most compilers don't optimize that
2821 * well for 2/3 values. An if() else if() cascade is just fine. We put
2822 * tied hashes first, as they are the most likely beasts.
2825 if (svt == SVt_PVHV) {
2826 TRACEME(("tied hash"));
2827 PUTMARK(SX_TIED_HASH); /* Introduces tied hash */
2828 } else if (svt == SVt_PVAV) {
2829 TRACEME(("tied array"));
2830 PUTMARK(SX_TIED_ARRAY); /* Introduces tied array */
2832 TRACEME(("tied scalar"));
2833 PUTMARK(SX_TIED_SCALAR); /* Introduces tied scalar */
2837 if (!(mg = mg_find(sv, mtype)))
2838 CROAK(("No magic '%c' found while storing tied %s", mtype,
2839 (svt == SVt_PVHV) ? "hash" :
2840 (svt == SVt_PVAV) ? "array" : "scalar"));
2843 * The mg->mg_obj found by mg_find() above actually points to the
2844 * underlying tied Perl object implementation. For instance, if the
2845 * original SV was that of a tied array, then mg->mg_obj is an AV.
2847 * Note that we store the Perl object as-is. We don't call its FETCH
2848 * method along the way. At retrieval time, we won't call its STORE
2849 * method either, but the tieing magic will be re-installed. In itself,
2850 * that ensures that the tieing semantics are preserved since further
2851 * accesses on the retrieved object will indeed call the magic methods...
2854 /* [#17040] mg_obj is NULL for scalar self-ties. AMS 20030416 */
2855 obj = mg->mg_obj ? mg->mg_obj : newSV(0);
2856 if ((ret = store(aTHX_ cxt, obj)))
2859 TRACEME(("ok (tied)"));
2867 * Stores a reference to an item within a tied structure:
2869 * . \$h{key}, stores both the (tied %h) object and 'key'.
2870 * . \$a[idx], stores both the (tied @a) object and 'idx'.
2872 * Layout is therefore either:
2873 * SX_TIED_KEY <object> <key>
2874 * SX_TIED_IDX <object> <index>
2876 static int store_tied_item(pTHX_ stcxt_t *cxt, SV *sv)
2881 TRACEME(("store_tied_item (0x%" UVxf ")", PTR2UV(sv)));
2883 if (!(mg = mg_find(sv, 'p')))
2884 CROAK(("No magic 'p' found while storing reference to tied item"));
2887 * We discriminate between \$h{key} and \$a[idx] via mg_ptr.
2891 TRACEME(("store_tied_item: storing a ref to a tied hash item"));
2892 PUTMARK(SX_TIED_KEY);
2893 TRACEME(("store_tied_item: storing OBJ 0x%" UVxf,
2894 PTR2UV(mg->mg_obj)));
2896 if ((ret = store(aTHX_ cxt, mg->mg_obj))) /* Extra () for -Wall, grr... */
2899 TRACEME(("store_tied_item: storing PTR 0x%" UVxf,
2900 PTR2UV(mg->mg_ptr)));
2902 if ((ret = store(aTHX_ cxt, (SV *) mg->mg_ptr))) /* Idem, for -Wall */
2905 I32 idx = mg->mg_len;
2907 TRACEME(("store_tied_item: storing a ref to a tied array item "));
2908 PUTMARK(SX_TIED_IDX);
2909 TRACEME(("store_tied_item: storing OBJ 0x%" UVxf,
2910 PTR2UV(mg->mg_obj)));
2912 if ((ret = store(aTHX_ cxt, mg->mg_obj))) /* Idem, for -Wall */
2915 TRACEME(("store_tied_item: storing IDX %d", idx));
2920 TRACEME(("ok (tied item)"));
2926 * store_hook -- dispatched manually, not via sv_store[]
2928 * The blessed SV is serialized by a hook.
2932 * SX_HOOK <flags> <len> <classname> <len2> <str> [<len3> <object-IDs>]
2934 * where <flags> indicates how long <len>, <len2> and <len3> are, whether
2935 * the trailing part [] is present, the type of object (scalar, array or hash).
2936 * There is also a bit which says how the classname is stored between:
2941 * and when the <index> form is used (classname already seen), the "large
2942 * classname" bit in <flags> indicates how large the <index> is.
2944 * The serialized string returned by the hook is of length <len2> and comes
2945 * next. It is an opaque string for us.
2947 * Those <len3> object IDs which are listed last represent the extra references
2948 * not directly serialized by the hook, but which are linked to the object.
2950 * When recursion is mandated to resolve object-IDs not yet seen, we have
2951 * instead, with <header> being flags with bits set to indicate the object type
2952 * and that recursion was indeed needed:
2954 * SX_HOOK <header> <object> <header> <object> <flags>
2956 * that same header being repeated between serialized objects obtained through
2957 * recursion, until we reach flags indicating no recursion, at which point
2958 * we know we've resynchronized with a single layout, after <flags>.
2960 * When storing a blessed ref to a tied variable, the following format is
2963 * SX_HOOK <flags> <extra> ... [<len3> <object-IDs>] <magic object>
2965 * The first <flags> indication carries an object of type SHT_EXTRA, and the
2966 * real object type is held in the <extra> flag. At the very end of the
2967 * serialization stream, the underlying magic object is serialized, just like
2968 * any other tied variable.
2970 static int store_hook(
2984 int count; /* really len3 + 1 */
2985 unsigned char flags;
2988 int recursed = 0; /* counts recursion */
2989 int obj_type; /* object type, on 2 bits */
2992 int clone = cxt->optype & ST_CLONE;
2993 char mtype = '\0'; /* for blessed ref to tied structures */
2994 unsigned char eflags = '\0'; /* used when object type is SHT_EXTRA */
2996 TRACEME(("store_hook, classname \"%s\", tagged #%d", HvNAME_get(pkg), cxt->tagnum));
2999 * Determine object type on 2 bits.
3005 obj_type = SHT_SCALAR;
3008 obj_type = SHT_ARRAY;
3011 obj_type = SHT_HASH;
3015 * Produced by a blessed ref to a tied data structure, $o in the
3016 * following Perl code.
3020 * my $o = bless \%h, 'BAR';
3022 * Signal the tie-ing magic by setting the object type as SHT_EXTRA
3023 * (since we have only 2 bits in <flags> to store the type), and an
3024 * <extra> byte flag will be emitted after the FIRST <flags> in the
3025 * stream, carrying what we put in 'eflags'.
3027 obj_type = SHT_EXTRA;
3028 switch (SvTYPE(sv)) {
3030 eflags = (unsigned char) SHT_THASH;
3034 eflags = (unsigned char) SHT_TARRAY;
3038 eflags = (unsigned char) SHT_TSCALAR;
3044 CROAK(("Unexpected object type (%d) in store_hook()", type));
3046 flags = SHF_NEED_RECURSE | obj_type;
3048 classname = HvNAME_get(pkg);
3049 len = strlen(classname);
3052 * To call the hook, we need to fake a call like:
3054 * $object->STORABLE_freeze($cloning);
3056 * but we don't have the $object here. For instance, if $object is
3057 * a blessed array, what we have in 'sv' is the array, and we can't
3058 * call a method on those.
3060 * Therefore, we need to create a temporary reference to the object and
3061 * make the call on that reference.
3064 TRACEME(("about to call STORABLE_freeze on class %s", classname));
3066 ref = newRV_inc(sv); /* Temporary reference */
3067 av = array_call(aTHX_ ref, hook, clone); /* @a = $object->STORABLE_freeze($c) */
3068 SvREFCNT_dec(ref); /* Reclaim temporary reference */
3070 count = AvFILLp(av) + 1;
3071 TRACEME(("store_hook, array holds %d items", count));
3074 * If they return an empty list, it means they wish to ignore the
3075 * hook for this class (and not just this instance -- that's for them
3076 * to handle if they so wish).
3078 * Simply disable the cached entry for the hook (it won't be recomputed
3079 * since it's present in the cache) and recurse to store_blessed().
3083 /* free empty list returned by the hook */
3088 * They must not change their mind in the middle of a serialization.
3091 if (hv_fetch(cxt->hclass, classname, len, FALSE))
3092 CROAK(("Too late to ignore hooks for %s class \"%s\"",
3093 (cxt->optype & ST_CLONE) ? "cloning" : "storing", classname));
3095 pkg_hide(aTHX_ cxt->hook, pkg, "STORABLE_freeze");
3097 ASSERT(!pkg_can(aTHX_ cxt->hook, pkg, "STORABLE_freeze"), ("hook invisible"));
3098 TRACEME(("ignoring STORABLE_freeze in class \"%s\"", classname));
3100 return store_blessed(aTHX_ cxt, sv, type, pkg);
3104 * Get frozen string.
3108 pv = SvPV(ary[0], len2);
3109 /* We can't use pkg_can here because it only caches one method per
3112 GV* gv = gv_fetchmethod_autoload(pkg, "STORABLE_attach", FALSE);
3113 if (gv && isGV(gv)) {
3115 CROAK(("Freeze cannot return references if %s class is using STORABLE_attach", classname));
3121 * If they returned more than one item, we need to serialize some
3122 * extra references if not already done.
3124 * Loop over the array, starting at position #1, and for each item,
3125 * ensure it is a reference, serialize it if not already done, and
3126 * replace the entry with the tag ID of the corresponding serialized
3129 * We CHEAT by not calling av_fetch() and read directly within the
3133 for (i = 1; i < count; i++) {
3134 #ifdef USE_PTR_TABLE
3142 AV *av_hook = cxt->hook_seen;
3145 CROAK(("Item #%d returned by STORABLE_freeze "
3146 "for %s is not a reference", i, classname));
3147 xsv = SvRV(rsv); /* Follow ref to know what to look for */
3150 * Look in hseen and see if we have a tag already.
3151 * Serialize entry if not done already, and get its tag.
3154 #ifdef USE_PTR_TABLE
3155 /* Fakery needed because ptr_table_fetch returns zero for a
3156 failure, whereas the existing code assumes that it can
3157 safely store a tag zero. So for ptr_tables we store tag+1
3159 if ((fake_tag = (char *)ptr_table_fetch(cxt->pseen, xsv)))
3160 goto sv_seen; /* Avoid moving code too far to the right */
3162 if ((svh = hv_fetch(cxt->hseen, (char *) &xsv, sizeof(xsv), FALSE)))
3163 goto sv_seen; /* Avoid moving code too far to the right */
3166 TRACEME(("listed object %d at 0x%" UVxf " is unknown",
3170 * We need to recurse to store that object and get it to be known
3171 * so that we can resolve the list of object-IDs at retrieve time.
3173 * The first time we do this, we need to emit the proper header
3174 * indicating that we recursed, and what the type of object is (the
3175 * object we're storing via a user-hook). Indeed, during retrieval,
3176 * we'll have to create the object before recursing to retrieve the
3177 * others, in case those would point back at that object.
3180 /* [SX_HOOK] <flags> [<extra>] <object>*/
3184 if (obj_type == SHT_EXTRA)
3189 if ((ret = store(aTHX_ cxt, xsv))) /* Given by hook for us to store */
3192 #ifdef USE_PTR_TABLE
3193 fake_tag = (char *)ptr_table_fetch(cxt->pseen, xsv);
3195 CROAK(("Could not serialize item #%d from hook in %s", i, classname));
3197 svh = hv_fetch(cxt->hseen, (char *) &xsv, sizeof(xsv), FALSE);
3199 CROAK(("Could not serialize item #%d from hook in %s", i, classname));
3202 * It was the first time we serialized 'xsv'.
3204 * Keep this SV alive until the end of the serialization: if we
3205 * disposed of it right now by decrementing its refcount, and it was
3206 * a temporary value, some next temporary value allocated during
3207 * another STORABLE_freeze might take its place, and we'd wrongly
3208 * assume that new SV was already serialized, based on its presence
3211 * Therefore, push it away in cxt->hook_seen.
3214 av_store(av_hook, AvFILLp(av_hook)+1, SvREFCNT_inc(xsv));
3218 * Dispose of the REF they returned. If we saved the 'xsv' away
3219 * in the array of returned SVs, that will not cause the underlying
3220 * referenced SV to be reclaimed.
3223 ASSERT(SvREFCNT(xsv) > 1, ("SV will survive disposal of its REF"));
3224 SvREFCNT_dec(rsv); /* Dispose of reference */
3227 * Replace entry with its tag (not a real SV, so no refcnt increment)
3230 #ifdef USE_PTR_TABLE
3231 tag = (SV *)--fake_tag;
3236 TRACEME(("listed object %d at 0x%" UVxf " is tag #%" UVuf,
3237 i-1, PTR2UV(xsv), PTR2UV(tag)));
3241 * Allocate a class ID if not already done.
3243 * This needs to be done after the recursion above, since at retrieval
3244 * time, we'll see the inner objects first. Many thanks to
3245 * Salvador Ortiz Garcia <sog@msg.com.mx> who spot that bug and
3246 * proposed the right fix. -- RAM, 15/09/2000
3250 if (!known_class(aTHX_ cxt, classname, len, &classnum)) {
3251 TRACEME(("first time we see class %s, ID = %d", classname, classnum));
3252 classnum = -1; /* Mark: we must store classname */
3254 TRACEME(("already seen class %s, ID = %d", classname, classnum));
3258 * Compute leading flags.
3262 if (((classnum == -1) ? len : classnum) > LG_SCALAR)
3263 flags |= SHF_LARGE_CLASSLEN;
3265 flags |= SHF_IDX_CLASSNAME;
3266 if (len2 > LG_SCALAR)
3267 flags |= SHF_LARGE_STRLEN;
3269 flags |= SHF_HAS_LIST;
3270 if (count > (LG_SCALAR + 1))
3271 flags |= SHF_LARGE_LISTLEN;
3274 * We're ready to emit either serialized form:
3276 * SX_HOOK <flags> <len> <classname> <len2> <str> [<len3> <object-IDs>]
3277 * SX_HOOK <flags> <index> <len2> <str> [<len3> <object-IDs>]
3279 * If we recursed, the SX_HOOK has already been emitted.
3282 TRACEME(("SX_HOOK (recursed=%d) flags=0x%x "
3283 "class=%" IVdf " len=%" IVdf " len2=%" IVdf " len3=%d",
3284 recursed, flags, (IV)classnum, (IV)len, (IV)len2, count-1));
3286 /* SX_HOOK <flags> [<extra>] */
3290 if (obj_type == SHT_EXTRA)
3295 /* <len> <classname> or <index> */
3296 if (flags & SHF_IDX_CLASSNAME) {
3297 if (flags & SHF_LARGE_CLASSLEN)
3300 unsigned char cnum = (unsigned char) classnum;
3304 if (flags & SHF_LARGE_CLASSLEN)
3307 unsigned char clen = (unsigned char) len;
3310 WRITE(classname, len); /* Final \0 is omitted */
3313 /* <len2> <frozen-str> */
3314 if (flags & SHF_LARGE_STRLEN) {
3315 I32 wlen2 = len2; /* STRLEN might be 8 bytes */
3316 WLEN(wlen2); /* Must write an I32 for 64-bit machines */
3318 unsigned char clen = (unsigned char) len2;
3322 WRITE(pv, (SSize_t)len2); /* Final \0 is omitted */
3324 /* [<len3> <object-IDs>] */
3325 if (flags & SHF_HAS_LIST) {
3326 int len3 = count - 1;
3327 if (flags & SHF_LARGE_LISTLEN)
3330 unsigned char clen = (unsigned char) len3;
3335 * NOTA BENE, for 64-bit machines: the ary[i] below does not yield a
3336 * real pointer, rather a tag number, well under the 32-bit limit.
3339 for (i = 1; i < count; i++) {
3340 I32 tagval = htonl(LOW_32BITS(ary[i]));
3342 TRACEME(("object %d, tag #%d", i-1, ntohl(tagval)));
3347 * Free the array. We need extra care for indices after 0, since they
3348 * don't hold real SVs but integers cast.
3352 AvFILLp(av) = 0; /* Cheat, nothing after 0 interests us */
3357 * If object was tied, need to insert serialization of the magic object.
3360 if (obj_type == SHT_EXTRA) {
3363 if (!(mg = mg_find(sv, mtype))) {
3364 int svt = SvTYPE(sv);
3365 CROAK(("No magic '%c' found while storing ref to tied %s with hook",
3366 mtype, (svt == SVt_PVHV) ? "hash" :
3367 (svt == SVt_PVAV) ? "array" : "scalar"));
3370 TRACEME(("handling the magic object 0x%" UVxf " part of 0x%"
3371 UVxf, PTR2UV(mg->mg_obj), PTR2UV(sv)));
3377 if ((ret = store(aTHX_ cxt, mg->mg_obj))) /* Extra () for -Wall, grr... */
3385 * store_blessed -- dispatched manually, not via sv_store[]
3387 * Check whether there is a STORABLE_xxx hook defined in the class or in one
3388 * of its ancestors. If there is, then redispatch to store_hook();
3390 * Otherwise, the blessed SV is stored using the following layout:
3392 * SX_BLESS <flag> <len> <classname> <object>
3394 * where <flag> indicates whether <len> is stored on 0 or 4 bytes, depending
3395 * on the high-order bit in flag: if 1, then length follows on 4 bytes.
3396 * Otherwise, the low order bits give the length, thereby giving a compact
3397 * representation for class names less than 127 chars long.
3399 * Each <classname> seen is remembered and indexed, so that the next time
3400 * an object in the blessed in the same <classname> is stored, the following
3403 * SX_IX_BLESS <flag> <index> <object>
3405 * where <index> is the classname index, stored on 0 or 4 bytes depending
3406 * on the high-order bit in flag (same encoding as above for <len>).
3408 static int store_blessed(
3420 TRACEME(("store_blessed, type %d, class \"%s\"", type, HvNAME_get(pkg)));
3423 * Look for a hook for this blessed SV and redirect to store_hook()
3427 hook = pkg_can(aTHX_ cxt->hook, pkg, "STORABLE_freeze");
3429 return store_hook(aTHX_ cxt, sv, type, pkg, hook);
3432 * This is a blessed SV without any serialization hook.
3435 classname = HvNAME_get(pkg);
3436 len = strlen(classname);
3438 TRACEME(("blessed 0x%" UVxf " in %s, no hook: tagged #%d",
3439 PTR2UV(sv), classname, cxt->tagnum));
3442 * Determine whether it is the first time we see that class name (in which
3443 * case it will be stored in the SX_BLESS form), or whether we already
3444 * saw that class name before (in which case the SX_IX_BLESS form will be
3448 if (known_class(aTHX_ cxt, classname, len, &classnum)) {
3449 TRACEME(("already seen class %s, ID = %d", classname, classnum));
3450 PUTMARK(SX_IX_BLESS);
3451 if (classnum <= LG_BLESS) {
3452 unsigned char cnum = (unsigned char) classnum;
3455 unsigned char flag = (unsigned char) 0x80;
3460 TRACEME(("first time we see class %s, ID = %d", classname, classnum));
3462 if (len <= LG_BLESS) {
3463 unsigned char clen = (unsigned char) len;
3466 unsigned char flag = (unsigned char) 0x80;
3468 WLEN(len); /* Don't BER-encode, this should be rare */
3470 WRITE(classname, len); /* Final \0 is omitted */
3474 * Now emit the <object> part.
3477 return SV_STORE(type)(aTHX_ cxt, sv);
3483 * We don't know how to store the item we reached, so return an error condition.
3484 * (it's probably a GLOB, some CODE reference, etc...)
3486 * If they defined the 'forgive_me' variable at the Perl level to some
3487 * true value, then don't croak, just warn, and store a placeholder string
3490 static int store_other(pTHX_ stcxt_t *cxt, SV *sv)
3495 TRACEME(("store_other"));
3498 * Fetch the value from perl only once per store() operation.
3502 cxt->forgive_me == 0 ||
3503 (cxt->forgive_me < 0 && !(cxt->forgive_me =
3504 SvTRUE(perl_get_sv("Storable::forgive_me", GV_ADD)) ? 1 : 0))
3506 CROAK(("Can't store %s items", sv_reftype(sv, FALSE)));
3508 warn("Can't store item %s(0x%" UVxf ")",
3509 sv_reftype(sv, FALSE), PTR2UV(sv));
3512 * Store placeholder string as a scalar instead...
3515 (void) sprintf(buf, "You lost %s(0x%" UVxf ")%c", sv_reftype(sv, FALSE),
3516 PTR2UV(sv), (char) 0);
3519 STORE_SCALAR(buf, len);
3520 TRACEME(("ok (dummy \"%s\", length = %" IVdf ")", buf, (IV) len));
3526 *** Store driving routines
3532 * WARNING: partially duplicates Perl's sv_reftype for speed.
3534 * Returns the type of the SV, identified by an integer. That integer
3535 * may then be used to index the dynamic routine dispatch table.
3537 static int sv_type(pTHX_ SV *sv)
3539 switch (SvTYPE(sv)) {
3541 #if PERL_VERSION <= 10
3546 * No need to check for ROK, that can't be set here since there
3547 * is no field capable of hodling the xrv_rv reference.
3551 #if PERL_VERSION <= 10
3559 * Starting from SVt_PV, it is possible to have the ROK flag
3560 * set, the pointer to the other SV being either stored in
3561 * the xrv_rv (in the case of a pure SVt_RV), or as the
3562 * xpv_pv field of an SVt_PV and its heirs.
3564 * However, those SV cannot be magical or they would be an
3565 * SVt_PVMG at least.
3567 return SvROK(sv) ? svis_REF : svis_SCALAR;
3569 case SVt_PVLV: /* Workaround for perl5.004_04 "LVALUE" bug */
3570 if ((SvFLAGS(sv) & (SVs_GMG|SVs_SMG|SVs_RMG)) ==
3571 (SVs_GMG|SVs_SMG|SVs_RMG) &&
3573 return svis_TIED_ITEM;
3575 #if PERL_VERSION < 9
3578 if ((SvFLAGS(sv) & (SVs_GMG|SVs_SMG|SVs_RMG)) ==
3579 (SVs_GMG|SVs_SMG|SVs_RMG) &&
3582 return SvROK(sv) ? svis_REF : svis_SCALAR;
3584 if (SvRMAGICAL(sv) && (mg_find(sv, 'P')))
3588 if (SvRMAGICAL(sv) && (mg_find(sv, 'P')))
3593 #if PERL_VERSION > 8
3594 /* case SVt_INVLIST: */
3606 * Recursively store objects pointed to by the sv to the specified file.
3608 * Layout is <content> or SX_OBJECT <tagnum> if we reach an already stored
3609 * object (one for which storage has started -- it may not be over if we have
3610 * a self-referenced structure). This data set forms a stored <object>.
3612 static int store(pTHX_ stcxt_t *cxt, SV *sv)
3617 #ifdef USE_PTR_TABLE
3618 struct ptr_tbl *pseen = cxt->pseen;
3620 HV *hseen = cxt->hseen;
3623 TRACEME(("store (0x%" UVxf ")", PTR2UV(sv)));
3626 * If object has already been stored, do not duplicate data.
3627 * Simply emit the SX_OBJECT marker followed by its tag data.
3628 * The tag is always written in network order.
3630 * NOTA BENE, for 64-bit machines: the "*svh" below does not yield a
3631 * real pointer, rather a tag number (watch the insertion code below).
3632 * That means it probably safe to assume it is well under the 32-bit limit,
3633 * and makes the truncation safe.
3634 * -- RAM, 14/09/1999
3637 #ifdef USE_PTR_TABLE
3638 svh = (SV **)ptr_table_fetch(pseen, sv);
3640 svh = hv_fetch(hseen, (char *) &sv, sizeof(sv), FALSE);
3645 if (sv == &PL_sv_undef) {
3646 /* We have seen PL_sv_undef before, but fake it as
3649 Not the simplest solution to making restricted
3650 hashes work on 5.8.0, but it does mean that
3651 repeated references to the one true undef will
3652 take up less space in the output file.
3654 /* Need to jump past the next hv_store, because on the
3655 second store of undef the old hash value will be
3656 SvREFCNT_dec()ed, and as Storable cheats horribly
3657 by storing non-SVs in the hash a SEGV will ensure.
3658 Need to increase the tag number so that the
3659 receiver has no idea what games we're up to. This
3660 special casing doesn't affect hooks that store
3661 undef, as the hook routine does its own lookup into
3662 hseen. Also this means that any references back
3663 to PL_sv_undef (from the pathological case of hooks
3664 storing references to it) will find the seen hash
3665 entry for the first time, as if we didn't have this
3666 hackery here. (That hseen lookup works even on 5.8.0
3667 because it's a key of &PL_sv_undef and a value
3668 which is a tag number, not a value which is
3672 goto undef_special_case;
3675 #ifdef USE_PTR_TABLE
3676 tagval = htonl(LOW_32BITS(((char *)svh)-1));
3678 tagval = htonl(LOW_32BITS(*svh));
3681 TRACEME(("object 0x%" UVxf " seen as #%d",
3682 PTR2UV(sv), ntohl(tagval)));
3690 * Allocate a new tag and associate it with the address of the sv being
3691 * stored, before recursing...
3693 * In order to avoid creating new SvIVs to hold the tagnum we just
3694 * cast the tagnum to an SV pointer and store that in the hash. This
3695 * means that we must clean up the hash manually afterwards, but gives
3696 * us a 15% throughput increase.
3701 #ifdef USE_PTR_TABLE
3702 ptr_table_store(pseen, sv, INT2PTR(SV*, 1 + cxt->tagnum));
3704 if (!hv_store(hseen,
3705 (char *) &sv, sizeof(sv), INT2PTR(SV*, cxt->tagnum), 0))
3710 * Store 'sv' and everything beneath it, using appropriate routine.
3711 * Abort immediately if we get a non-zero status back.
3714 type = sv_type(aTHX_ sv);
3717 TRACEME(("storing 0x%" UVxf " tag #%d, type %d...",
3718 PTR2UV(sv), cxt->tagnum, type));
3721 HV *pkg = SvSTASH(sv);
3722 ret = store_blessed(aTHX_ cxt, sv, type, pkg);
3724 ret = SV_STORE(type)(aTHX_ cxt, sv);
3726 TRACEME(("%s (stored 0x%" UVxf ", refcnt=%d, %s)",
3727 ret ? "FAILED" : "ok", PTR2UV(sv),
3728 SvREFCNT(sv), sv_reftype(sv, FALSE)));
3736 * Write magic number and system information into the file.
3737 * Layout is <magic> <network> [<len> <byteorder> <sizeof int> <sizeof long>
3738 * <sizeof ptr>] where <len> is the length of the byteorder hexa string.
3739 * All size and lengths are written as single characters here.
3741 * Note that no byte ordering info is emitted when <network> is true, since
3742 * integers will be emitted in network order in that case.
3744 static int magic_write(pTHX_ stcxt_t *cxt)
3747 * Starting with 0.6, the "use_network_order" byte flag is also used to
3748 * indicate the version number of the binary image, encoded in the upper
3749 * bits. The bit 0 is always used to indicate network order.
3752 * Starting with 0.7, a full byte is dedicated to the minor version of
3753 * the binary format, which is incremented only when new markers are
3754 * introduced, for instance, but when backward compatibility is preserved.
3757 /* Make these at compile time. The WRITE() macro is sufficiently complex
3758 that it saves about 200 bytes doing it this way and only using it
3760 static const unsigned char network_file_header[] = {
3762 (STORABLE_BIN_MAJOR << 1) | 1,
3763 STORABLE_BIN_WRITE_MINOR
3765 static const unsigned char file_header[] = {
3767 (STORABLE_BIN_MAJOR << 1) | 0,
3768 STORABLE_BIN_WRITE_MINOR,
3769 /* sizeof the array includes the 0 byte at the end: */
3770 (char) sizeof (byteorderstr) - 1,
3772 (unsigned char) sizeof(int),
3773 (unsigned char) sizeof(long),
3774 (unsigned char) sizeof(char *),
3775 (unsigned char) sizeof(NV)
3777 #ifdef USE_56_INTERWORK_KLUDGE
3778 static const unsigned char file_header_56[] = {
3780 (STORABLE_BIN_MAJOR << 1) | 0,
3781 STORABLE_BIN_WRITE_MINOR,
3782 /* sizeof the array includes the 0 byte at the end: */
3783 (char) sizeof (byteorderstr_56) - 1,
3785 (unsigned char) sizeof(int),
3786 (unsigned char) sizeof(long),
3787 (unsigned char) sizeof(char *),
3788 (unsigned char) sizeof(NV)
3791 const unsigned char *header;
3794 TRACEME(("magic_write on fd=%d", cxt->fio ? PerlIO_fileno(cxt->fio) : -1));
3796 if (cxt->netorder) {
3797 header = network_file_header;
3798 length = sizeof (network_file_header);
3800 #ifdef USE_56_INTERWORK_KLUDGE
3801 if (SvTRUE(perl_get_sv("Storable::interwork_56_64bit", GV_ADD))) {
3802 header = file_header_56;
3803 length = sizeof (file_header_56);
3807 header = file_header;
3808 length = sizeof (file_header);
3813 /* sizeof the array includes the 0 byte at the end. */
3814 header += sizeof (magicstr) - 1;
3815 length -= sizeof (magicstr) - 1;
3818 WRITE( (unsigned char*) header, length);
3820 if (!cxt->netorder) {
3821 TRACEME(("ok (magic_write byteorder = 0x%lx [%d], I%d L%d P%d D%d)",
3822 (unsigned long) BYTEORDER, (int) sizeof (byteorderstr) - 1,
3823 (int) sizeof(int), (int) sizeof(long),
3824 (int) sizeof(char *), (int) sizeof(NV)));
3832 * Common code for store operations.
3834 * When memory store is requested (f = NULL) and a non null SV* is given in
3835 * 'res', it is filled with a new SV created out of the memory buffer.
3837 * It is required to provide a non-null 'res' when the operation type is not
3838 * dclone() and store() is performed to memory.
3840 static int do_store(
3851 ASSERT(!(f == 0 && !(optype & ST_CLONE)) || res,
3852 ("must supply result SV pointer for real recursion to memory"));
3854 TRACEME(("do_store (optype=%d, netorder=%d)",
3855 optype, network_order));
3860 * Workaround for CROAK leak: if they enter with a "dirty" context,
3861 * free up memory for them now.
3866 clean_context(aTHX_ cxt);
3869 * Now that STORABLE_xxx hooks exist, it is possible that they try to
3870 * re-enter store() via the hooks. We need to stack contexts.
3874 cxt = allocate_context(aTHX_ cxt);
3878 ASSERT(cxt->entry == 1, ("starting new recursion"));
3879 ASSERT(!cxt->s_dirty, ("clean context"));
3882 * Ensure sv is actually a reference. From perl, we called something
3884 * pstore(aTHX_ FILE, \@array);
3885 * so we must get the scalar value behind that reference.
3889 CROAK(("Not a reference"));
3890 sv = SvRV(sv); /* So follow it to know what to store */
3893 * If we're going to store to memory, reset the buffer.
3900 * Prepare context and emit headers.
3903 init_store_context(aTHX_ cxt, f, optype, network_order);
3905 if (-1 == magic_write(aTHX_ cxt)) /* Emit magic and ILP info */
3906 return 0; /* Error */
3909 * Recursively store object...
3912 ASSERT(is_storing(aTHX), ("within store operation"));
3914 status = store(aTHX_ cxt, sv); /* Just do it! */
3917 * If they asked for a memory store and they provided an SV pointer,
3918 * make an SV string out of the buffer and fill their pointer.
3920 * When asking for ST_REAL, it's MANDATORY for the caller to provide
3921 * an SV, since context cleanup might free the buffer if we did recurse.
3922 * (unless caller is dclone(), which is aware of that).
3925 if (!cxt->fio && res)
3926 *res = mbuf2sv(aTHX);
3931 * The "root" context is never freed, since it is meant to be always
3932 * handy for the common case where no recursion occurs at all (i.e.
3933 * we enter store() outside of any Storable code and leave it, period).
3934 * We know it's the "root" context because there's nothing stacked
3939 * When deep cloning, we don't free the context: doing so would force
3940 * us to copy the data in the memory buffer. Sicne we know we're
3941 * about to enter do_retrieve...
3944 clean_store_context(aTHX_ cxt);
3945 if (cxt->prev && !(cxt->optype & ST_CLONE))
3946 free_context(aTHX_ cxt);
3948 TRACEME(("do_store returns %d", status));
3960 * Build a new SV out of the content of the internal memory buffer.
3962 static SV *mbuf2sv(pTHX)
3967 return newSVpv(mbase, MBUF_SIZE());
3971 *** Specific retrieve callbacks.
3977 * Return an error via croak, since it is not possible that we get here
3978 * under normal conditions, when facing a file produced via pstore().
3980 static SV *retrieve_other(pTHX_ stcxt_t *cxt, const char *cname)
3982 PERL_UNUSED_ARG(cname);
3984 cxt->ver_major != STORABLE_BIN_MAJOR &&
3985 cxt->ver_minor != STORABLE_BIN_MINOR
3987 CROAK(("Corrupted storable %s (binary v%d.%d), current is v%d.%d",
3988 cxt->fio ? "file" : "string",
3989 cxt->ver_major, cxt->ver_minor,
3990 STORABLE_BIN_MAJOR, STORABLE_BIN_MINOR));
3992 CROAK(("Corrupted storable %s (binary v%d.%d)",
3993 cxt->fio ? "file" : "string",
3994 cxt->ver_major, cxt->ver_minor));
3997 return (SV *) 0; /* Just in case */
4001 * retrieve_idx_blessed
4003 * Layout is SX_IX_BLESS <index> <object> with SX_IX_BLESS already read.
4004 * <index> can be coded on either 1 or 5 bytes.
4006 static SV *retrieve_idx_blessed(pTHX_ stcxt_t *cxt, const char *cname)
4009 const char *classname;
4013 PERL_UNUSED_ARG(cname);
4014 TRACEME(("retrieve_idx_blessed (#%d)", cxt->tagnum));
4015 ASSERT(!cname, ("no bless-into class given here, got %s", cname));
4017 GETMARK(idx); /* Index coded on a single char? */
4022 * Fetch classname in 'aclass'
4025 sva = av_fetch(cxt->aclass, idx, FALSE);
4027 CROAK(("Class name #%" IVdf " should have been seen already",
4030 classname = SvPVX(*sva); /* We know it's a PV, by construction */
4032 TRACEME(("class ID %d => %s", idx, classname));
4035 * Retrieve object and bless it.
4038 sv = retrieve(aTHX_ cxt, classname); /* First SV which is SEEN will be blessed */
4046 * Layout is SX_BLESS <len> <classname> <object> with SX_BLESS already read.
4047 * <len> can be coded on either 1 or 5 bytes.
4049 static SV *retrieve_blessed(pTHX_ stcxt_t *cxt, const char *cname)
4053 char buf[LG_BLESS + 1]; /* Avoid malloc() if possible */
4054 char *classname = buf;
4055 char *malloced_classname = NULL;
4057 PERL_UNUSED_ARG(cname);
4058 TRACEME(("retrieve_blessed (#%d)", cxt->tagnum));
4059 ASSERT(!cname, ("no bless-into class given here, got %s", cname));
4062 * Decode class name length and read that name.
4064 * Short classnames have two advantages: their length is stored on one
4065 * single byte, and the string can be read on the stack.
4068 GETMARK(len); /* Length coded on a single char? */
4071 TRACEME(("** allocating %d bytes for class name", len+1));
4072 New(10003, classname, len+1, char);
4073 malloced_classname = classname;
4075 SAFEPVREAD(classname, len, malloced_classname);
4076 classname[len] = '\0'; /* Mark string end */
4079 * It's a new classname, otherwise it would have been an SX_IX_BLESS.
4082 TRACEME(("new class name \"%s\" will bear ID = %d", classname, cxt->classnum));
4084 if (!av_store(cxt->aclass, cxt->classnum++, newSVpvn(classname, len))) {
4085 Safefree(malloced_classname);
4090 * Retrieve object and bless it.
4093 sv = retrieve(aTHX_ cxt, classname); /* First SV which is SEEN will be blessed */
4094 if (malloced_classname)
4095 Safefree(malloced_classname);
4103 * Layout: SX_HOOK <flags> <len> <classname> <len2> <str> [<len3> <object-IDs>]
4104 * with leading mark already read, as usual.
4106 * When recursion was involved during serialization of the object, there
4107 * is an unknown amount of serialized objects after the SX_HOOK mark. Until
4108 * we reach a <flags> marker with the recursion bit cleared.
4110 * If the first <flags> byte contains a type of SHT_EXTRA, then the real type
4111 * is held in the <extra> byte, and if the object is tied, the serialized
4112 * magic object comes at the very end:
4114 * SX_HOOK <flags> <extra> ... [<len3> <object-IDs>] <magic object>
4116 * This means the STORABLE_thaw hook will NOT get a tied variable during its
4117 * processing (since we won't have seen the magic object by the time the hook
4118 * is called). See comments below for why it was done that way.
4120 static SV *retrieve_hook(pTHX_ stcxt_t *cxt, const char *cname)
4123 char buf[LG_BLESS + 1]; /* Avoid malloc() if possible */
4124 char *classname = buf;
4136 int clone = cxt->optype & ST_CLONE;
4138 unsigned int extra_type = 0;
4140 PERL_UNUSED_ARG(cname);
4141 TRACEME(("retrieve_hook (#%d)", cxt->tagnum));
4142 ASSERT(!cname, ("no bless-into class given here, got %s", cname));
4145 * Read flags, which tell us about the type, and whether we need to recurse.
4151 * Create the (empty) object, and mark it as seen.
4153 * This must be done now, because tags are incremented, and during
4154 * serialization, the object tag was affected before recursion could
4158 obj_type = flags & SHF_TYPE_MASK;
4164 sv = (SV *) newAV();
4167 sv = (SV *) newHV();
4171 * Read <extra> flag to know the type of the object.
4172 * Record associated magic type for later.
4174 GETMARK(extra_type);
4175 switch (extra_type) {
4181 sv = (SV *) newAV();
4185 sv = (SV *) newHV();
4189 return retrieve_other(aTHX_ cxt, 0); /* Let it croak */
4193 return retrieve_other(aTHX_ cxt, 0); /* Let it croak */
4195 SEEN0_NN(sv, 0); /* Don't bless yet */
4198 * Whilst flags tell us to recurse, do so.
4200 * We don't need to remember the addresses returned by retrieval, because
4201 * all the references will be obtained through indirection via the object
4202 * tags in the object-ID list.
4204 * We need to decrement the reference count for these objects
4205 * because, if the user doesn't save a reference to them in the hook,
4206 * they must be freed when this context is cleaned.
4209 while (flags & SHF_NEED_RECURSE) {
4210 TRACEME(("retrieve_hook recursing..."));
4211 rv = retrieve(aTHX_ cxt, 0);
4215 TRACEME(("retrieve_hook back with rv=0x%" UVxf,
4220 if (flags & SHF_IDX_CLASSNAME) {
4225 * Fetch index from 'aclass'
4228 if (flags & SHF_LARGE_CLASSLEN)
4233 sva = av_fetch(cxt->aclass, idx, FALSE);
4235 CROAK(("Class name #%" IVdf
4236 " should have been seen already", (IV) idx));
4238 classname = SvPVX(*sva); /* We know it's a PV, by construction */
4239 TRACEME(("class ID %d => %s", idx, classname));
4243 * Decode class name length and read that name.
4245 * NOTA BENE: even if the length is stored on one byte, we don't read
4246 * on the stack. Just like retrieve_blessed(), we limit the name to
4247 * LG_BLESS bytes. This is an arbitrary decision.
4249 char *malloced_classname = NULL;
4251 if (flags & SHF_LARGE_CLASSLEN)
4256 if (len > LG_BLESS) {
4257 TRACEME(("** allocating %d bytes for class name", len+1));
4258 New(10003, classname, len+1, char);
4259 malloced_classname = classname;
4262 SAFEPVREAD(classname, len, malloced_classname);
4263 classname[len] = '\0'; /* Mark string end */
4266 * Record new classname.
4269 if (!av_store(cxt->aclass, cxt->classnum++, newSVpvn(classname, len))) {
4270 Safefree(malloced_classname);
4275 TRACEME(("class name: %s", classname));
4278 * Decode user-frozen string length and read it in an SV.
4280 * For efficiency reasons, we read data directly into the SV buffer.
4281 * To understand that code, read retrieve_scalar()
4284 if (flags & SHF_LARGE_STRLEN)
4289 frozen = NEWSV(10002, len2);
4291 SAFEREAD(SvPVX(frozen), len2, frozen);
4292 SvCUR_set(frozen, len2);
4293 *SvEND(frozen) = '\0';
4295 (void) SvPOK_only(frozen); /* Validates string pointer */
4296 if (cxt->s_tainted) /* Is input source tainted? */
4299 TRACEME(("frozen string: %d bytes", len2));
4302 * Decode object-ID list length, if present.
4305 if (flags & SHF_HAS_LIST) {
4306 if (flags & SHF_LARGE_LISTLEN)
4312 av_extend(av, len3 + 1); /* Leave room for [0] */
4313 AvFILLp(av) = len3; /* About to be filled anyway */
4317 TRACEME(("has %d object IDs to link", len3));
4320 * Read object-ID list into array.
4321 * Because we pre-extended it, we can cheat and fill it manually.
4323 * We read object tags and we can convert them into SV* on the fly
4324 * because we know all the references listed in there (as tags)
4325 * have been already serialized, hence we have a valid correspondence
4326 * between each of those tags and the recreated SV.
4330 SV **ary = AvARRAY(av);
4332 for (i = 1; i <= len3; i++) { /* We leave [0] alone */
4339 svh = av_fetch(cxt->aseen, tag, FALSE);
4341 if (tag == cxt->where_is_undef) {
4342 /* av_fetch uses PL_sv_undef internally, hence this
4343 somewhat gruesome hack. */
4347 CROAK(("Object #%" IVdf
4348 " should have been retrieved already",
4353 ary[i] = SvREFCNT_inc(xsv);
4358 * Look up the STORABLE_attach hook
4360 stash = gv_stashpv(classname, GV_ADD);
4362 /* Handle attach case; again can't use pkg_can because it only
4363 * caches one method */
4364 attach = gv_fetchmethod_autoload(stash, "STORABLE_attach", FALSE);
4365 if (attach && isGV(attach)) {
4367 SV* attach_hook = newRV((SV*) GvCV(attach));
4370 CROAK(("STORABLE_attach called with unexpected references"));
4374 AvARRAY(av)[0] = SvREFCNT_inc(frozen);
4375 rv = newSVpv(classname, 0);
4376 attached = scalar_call(aTHX_ rv, attach_hook, clone, av, G_SCALAR);
4377 /* Free memory after a call */
4379 SvREFCNT_dec(frozen);
4382 SvREFCNT_dec(attach_hook);
4385 sv_derived_from(attached, classname)
4388 /* refcnt of unneeded sv is 2 at this point (one from newHV, second from SEEN call) */
4391 /* we need to free RV but preserve value that RV point to */
4392 sv = SvRV(attached);
4394 SvRV_set(attached, NULL);
4395 SvREFCNT_dec(attached);
4396 if (!(flags & SHF_IDX_CLASSNAME) && classname != buf)
4397 Safefree(classname);
4400 CROAK(("STORABLE_attach did not return a %s object", classname));
4404 * Bless the object and look up the STORABLE_thaw hook.
4409 hook = pkg_can(aTHX_ cxt->hook, stash, "STORABLE_thaw");
4412 * Hook not found. Maybe they did not require the module where this
4413 * hook is defined yet?
4415 * If the load below succeeds, we'll be able to find the hook.
4416 * Still, it only works reliably when each class is defined in a
4420 TRACEME(("No STORABLE_thaw defined for objects of class %s", classname));
4421 TRACEME(("Going to load module '%s'", classname));
4422 load_module(PERL_LOADMOD_NOIMPORT, newSVpv(classname, 0), Nullsv);
4425 * We cache results of pkg_can, so we need to uncache before attempting
4429 pkg_uncache(aTHX_ cxt->hook, SvSTASH(sv), "STORABLE_thaw");
4430 hook = pkg_can(aTHX_ cxt->hook, SvSTASH(sv), "STORABLE_thaw");
4433 CROAK(("No STORABLE_thaw defined for objects of class %s "
4434 "(even after a \"require %s;\")", classname, classname));
4438 * If we don't have an 'av' yet, prepare one.
4439 * Then insert the frozen string as item [0].
4447 AvARRAY(av)[0] = SvREFCNT_inc(frozen);
4452 * $object->STORABLE_thaw($cloning, $frozen, @refs);
4454 * where $object is our blessed (empty) object, $cloning is a boolean
4455 * telling whether we're running a deep clone, $frozen is the frozen
4456 * string the user gave us in his serializing hook, and @refs, which may
4457 * be empty, is the list of extra references he returned along for us
4460 * In effect, the hook is an alternate creation routine for the class,
4461 * the object itself being already created by the runtime.
4464 TRACEME(("calling STORABLE_thaw on %s at 0x%" UVxf " (%" IVdf " args)",
4465 classname, PTR2UV(sv), (IV) AvFILLp(av) + 1));
4468 (void) scalar_call(aTHX_ rv, hook, clone, av, G_SCALAR|G_DISCARD);
4475 SvREFCNT_dec(frozen);
4478 if (!(flags & SHF_IDX_CLASSNAME) && classname != buf)
4479 Safefree(classname);
4482 * If we had an <extra> type, then the object was not as simple, and
4483 * we need to restore extra magic now.
4489 TRACEME(("retrieving magic object for 0x%" UVxf "...", PTR2UV(sv)));
4491 rv = retrieve(aTHX_ cxt, 0); /* Retrieve <magic object> */
4493 TRACEME(("restoring the magic object 0x%" UVxf " part of 0x%" UVxf,
4494 PTR2UV(rv), PTR2UV(sv)));
4496 switch (extra_type) {
4498 sv_upgrade(sv, SVt_PVMG);
4501 sv_upgrade(sv, SVt_PVAV);
4502 AvREAL_off((AV *)sv);
4505 sv_upgrade(sv, SVt_PVHV);
4508 CROAK(("Forgot to deal with extra type %d", extra_type));
4513 * Adding the magic only now, well after the STORABLE_thaw hook was called
4514 * means the hook cannot know it deals with an object whose variable is
4515 * tied. But this is happening when retrieving $o in the following case:
4519 * my $o = bless \%h, 'BAR';
4521 * The 'BAR' class is NOT the one where %h is tied into. Therefore, as
4522 * far as the 'BAR' class is concerned, the fact that %h is not a REAL
4523 * hash but a tied one should not matter at all, and remain transparent.
4524 * This means the magic must be restored by Storable AFTER the hook is
4527 * That looks very reasonable to me, but then I've come up with this
4528 * after a bug report from David Nesting, who was trying to store such
4529 * an object and caused Storable to fail. And unfortunately, it was
4530 * also the easiest way to retrofit support for blessed ref to tied objects
4531 * into the existing design. -- RAM, 17/02/2001
4534 sv_magic(sv, rv, mtype, (char *)NULL, 0);
4535 SvREFCNT_dec(rv); /* Undo refcnt inc from sv_magic() */
4543 * Retrieve reference to some other scalar.
4544 * Layout is SX_REF <object>, with SX_REF already read.
4546 static SV *retrieve_ref(pTHX_ stcxt_t *cxt, const char *cname)
4552 TRACEME(("retrieve_ref (#%d)", cxt->tagnum));
4555 * We need to create the SV that holds the reference to the yet-to-retrieve
4556 * object now, so that we may record the address in the seen table.
4557 * Otherwise, if the object to retrieve references us, we won't be able
4558 * to resolve the SX_OBJECT we'll see at that point! Hence we cannot
4559 * do the retrieve first and use rv = newRV(sv) since it will be too late
4560 * for SEEN() recording.
4563 rv = NEWSV(10002, 0);
4565 stash = gv_stashpv(cname, GV_ADD);
4568 SEEN_NN(rv, stash, 0); /* Will return if rv is null */
4569 sv = retrieve(aTHX_ cxt, 0); /* Retrieve <object> */
4571 return (SV *) 0; /* Failed */
4574 * WARNING: breaks RV encapsulation.
4576 * Now for the tricky part. We have to upgrade our existing SV, so that
4577 * it is now an RV on sv... Again, we cheat by duplicating the code
4578 * held in newSVrv(), since we already got our SV from retrieve().
4582 * SvRV(rv) = SvREFCNT_inc(sv);
4584 * here because the reference count we got from retrieve() above is
4585 * already correct: if the object was retrieved from the file, then
4586 * its reference count is one. Otherwise, if it was retrieved via
4587 * an SX_OBJECT indication, a ref count increment was done.
4591 /* No need to do anything, as rv will already be PVMG. */
4592 assert (SvTYPE(rv) == SVt_RV || SvTYPE(rv) >= SVt_PV);
4594 sv_upgrade(rv, SVt_RV);
4597 SvRV_set(rv, sv); /* $rv = \$sv */
4600 TRACEME(("ok (retrieve_ref at 0x%" UVxf ")", PTR2UV(rv)));
4608 * Retrieve weak reference to some other scalar.
4609 * Layout is SX_WEAKREF <object>, with SX_WEAKREF already read.
4611 static SV *retrieve_weakref(pTHX_ stcxt_t *cxt, const char *cname)
4615 TRACEME(("retrieve_weakref (#%d)", cxt->tagnum));
4617 sv = retrieve_ref(aTHX_ cxt, cname);
4629 * retrieve_overloaded
4631 * Retrieve reference to some other scalar with overloading.
4632 * Layout is SX_OVERLOAD <object>, with SX_OVERLOAD already read.
4634 static SV *retrieve_overloaded(pTHX_ stcxt_t *cxt, const char *cname)
4640 TRACEME(("retrieve_overloaded (#%d)", cxt->tagnum));
4643 * Same code as retrieve_ref(), duplicated to avoid extra call.
4646 rv = NEWSV(10002, 0);
4647 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
4648 SEEN_NN(rv, stash, 0); /* Will return if rv is null */
4649 cxt->in_retrieve_overloaded = 1; /* so sv_bless doesn't call S_reset_amagic */
4650 sv = retrieve(aTHX_ cxt, 0); /* Retrieve <object> */
4651 cxt->in_retrieve_overloaded = 0;
4653 return (SV *) 0; /* Failed */
4656 * WARNING: breaks RV encapsulation.
4659 SvUPGRADE(rv, SVt_RV);
4660 SvRV_set(rv, sv); /* $rv = \$sv */
4664 * Restore overloading magic.
4667 stash = SvTYPE(sv) ? (HV *) SvSTASH (sv) : 0;
4669 CROAK(("Cannot restore overloading on %s(0x%" UVxf
4670 ") (package <unknown>)",
4671 sv_reftype(sv, FALSE),
4674 if (!Gv_AMG(stash)) {
4675 const char *package = HvNAME_get(stash);
4676 TRACEME(("No overloading defined for package %s", package));
4677 TRACEME(("Going to load module '%s'", package));
4678 load_module(PERL_LOADMOD_NOIMPORT, newSVpv(package, 0), Nullsv);
4679 if (!Gv_AMG(stash)) {
4680 CROAK(("Cannot restore overloading on %s(0x%" UVxf
4681 ") (package %s) (even after a \"require %s;\")",
4682 sv_reftype(sv, FALSE),
4690 TRACEME(("ok (retrieve_overloaded at 0x%" UVxf ")", PTR2UV(rv)));
4696 * retrieve_weakoverloaded
4698 * Retrieve weak overloaded reference to some other scalar.
4699 * Layout is SX_WEAKOVERLOADED <object>, with SX_WEAKOVERLOADED already read.
4701 static SV *retrieve_weakoverloaded(pTHX_ stcxt_t *cxt, const char *cname)
4705 TRACEME(("retrieve_weakoverloaded (#%d)", cxt->tagnum));
4707 sv = retrieve_overloaded(aTHX_ cxt, cname);
4719 * retrieve_tied_array
4721 * Retrieve tied array
4722 * Layout is SX_TIED_ARRAY <object>, with SX_TIED_ARRAY already read.
4724 static SV *retrieve_tied_array(pTHX_ stcxt_t *cxt, const char *cname)
4730 TRACEME(("retrieve_tied_array (#%d)", cxt->tagnum));
4732 tv = NEWSV(10002, 0);
4733 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
4734 SEEN_NN(tv, stash, 0); /* Will return if tv is null */
4735 sv = retrieve(aTHX_ cxt, 0); /* Retrieve <object> */
4737 return (SV *) 0; /* Failed */
4739 sv_upgrade(tv, SVt_PVAV);
4740 AvREAL_off((AV *)tv);
4741 sv_magic(tv, sv, 'P', (char *)NULL, 0);
4742 SvREFCNT_dec(sv); /* Undo refcnt inc from sv_magic() */
4744 TRACEME(("ok (retrieve_tied_array at 0x%" UVxf ")", PTR2UV(tv)));
4750 * retrieve_tied_hash
4752 * Retrieve tied hash
4753 * Layout is SX_TIED_HASH <object>, with SX_TIED_HASH already read.
4755 static SV *retrieve_tied_hash(pTHX_ stcxt_t *cxt, const char *cname)
4761 TRACEME(("retrieve_tied_hash (#%d)", cxt->tagnum));
4763 tv = NEWSV(10002, 0);
4764 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
4765 SEEN_NN(tv, stash, 0); /* Will return if tv is null */
4766 sv = retrieve(aTHX_ cxt, 0); /* Retrieve <object> */
4768 return (SV *) 0; /* Failed */
4770 sv_upgrade(tv, SVt_PVHV);
4771 sv_magic(tv, sv, 'P', (char *)NULL, 0);
4772 SvREFCNT_dec(sv); /* Undo refcnt inc from sv_magic() */
4774 TRACEME(("ok (retrieve_tied_hash at 0x%" UVxf ")", PTR2UV(tv)));
4780 * retrieve_tied_scalar
4782 * Retrieve tied scalar
4783 * Layout is SX_TIED_SCALAR <object>, with SX_TIED_SCALAR already read.
4785 static SV *retrieve_tied_scalar(pTHX_ stcxt_t *cxt, const char *cname)
4788 SV *sv, *obj = NULL;
4791 TRACEME(("retrieve_tied_scalar (#%d)", cxt->tagnum));
4793 tv = NEWSV(10002, 0);
4794 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
4795 SEEN_NN(tv, stash, 0); /* Will return if rv is null */
4796 sv = retrieve(aTHX_ cxt, 0); /* Retrieve <object> */
4798 return (SV *) 0; /* Failed */
4800 else if (SvTYPE(sv) != SVt_NULL) {
4804 sv_upgrade(tv, SVt_PVMG);
4805 sv_magic(tv, obj, 'q', (char *)NULL, 0);
4808 /* Undo refcnt inc from sv_magic() */
4812 TRACEME(("ok (retrieve_tied_scalar at 0x%" UVxf ")", PTR2UV(tv)));
4820 * Retrieve reference to value in a tied hash.
4821 * Layout is SX_TIED_KEY <object> <key>, with SX_TIED_KEY already read.
4823 static SV *retrieve_tied_key(pTHX_ stcxt_t *cxt, const char *cname)
4830 TRACEME(("retrieve_tied_key (#%d)", cxt->tagnum));
4832 tv = NEWSV(10002, 0);
4833 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
4834 SEEN_NN(tv, stash, 0); /* Will return if tv is null */
4835 sv = retrieve(aTHX_ cxt, 0); /* Retrieve <object> */
4837 return (SV *) 0; /* Failed */
4839 key = retrieve(aTHX_ cxt, 0); /* Retrieve <key> */
4841 return (SV *) 0; /* Failed */
4843 sv_upgrade(tv, SVt_PVMG);
4844 sv_magic(tv, sv, 'p', (char *)key, HEf_SVKEY);
4845 SvREFCNT_dec(key); /* Undo refcnt inc from sv_magic() */
4846 SvREFCNT_dec(sv); /* Undo refcnt inc from sv_magic() */
4854 * Retrieve reference to value in a tied array.
4855 * Layout is SX_TIED_IDX <object> <idx>, with SX_TIED_IDX already read.
4857 static SV *retrieve_tied_idx(pTHX_ stcxt_t *cxt, const char *cname)
4864 TRACEME(("retrieve_tied_idx (#%d)", cxt->tagnum));
4866 tv = NEWSV(10002, 0);
4867 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
4868 SEEN_NN(tv, stash, 0); /* Will return if tv is null */
4869 sv = retrieve(aTHX_ cxt, 0); /* Retrieve <object> */
4871 return (SV *) 0; /* Failed */
4873 RLEN(idx); /* Retrieve <idx> */
4875 sv_upgrade(tv, SVt_PVMG);
4876 sv_magic(tv, sv, 'p', (char *)NULL, idx);
4877 SvREFCNT_dec(sv); /* Undo refcnt inc from sv_magic() */
4886 * Retrieve defined long (string) scalar.
4888 * Layout is SX_LSCALAR <length> <data>, with SX_LSCALAR already read.
4889 * The scalar is "long" in that <length> is larger than LG_SCALAR so it
4890 * was not stored on a single byte.
4892 static SV *retrieve_lscalar(pTHX_ stcxt_t *cxt, const char *cname)
4899 TRACEME(("retrieve_lscalar (#%d), len = %" IVdf, cxt->tagnum, (IV) len));
4902 * Allocate an empty scalar of the suitable length.
4905 sv = NEWSV(10002, len);
4906 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
4907 SEEN_NN(sv, stash, 0); /* Associate this new scalar with tag "tagnum" */
4915 * WARNING: duplicates parts of sv_setpv and breaks SV data encapsulation.
4917 * Now, for efficiency reasons, read data directly inside the SV buffer,
4918 * and perform the SV final settings directly by duplicating the final
4919 * work done by sv_setpv. Since we're going to allocate lots of scalars
4920 * this way, it's worth the hassle and risk.
4923 SAFEREAD(SvPVX(sv), len, sv);
4924 SvCUR_set(sv, len); /* Record C string length */
4925 *SvEND(sv) = '\0'; /* Ensure it's null terminated anyway */
4926 (void) SvPOK_only(sv); /* Validate string pointer */
4927 if (cxt->s_tainted) /* Is input source tainted? */
4928 SvTAINT(sv); /* External data cannot be trusted */
4930 TRACEME(("large scalar len %" IVdf " '%s'", (IV) len, SvPVX(sv)));
4931 TRACEME(("ok (retrieve_lscalar at 0x%" UVxf ")", PTR2UV(sv)));
4939 * Retrieve defined short (string) scalar.
4941 * Layout is SX_SCALAR <length> <data>, with SX_SCALAR already read.
4942 * The scalar is "short" so <length> is single byte. If it is 0, there
4943 * is no <data> section.
4945 static SV *retrieve_scalar(pTHX_ stcxt_t *cxt, const char *cname)
4952 TRACEME(("retrieve_scalar (#%d), len = %d", cxt->tagnum, len));
4955 * Allocate an empty scalar of the suitable length.
4958 sv = NEWSV(10002, len);
4959 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
4960 SEEN_NN(sv, stash, 0); /* Associate this new scalar with tag "tagnum" */
4963 * WARNING: duplicates parts of sv_setpv and breaks SV data encapsulation.
4968 * newSV did not upgrade to SVt_PV so the scalar is undefined.
4969 * To make it defined with an empty length, upgrade it now...
4970 * Don't upgrade to a PV if the original type contains more
4971 * information than a scalar.
4973 if (SvTYPE(sv) <= SVt_PV) {
4974 sv_upgrade(sv, SVt_PV);
4977 *SvEND(sv) = '\0'; /* Ensure it's null terminated anyway */
4978 TRACEME(("ok (retrieve_scalar empty at 0x%" UVxf ")", PTR2UV(sv)));
4981 * Now, for efficiency reasons, read data directly inside the SV buffer,
4982 * and perform the SV final settings directly by duplicating the final
4983 * work done by sv_setpv. Since we're going to allocate lots of scalars
4984 * this way, it's worth the hassle and risk.
4986 SAFEREAD(SvPVX(sv), len, sv);
4987 SvCUR_set(sv, len); /* Record C string length */
4988 *SvEND(sv) = '\0'; /* Ensure it's null terminated anyway */
4989 TRACEME(("small scalar len %d '%s'", len, SvPVX(sv)));
4992 (void) SvPOK_only(sv); /* Validate string pointer */
4993 if (cxt->s_tainted) /* Is input source tainted? */
4994 SvTAINT(sv); /* External data cannot be trusted */
4996 TRACEME(("ok (retrieve_scalar at 0x%" UVxf ")", PTR2UV(sv)));
5003 * Like retrieve_scalar(), but tag result as utf8.
5004 * If we're retrieving UTF8 data in a non-UTF8 perl, croaks.
5006 static SV *retrieve_utf8str(pTHX_ stcxt_t *cxt, const char *cname)
5010 TRACEME(("retrieve_utf8str"));
5012 sv = retrieve_scalar(aTHX_ cxt, cname);
5014 #ifdef HAS_UTF8_SCALARS
5017 if (cxt->use_bytes < 0)
5019 = (SvTRUE(perl_get_sv("Storable::drop_utf8", GV_ADD))
5021 if (cxt->use_bytes == 0)
5032 * Like retrieve_lscalar(), but tag result as utf8.
5033 * If we're retrieving UTF8 data in a non-UTF8 perl, croaks.
5035 static SV *retrieve_lutf8str(pTHX_ stcxt_t *cxt, const char *cname)
5039 TRACEME(("retrieve_lutf8str"));
5041 sv = retrieve_lscalar(aTHX_ cxt, cname);
5043 #ifdef HAS_UTF8_SCALARS
5046 if (cxt->use_bytes < 0)
5048 = (SvTRUE(perl_get_sv("Storable::drop_utf8", GV_ADD))
5050 if (cxt->use_bytes == 0)
5060 * Retrieve a vstring, and then retrieve the stringy scalar following it,
5061 * attaching the vstring to the scalar via magic.
5062 * If we're retrieving a vstring in a perl without vstring magic, croaks.
5064 * The vstring layout mirrors an SX_SCALAR string:
5065 * SX_VSTRING <length> <data> with SX_VSTRING already read.
5067 static SV *retrieve_vstring(pTHX_ stcxt_t *cxt, const char *cname)
5075 TRACEME(("retrieve_vstring (#%d), len = %d", cxt->tagnum, len));
5079 sv = retrieve(aTHX_ cxt, cname);
5081 sv_magic(sv,NULL,PERL_MAGIC_vstring,s,len);
5082 /* 5.10.0 and earlier seem to need this */
5085 TRACEME(("ok (retrieve_vstring at 0x%" UVxf ")", PTR2UV(sv)));
5096 * Like retrieve_vstring, but for longer vstrings.
5098 static SV *retrieve_lvstring(pTHX_ stcxt_t *cxt, const char *cname)
5106 TRACEME(("retrieve_lvstring (#%d), len = %" IVdf,
5107 cxt->tagnum, (IV)len));
5109 New(10003, s, len+1, char);
5110 SAFEPVREAD(s, len, s);
5112 sv = retrieve(aTHX_ cxt, cname);
5114 sv_magic(sv,NULL,PERL_MAGIC_vstring,s,len);
5115 /* 5.10.0 and earlier seem to need this */
5120 TRACEME(("ok (retrieve_lvstring at 0x%" UVxf ")", PTR2UV(sv)));
5131 * Retrieve defined integer.
5132 * Layout is SX_INTEGER <data>, whith SX_INTEGER already read.
5134 static SV *retrieve_integer(pTHX_ stcxt_t *cxt, const char *cname)
5140 TRACEME(("retrieve_integer (#%d)", cxt->tagnum));
5142 READ(&iv, sizeof(iv));
5144 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5145 SEEN_NN(sv, stash, 0); /* Associate this new scalar with tag "tagnum" */
5147 TRACEME(("integer %" IVdf, iv));
5148 TRACEME(("ok (retrieve_integer at 0x%" UVxf ")", PTR2UV(sv)));
5156 * Retrieve defined integer in network order.
5157 * Layout is SX_NETINT <data>, whith SX_NETINT already read.
5159 static SV *retrieve_netint(pTHX_ stcxt_t *cxt, const char *cname)
5165 TRACEME(("retrieve_netint (#%d)", cxt->tagnum));
5169 sv = newSViv((int) ntohl(iv));
5170 TRACEME(("network integer %d", (int) ntohl(iv)));
5173 TRACEME(("network integer (as-is) %d", iv));
5175 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5176 SEEN_NN(sv, stash, 0); /* Associate this new scalar with tag "tagnum" */
5178 TRACEME(("ok (retrieve_netint at 0x%" UVxf ")", PTR2UV(sv)));
5186 * Retrieve defined double.
5187 * Layout is SX_DOUBLE <data>, whith SX_DOUBLE already read.
5189 static SV *retrieve_double(pTHX_ stcxt_t *cxt, const char *cname)
5195 TRACEME(("retrieve_double (#%d)", cxt->tagnum));
5197 READ(&nv, sizeof(nv));
5199 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5200 SEEN_NN(sv, stash, 0); /* Associate this new scalar with tag "tagnum" */
5202 TRACEME(("double %" NVff, nv));
5203 TRACEME(("ok (retrieve_double at 0x%" UVxf ")", PTR2UV(sv)));
5211 * Retrieve defined byte (small integer within the [-128, +127] range).
5212 * Layout is SX_BYTE <data>, whith SX_BYTE already read.
5214 static SV *retrieve_byte(pTHX_ stcxt_t *cxt, const char *cname)
5219 signed char tmp; /* Workaround for AIX cc bug --H.Merijn Brand */
5221 TRACEME(("retrieve_byte (#%d)", cxt->tagnum));
5224 TRACEME(("small integer read as %d", (unsigned char) siv));
5225 tmp = (unsigned char) siv - 128;
5227 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5228 SEEN_NN(sv, stash, 0); /* Associate this new scalar with tag "tagnum" */
5230 TRACEME(("byte %d", tmp));
5231 TRACEME(("ok (retrieve_byte at 0x%" UVxf ")", PTR2UV(sv)));
5239 * Return the undefined value.
5241 static SV *retrieve_undef(pTHX_ stcxt_t *cxt, const char *cname)
5246 TRACEME(("retrieve_undef"));
5249 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5250 SEEN_NN(sv, stash, 0);
5258 * Return the immortal undefined value.
5260 static SV *retrieve_sv_undef(pTHX_ stcxt_t *cxt, const char *cname)
5262 SV *sv = &PL_sv_undef;
5265 TRACEME(("retrieve_sv_undef"));
5267 /* Special case PL_sv_undef, as av_fetch uses it internally to mark
5268 deleted elements, and will return NULL (fetch failed) whenever it
5270 if (cxt->where_is_undef == -1) {
5271 cxt->where_is_undef = cxt->tagnum;
5273 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5274 SEEN_NN(sv, stash, 1);
5281 * Return the immortal yes value.
5283 static SV *retrieve_sv_yes(pTHX_ stcxt_t *cxt, const char *cname)
5285 SV *sv = &PL_sv_yes;
5288 TRACEME(("retrieve_sv_yes"));
5290 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5291 SEEN_NN(sv, stash, 1);
5298 * Return the immortal no value.
5300 static SV *retrieve_sv_no(pTHX_ stcxt_t *cxt, const char *cname)
5305 TRACEME(("retrieve_sv_no"));
5307 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5308 SEEN_NN(sv, stash, 1);
5313 * retrieve_svundef_elem
5315 * Return &PL_sv_placeholder, representing &PL_sv_undef in an array. This
5316 * is a bit of a hack, but we already use SX_SV_UNDEF to mean a nonexistent
5317 * element, for historical reasons.
5319 static SV *retrieve_svundef_elem(pTHX_ stcxt_t *cxt, const char *cname)
5321 TRACEME(("retrieve_svundef_elem"));
5323 /* SEEN reads the contents of its SV argument, which we are not
5324 supposed to do with &PL_sv_placeholder. */
5325 SEEN_NN(&PL_sv_undef, cname, 1);
5327 return &PL_sv_placeholder;
5333 * Retrieve a whole array.
5334 * Layout is SX_ARRAY <size> followed by each item, in increasing index order.
5335 * Each item is stored as <object>.
5337 * When we come here, SX_ARRAY has been read already.
5339 static SV *retrieve_array(pTHX_ stcxt_t *cxt, const char *cname)
5346 bool seen_null = FALSE;
5348 TRACEME(("retrieve_array (#%d)", cxt->tagnum));
5351 * Read length, and allocate array, then pre-extend it.
5355 TRACEME(("size = %d", len));
5357 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5358 SEEN_NN(av, stash, 0); /* Will return if array not allocated nicely */
5362 return (SV *) av; /* No data follow if array is empty */
5365 * Now get each item in turn...
5368 for (i = 0; i < len; i++) {
5369 TRACEME(("(#%d) item", i));
5370 sv = retrieve(aTHX_ cxt, 0); /* Retrieve item */
5373 if (sv == &PL_sv_undef) {
5377 if (sv == &PL_sv_placeholder)
5379 if (av_store(av, i, sv) == 0)
5382 if (seen_null) av_fill(av, len-1);
5384 TRACEME(("ok (retrieve_array at 0x%" UVxf ")", PTR2UV(av)));
5392 * Retrieve a whole hash table.
5393 * Layout is SX_HASH <size> followed by each key/value pair, in random order.
5394 * Keys are stored as <length> <data>, the <data> section being omitted
5396 * Values are stored as <object>.
5398 * When we come here, SX_HASH has been read already.
5400 static SV *retrieve_hash(pTHX_ stcxt_t *cxt, const char *cname)
5409 TRACEME(("retrieve_hash (#%d)", cxt->tagnum));
5412 * Read length, allocate table.
5416 TRACEME(("size = %d", len));
5418 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5419 SEEN_NN(hv, stash, 0); /* Will return if table not allocated properly */
5421 return (SV *) hv; /* No data follow if table empty */
5422 hv_ksplit(hv, len + 1); /* pre-extend hash to save multiple splits */
5425 * Now get each key/value pair in turn...
5428 for (i = 0; i < len; i++) {
5433 TRACEME(("(#%d) value", i));
5434 sv = retrieve(aTHX_ cxt, 0);
5440 * Since we're reading into kbuf, we must ensure we're not
5441 * recursing between the read and the hv_store() where it's used.
5442 * Hence the key comes after the value.
5445 RLEN(size); /* Get key size */
5446 KBUFCHK((STRLEN)size); /* Grow hash key read pool if needed */
5449 kbuf[size] = '\0'; /* Mark string end, just in case */
5450 TRACEME(("(#%d) key '%s'", i, kbuf));
5453 * Enter key/value pair into hash table.
5456 if (hv_store(hv, kbuf, (U32) size, sv, 0) == 0)
5460 TRACEME(("ok (retrieve_hash at 0x%" UVxf ")", PTR2UV(hv)));
5468 * Retrieve a whole hash table.
5469 * Layout is SX_HASH <size> followed by each key/value pair, in random order.
5470 * Keys are stored as <length> <data>, the <data> section being omitted
5472 * Values are stored as <object>.
5474 * When we come here, SX_HASH has been read already.
5476 static SV *retrieve_flag_hash(pTHX_ stcxt_t *cxt, const char *cname)
5487 GETMARK(hash_flags);
5488 TRACEME(("retrieve_flag_hash (#%d)", cxt->tagnum));
5490 * Read length, allocate table.
5493 #ifndef HAS_RESTRICTED_HASHES
5494 if (hash_flags & SHV_RESTRICTED) {
5495 if (cxt->derestrict < 0)
5497 = (SvTRUE(perl_get_sv("Storable::downgrade_restricted", GV_ADD))
5499 if (cxt->derestrict == 0)
5500 RESTRICTED_HASH_CROAK();
5505 TRACEME(("size = %d, flags = %d", len, hash_flags));
5507 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5508 SEEN_NN(hv, stash, 0); /* Will return if table not allocated properly */
5510 return (SV *) hv; /* No data follow if table empty */
5511 hv_ksplit(hv, len + 1); /* pre-extend hash to save multiple splits */
5514 * Now get each key/value pair in turn...
5517 for (i = 0; i < len; i++) {
5519 int store_flags = 0;
5524 TRACEME(("(#%d) value", i));
5525 sv = retrieve(aTHX_ cxt, 0);
5530 #ifdef HAS_RESTRICTED_HASHES
5531 if ((hash_flags & SHV_RESTRICTED) && (flags & SHV_K_LOCKED))
5535 if (flags & SHV_K_ISSV) {
5536 /* XXX you can't set a placeholder with an SV key.
5537 Then again, you can't get an SV key.
5538 Without messing around beyond what the API is supposed to do.
5541 TRACEME(("(#%d) keysv, flags=%d", i, flags));
5542 keysv = retrieve(aTHX_ cxt, 0);
5546 if (!hv_store_ent(hv, keysv, sv, 0))
5551 * Since we're reading into kbuf, we must ensure we're not
5552 * recursing between the read and the hv_store() where it's used.
5553 * Hence the key comes after the value.
5556 if (flags & SHV_K_PLACEHOLDER) {
5558 sv = &PL_sv_placeholder;
5559 store_flags |= HVhek_PLACEHOLD;
5561 if (flags & SHV_K_UTF8) {
5562 #ifdef HAS_UTF8_HASHES
5563 store_flags |= HVhek_UTF8;
5565 if (cxt->use_bytes < 0)
5567 = (SvTRUE(perl_get_sv("Storable::drop_utf8", GV_ADD))
5569 if (cxt->use_bytes == 0)
5573 #ifdef HAS_UTF8_HASHES
5574 if (flags & SHV_K_WASUTF8)
5575 store_flags |= HVhek_WASUTF8;
5578 RLEN(size); /* Get key size */
5579 KBUFCHK((STRLEN)size); /* Grow hash key read pool if needed */
5582 kbuf[size] = '\0'; /* Mark string end, just in case */
5583 TRACEME(("(#%d) key '%s' flags %X store_flags %X", i, kbuf,
5584 flags, store_flags));
5587 * Enter key/value pair into hash table.
5590 #ifdef HAS_RESTRICTED_HASHES
5591 if (hv_store_flags(hv, kbuf, size, sv, 0, store_flags) == 0)
5594 if (!(store_flags & HVhek_PLACEHOLD))
5595 if (hv_store(hv, kbuf, size, sv, 0) == 0)
5600 #ifdef HAS_RESTRICTED_HASHES
5601 if (hash_flags & SHV_RESTRICTED)
5605 TRACEME(("ok (retrieve_hash at 0x%" UVxf ")", PTR2UV(hv)));
5613 * Return a code reference.
5615 static SV *retrieve_code(pTHX_ stcxt_t *cxt, const char *cname)
5617 #if PERL_VERSION < 6
5618 CROAK(("retrieve_code does not work with perl 5.005 or less\n"));
5621 int type, count, tagnum;
5623 SV *sv, *text, *sub, *errsv;
5626 TRACEME(("retrieve_code (#%d)", cxt->tagnum));
5629 * Insert dummy SV in the aseen array so that we don't screw
5630 * up the tag numbers. We would just make the internal
5631 * scalar an untagged item in the stream, but
5632 * retrieve_scalar() calls SEEN(). So we just increase the
5635 tagnum = cxt->tagnum;
5637 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5638 SEEN_NN(sv, stash, 0);
5641 * Retrieve the source of the code reference
5642 * as a small or large scalar
5648 text = retrieve_scalar(aTHX_ cxt, cname);
5651 text = retrieve_lscalar(aTHX_ cxt, cname);
5654 text = retrieve_utf8str(aTHX_ cxt, cname);
5657 text = retrieve_lutf8str(aTHX_ cxt, cname);
5660 CROAK(("Unexpected type %d in retrieve_code\n", type));
5664 CROAK(("Unable to retrieve code\n"));
5668 * prepend "sub " to the source
5671 sub = newSVpvs("sub ");
5674 sv_catpv(sub, SvPV_nolen(text)); /* XXX no sv_catsv! */
5678 * evaluate the source to a code reference and use the CV value
5681 if (cxt->eval == NULL) {
5682 cxt->eval = perl_get_sv("Storable::Eval", GV_ADD);
5683 SvREFCNT_inc(cxt->eval);
5685 if (!SvTRUE(cxt->eval)) {
5687 cxt->forgive_me == 0 ||
5688 (cxt->forgive_me < 0 && !(cxt->forgive_me =
5689 SvTRUE(perl_get_sv("Storable::forgive_me", GV_ADD)) ? 1 : 0))
5691 CROAK(("Can't eval, please set $Storable::Eval to a true value"));
5694 /* fix up the dummy entry... */
5695 av_store(cxt->aseen, tagnum, SvREFCNT_inc(sv));
5703 errsv = get_sv("@", GV_ADD);
5704 SvPVCLEAR(errsv); /* clear $@ */
5705 if (SvROK(cxt->eval) && SvTYPE(SvRV(cxt->eval)) == SVt_PVCV) {
5707 XPUSHs(sv_2mortal(newSVsv(sub)));
5709 count = call_sv(cxt->eval, G_SCALAR);
5711 CROAK(("Unexpected return value from $Storable::Eval callback\n"));
5713 eval_sv(sub, G_SCALAR);
5719 if (SvTRUE(errsv)) {
5720 CROAK(("code %s caused an error: %s",
5721 SvPV_nolen(sub), SvPV_nolen(errsv)));
5724 if (cv && SvROK(cv) && SvTYPE(SvRV(cv)) == SVt_PVCV) {
5727 CROAK(("code %s did not evaluate to a subroutine reference\n", SvPV_nolen(sub)));
5730 SvREFCNT_inc(sv); /* XXX seems to be necessary */
5735 /* fix up the dummy entry... */
5736 av_store(cxt->aseen, tagnum, SvREFCNT_inc(sv));
5743 * old_retrieve_array
5745 * Retrieve a whole array in pre-0.6 binary format.
5747 * Layout is SX_ARRAY <size> followed by each item, in increasing index order.
5748 * Each item is stored as SX_ITEM <object> or SX_IT_UNDEF for "holes".
5750 * When we come here, SX_ARRAY has been read already.
5752 static SV *old_retrieve_array(pTHX_ stcxt_t *cxt, const char *cname)
5760 PERL_UNUSED_ARG(cname);
5761 TRACEME(("old_retrieve_array (#%d)", cxt->tagnum));
5764 * Read length, and allocate array, then pre-extend it.
5768 TRACEME(("size = %d", len));
5770 SEEN0_NN(av, 0); /* Will return if array not allocated nicely */
5774 return (SV *) av; /* No data follow if array is empty */
5777 * Now get each item in turn...
5780 for (i = 0; i < len; i++) {
5782 if (c == SX_IT_UNDEF) {
5783 TRACEME(("(#%d) undef item", i));
5784 continue; /* av_extend() already filled us with undef */
5787 (void) retrieve_other(aTHX_ cxt, 0); /* Will croak out */
5788 TRACEME(("(#%d) item", i));
5789 sv = retrieve(aTHX_ cxt, 0); /* Retrieve item */
5792 if (av_store(av, i, sv) == 0)
5796 TRACEME(("ok (old_retrieve_array at 0x%" UVxf ")", PTR2UV(av)));
5804 * Retrieve a whole hash table in pre-0.6 binary format.
5806 * Layout is SX_HASH <size> followed by each key/value pair, in random order.
5807 * Keys are stored as SX_KEY <length> <data>, the <data> section being omitted
5809 * Values are stored as SX_VALUE <object> or SX_VL_UNDEF for "holes".
5811 * When we come here, SX_HASH has been read already.
5813 static SV *old_retrieve_hash(pTHX_ stcxt_t *cxt, const char *cname)
5821 SV *sv_h_undef = (SV *) 0; /* hv_store() bug */
5823 PERL_UNUSED_ARG(cname);
5824 TRACEME(("old_retrieve_hash (#%d)", cxt->tagnum));
5827 * Read length, allocate table.
5831 TRACEME(("size = %d", len));
5833 SEEN0_NN(hv, 0); /* Will return if table not allocated properly */
5835 return (SV *) hv; /* No data follow if table empty */
5836 hv_ksplit(hv, len + 1); /* pre-extend hash to save multiple splits */
5839 * Now get each key/value pair in turn...
5842 for (i = 0; i < len; i++) {
5848 if (c == SX_VL_UNDEF) {
5849 TRACEME(("(#%d) undef value", i));
5851 * Due to a bug in hv_store(), it's not possible to pass
5852 * &PL_sv_undef to hv_store() as a value, otherwise the
5853 * associated key will not be creatable any more. -- RAM, 14/01/97
5856 sv_h_undef = newSVsv(&PL_sv_undef);
5857 sv = SvREFCNT_inc(sv_h_undef);
5858 } else if (c == SX_VALUE) {
5859 TRACEME(("(#%d) value", i));
5860 sv = retrieve(aTHX_ cxt, 0);
5864 (void) retrieve_other(aTHX_ cxt, 0); /* Will croak out */
5868 * Since we're reading into kbuf, we must ensure we're not
5869 * recursing between the read and the hv_store() where it's used.
5870 * Hence the key comes after the value.
5875 (void) retrieve_other(aTHX_ cxt, 0); /* Will croak out */
5876 RLEN(size); /* Get key size */
5877 KBUFCHK((STRLEN)size); /* Grow hash key read pool if needed */
5880 kbuf[size] = '\0'; /* Mark string end, just in case */
5881 TRACEME(("(#%d) key '%s'", i, kbuf));
5884 * Enter key/value pair into hash table.
5887 if (hv_store(hv, kbuf, (U32) size, sv, 0) == 0)
5891 TRACEME(("ok (retrieve_hash at 0x%" UVxf ")", PTR2UV(hv)));
5897 *** Retrieval engine.
5903 * Make sure the stored data we're trying to retrieve has been produced
5904 * on an ILP compatible system with the same byteorder. It croaks out in
5905 * case an error is detected. [ILP = integer-long-pointer sizes]
5906 * Returns null if error is detected, &PL_sv_undef otherwise.
5908 * Note that there's no byte ordering info emitted when network order was
5909 * used at store time.
5911 static SV *magic_check(pTHX_ stcxt_t *cxt)
5913 /* The worst case for a malicious header would be old magic (which is
5914 longer), major, minor, byteorder length byte of 255, 255 bytes of
5915 garbage, sizeof int, long, pointer, NV.
5916 So the worse of that we can read is 255 bytes of garbage plus 4.
5917 Err, I am assuming 8 bit bytes here. Please file a bug report if you're
5918 compiling perl on a system with chars that are larger than 8 bits.
5919 (Even Crays aren't *that* perverse).
5921 unsigned char buf[4 + 255];
5922 unsigned char *current;
5925 int use_network_order;
5929 int version_minor = 0;
5931 TRACEME(("magic_check"));
5934 * The "magic number" is only for files, not when freezing in memory.
5938 /* This includes the '\0' at the end. I want to read the extra byte,
5939 which is usually going to be the major version number. */
5940 STRLEN len = sizeof(magicstr);
5943 READ(buf, (SSize_t)(len)); /* Not null-terminated */
5945 /* Point at the byte after the byte we read. */
5946 current = buf + --len; /* Do the -- outside of macros. */
5948 if (memNE(buf, magicstr, len)) {
5950 * Try to read more bytes to check for the old magic number, which
5954 TRACEME(("trying for old magic number"));
5956 old_len = sizeof(old_magicstr) - 1;
5957 READ(current + 1, (SSize_t)(old_len - len));
5959 if (memNE(buf, old_magicstr, old_len))
5960 CROAK(("File is not a perl storable"));
5962 current = buf + old_len;
5964 use_network_order = *current;
5966 GETMARK(use_network_order);
5969 * Starting with 0.6, the "use_network_order" byte flag is also used to
5970 * indicate the version number of the binary, and therefore governs the
5971 * setting of sv_retrieve_vtbl. See magic_write().
5973 if (old_magic && use_network_order > 1) {
5974 /* 0.1 dump - use_network_order is really byte order length */
5978 version_major = use_network_order >> 1;
5980 cxt->retrieve_vtbl = (SV*(**)(pTHX_ stcxt_t *cxt, const char *cname)) (version_major > 0 ? sv_retrieve : sv_old_retrieve);
5982 TRACEME(("magic_check: netorder = 0x%x", use_network_order));
5986 * Starting with 0.7 (binary major 2), a full byte is dedicated to the
5987 * minor version of the protocol. See magic_write().
5990 if (version_major > 1)
5991 GETMARK(version_minor);
5993 cxt->ver_major = version_major;
5994 cxt->ver_minor = version_minor;
5996 TRACEME(("binary image version is %d.%d", version_major, version_minor));
5999 * Inter-operability sanity check: we can't retrieve something stored
6000 * using a format more recent than ours, because we have no way to
6001 * know what has changed, and letting retrieval go would mean a probable
6002 * failure reporting a "corrupted" storable file.
6006 version_major > STORABLE_BIN_MAJOR ||
6007 (version_major == STORABLE_BIN_MAJOR &&
6008 version_minor > STORABLE_BIN_MINOR)
6011 TRACEME(("but I am version is %d.%d", STORABLE_BIN_MAJOR,
6012 STORABLE_BIN_MINOR));
6014 if (version_major == STORABLE_BIN_MAJOR) {
6015 TRACEME(("cxt->accept_future_minor is %d",
6016 cxt->accept_future_minor));
6017 if (cxt->accept_future_minor < 0)
6018 cxt->accept_future_minor
6019 = (SvTRUE(perl_get_sv("Storable::accept_future_minor",
6022 if (cxt->accept_future_minor == 1)
6023 croak_now = 0; /* Don't croak yet. */
6026 CROAK(("Storable binary image v%d.%d more recent than I am (v%d.%d)",
6027 version_major, version_minor,
6028 STORABLE_BIN_MAJOR, STORABLE_BIN_MINOR));
6033 * If they stored using network order, there's no byte ordering
6034 * information to check.
6037 if ((cxt->netorder = (use_network_order & 0x1))) /* Extra () for -Wall */
6038 return &PL_sv_undef; /* No byte ordering info */
6040 /* In C truth is 1, falsehood is 0. Very convenient. */
6041 use_NV_size = version_major >= 2 && version_minor >= 2;
6043 if (version_major >= 0) {
6047 c = use_network_order;
6049 length = c + 3 + use_NV_size;
6050 READ(buf, length); /* Not null-terminated */
6052 TRACEME(("byte order '%.*s' %d", c, buf, c));
6054 #ifdef USE_56_INTERWORK_KLUDGE
6055 /* No point in caching this in the context as we only need it once per
6056 retrieve, and we need to recheck it each read. */
6057 if (SvTRUE(perl_get_sv("Storable::interwork_56_64bit", GV_ADD))) {
6058 if ((c != (sizeof (byteorderstr_56) - 1))
6059 || memNE(buf, byteorderstr_56, c))
6060 CROAK(("Byte order is not compatible"));
6064 if ((c != (sizeof (byteorderstr) - 1)) || memNE(buf, byteorderstr, c))
6065 CROAK(("Byte order is not compatible"));
6071 if ((int) *current++ != sizeof(int))
6072 CROAK(("Integer size is not compatible"));
6075 if ((int) *current++ != sizeof(long))
6076 CROAK(("Long integer size is not compatible"));
6078 /* sizeof(char *) */
6079 if ((int) *current != sizeof(char *))
6080 CROAK(("Pointer size is not compatible"));
6084 if ((int) *++current != sizeof(NV))
6085 CROAK(("Double size is not compatible"));
6088 return &PL_sv_undef; /* OK */
6094 * Recursively retrieve objects from the specified file and return their
6095 * root SV (which may be an AV or an HV for what we care).
6096 * Returns null if there is a problem.
6098 static SV *retrieve(pTHX_ stcxt_t *cxt, const char *cname)
6104 TRACEME(("retrieve"));
6107 * Grab address tag which identifies the object if we are retrieving
6108 * an older format. Since the new binary format counts objects and no
6109 * longer explicitly tags them, we must keep track of the correspondence
6112 * The following section will disappear one day when the old format is
6113 * no longer supported, hence the final "goto" in the "if" block.
6116 if (cxt->hseen) { /* Retrieving old binary */
6118 if (cxt->netorder) {
6120 READ(&nettag, sizeof(I32)); /* Ordered sequence of I32 */
6121 tag = (stag_t) nettag;
6123 READ(&tag, sizeof(stag_t)); /* Original address of the SV */
6126 if (type == SX_OBJECT) {
6128 svh = hv_fetch(cxt->hseen, (char *) &tag, sizeof(tag), FALSE);
6130 CROAK(("Old tag 0x%" UVxf " should have been mapped already",
6132 tagn = SvIV(*svh); /* Mapped tag number computed earlier below */
6135 * The following code is common with the SX_OBJECT case below.
6138 svh = av_fetch(cxt->aseen, tagn, FALSE);
6140 CROAK(("Object #%" IVdf
6141 " should have been retrieved already",
6144 TRACEME(("has retrieved #%d at 0x%" UVxf, tagn,
6146 SvREFCNT_inc(sv); /* One more reference to this same sv */
6147 return sv; /* The SV pointer where object was retrieved */
6151 * Map new object, but don't increase tagnum. This will be done
6152 * by each of the retrieve_* functions when they call SEEN().
6154 * The mapping associates the "tag" initially present with a unique
6155 * tag number. See test for SX_OBJECT above to see how this is perused.
6158 if (!hv_store(cxt->hseen, (char *) &tag, sizeof(tag),
6159 newSViv(cxt->tagnum), 0))
6166 * Regular post-0.6 binary format.
6171 TRACEME(("retrieve type = %d", type));
6174 * Are we dealing with an object we should have already retrieved?
6177 if (type == SX_OBJECT) {
6181 svh = av_fetch(cxt->aseen, tag, FALSE);
6183 CROAK(("Object #%" IVdf
6184 " should have been retrieved already",
6187 TRACEME(("had retrieved #%d at 0x%" UVxf, tag, PTR2UV(sv)));
6188 SvREFCNT_inc(sv); /* One more reference to this same sv */
6189 return sv; /* The SV pointer where object was retrieved */
6190 } else if (type >= SX_ERROR && cxt->ver_minor > STORABLE_BIN_MINOR) {
6191 if (cxt->accept_future_minor < 0)
6192 cxt->accept_future_minor
6193 = (SvTRUE(perl_get_sv("Storable::accept_future_minor",
6196 if (cxt->accept_future_minor == 1) {
6197 CROAK(("Storable binary image v%d.%d contains data of type %d. "
6198 "This Storable is v%d.%d and can only handle data types up to %d",
6199 cxt->ver_major, cxt->ver_minor, type,
6200 STORABLE_BIN_MAJOR, STORABLE_BIN_MINOR, SX_ERROR - 1));
6204 first_time: /* Will disappear when support for old format is dropped */
6207 * Okay, first time through for this one.
6210 sv = RETRIEVE(cxt, type)(aTHX_ cxt, cname);
6212 return (SV *) 0; /* Failed */
6215 * Old binary formats (pre-0.7).
6217 * Final notifications, ended by SX_STORED may now follow.
6218 * Currently, the only pertinent notification to apply on the
6219 * freshly retrieved object is either:
6220 * SX_CLASS <char-len> <classname> for short classnames.
6221 * SX_LG_CLASS <int-len> <classname> for larger one (rare!).
6222 * Class name is then read into the key buffer pool used by
6223 * hash table key retrieval.
6226 if (cxt->ver_major < 2) {
6227 while ((type = GETCHAR()) != SX_STORED) {
6232 GETMARK(len); /* Length coded on a single char */
6234 case SX_LG_CLASS: /* Length coded on a regular integer */
6239 return (SV *) 0; /* Failed */
6241 KBUFCHK((STRLEN)len); /* Grow buffer as necessary */
6244 kbuf[len] = '\0'; /* Mark string end */
6245 stash = gv_stashpvn(kbuf, len, GV_ADD);
6250 TRACEME(("ok (retrieved 0x%" UVxf ", refcnt=%d, %s)", PTR2UV(sv),
6251 SvREFCNT(sv) - 1, sv_reftype(sv, FALSE)));
6259 * Retrieve data held in file and return the root object.
6260 * Common routine for pretrieve and mretrieve.
6262 static SV *do_retrieve(
6270 int is_tainted; /* Is input source tainted? */
6271 int pre_06_fmt = 0; /* True with pre Storable 0.6 formats */
6273 TRACEME(("do_retrieve (optype = 0x%x)", optype));
6275 optype |= ST_RETRIEVE;
6278 * Sanity assertions for retrieve dispatch tables.
6281 ASSERT(sizeof(sv_old_retrieve) == sizeof(sv_retrieve),
6282 ("old and new retrieve dispatch table have same size"));
6283 ASSERT(sv_old_retrieve[SX_ERROR] == retrieve_other,
6284 ("SX_ERROR entry correctly initialized in old dispatch table"));
6285 ASSERT(sv_retrieve[SX_ERROR] == retrieve_other,
6286 ("SX_ERROR entry correctly initialized in new dispatch table"));
6289 * Workaround for CROAK leak: if they enter with a "dirty" context,
6290 * free up memory for them now.
6295 clean_context(aTHX_ cxt);
6298 * Now that STORABLE_xxx hooks exist, it is possible that they try to
6299 * re-enter retrieve() via the hooks.
6303 cxt = allocate_context(aTHX_ cxt);
6307 ASSERT(cxt->entry == 1, ("starting new recursion"));
6308 ASSERT(!cxt->s_dirty, ("clean context"));
6313 * Data is loaded into the memory buffer when f is NULL, unless 'in' is
6314 * also NULL, in which case we're expecting the data to already lie
6315 * in the buffer (dclone case).
6318 KBUFINIT(); /* Allocate hash key reading pool once */
6324 const char *orig = SvPV(in, length);
6326 /* This is quite deliberate. I want the UTF8 routines
6327 to encounter the '\0' which perl adds at the end
6328 of all scalars, so that any new string also has
6331 STRLEN klen_tmp = length + 1;
6332 bool is_utf8 = TRUE;
6334 /* Just casting the &klen to (STRLEN) won't work
6335 well if STRLEN and I32 are of different widths.
6337 asbytes = (char*)bytes_from_utf8((U8*)orig,
6341 CROAK(("Frozen string corrupt - contains characters outside 0-255"));
6343 if (asbytes != orig) {
6344 /* String has been converted.
6345 There is no need to keep any reference to
6347 in = sv_newmortal();
6348 /* We donate the SV the malloc()ed string
6349 bytes_from_utf8 returned us. */
6350 SvUPGRADE(in, SVt_PV);
6352 SvPV_set(in, asbytes);
6353 SvLEN_set(in, klen_tmp);
6354 SvCUR_set(in, klen_tmp - 1);
6358 MBUF_SAVE_AND_LOAD(in);
6362 * Magic number verifications.
6364 * This needs to be done before calling init_retrieve_context()
6365 * since the format indication in the file are necessary to conduct
6366 * some of the initializations.
6369 cxt->fio = f; /* Where I/O are performed */
6371 if (!magic_check(aTHX_ cxt))
6372 CROAK(("Magic number checking on storable %s failed",
6373 cxt->fio ? "file" : "string"));
6375 TRACEME(("data stored in %s format",
6376 cxt->netorder ? "net order" : "native"));
6379 * Check whether input source is tainted, so that we don't wrongly
6380 * taint perfectly good values...
6382 * We assume file input is always tainted. If both 'f' and 'in' are
6383 * NULL, then we come from dclone, and tainted is already filled in
6384 * the context. That's a kludge, but the whole dclone() thing is
6385 * already quite a kludge anyway! -- RAM, 15/09/2000.
6388 is_tainted = f ? 1 : (in ? SvTAINTED(in) : cxt->s_tainted);
6389 TRACEME(("input source is %s", is_tainted ? "tainted" : "trusted"));
6390 init_retrieve_context(aTHX_ cxt, optype, is_tainted);
6392 ASSERT(is_retrieving(aTHX), ("within retrieve operation"));
6394 sv = retrieve(aTHX_ cxt, 0); /* Recursively retrieve object, get root SV */
6403 pre_06_fmt = cxt->hseen != NULL; /* Before we clean context */
6406 * The "root" context is never freed.
6409 clean_retrieve_context(aTHX_ cxt);
6410 if (cxt->prev) /* This context was stacked */
6411 free_context(aTHX_ cxt); /* It was not the "root" context */
6414 * Prepare returned value.
6418 TRACEME(("retrieve ERROR"));
6419 #if (PATCHLEVEL <= 4)
6420 /* perl 5.00405 seems to screw up at this point with an
6421 'attempt to modify a read only value' error reported in the
6422 eval { $self = pretrieve(*FILE) } in _retrieve.
6423 I can't see what the cause of this error is, but I suspect a
6424 bug in 5.004, as it seems to be capable of issuing spurious
6425 errors or core dumping with matches on $@. I'm not going to
6426 spend time on what could be a fruitless search for the cause,
6427 so here's a bodge. If you're running 5.004 and don't like
6428 this inefficiency, either upgrade to a newer perl, or you are
6429 welcome to find the problem and send in a patch.
6433 return &PL_sv_undef; /* Something went wrong, return undef */
6437 TRACEME(("retrieve got %s(0x%" UVxf ")",
6438 sv_reftype(sv, FALSE), PTR2UV(sv)));
6441 * Backward compatibility with Storable-0.5@9 (which we know we
6442 * are retrieving if hseen is non-null): don't create an extra RV
6443 * for objects since we special-cased it at store time.
6445 * Build a reference to the SV returned by pretrieve even if it is
6446 * already one and not a scalar, for consistency reasons.
6449 if (pre_06_fmt) { /* Was not handling overloading by then */
6451 TRACEME(("fixing for old formats -- pre 0.6"));
6452 if (sv_type(aTHX_ sv) == svis_REF && (rv = SvRV(sv)) && SvOBJECT(rv)) {
6453 TRACEME(("ended do_retrieve() with an object -- pre 0.6"));
6459 * If reference is overloaded, restore behaviour.
6461 * NB: minor glitch here: normally, overloaded refs are stored specially
6462 * so that we can croak when behaviour cannot be re-installed, and also
6463 * avoid testing for overloading magic at each reference retrieval.
6465 * Unfortunately, the root reference is implicitly stored, so we must
6466 * check for possible overloading now. Furthermore, if we don't restore
6467 * overloading, we cannot croak as if the original ref was, because we
6468 * have no way to determine whether it was an overloaded ref or not in
6471 * It's a pity that overloading magic is attached to the rv, and not to
6472 * the underlying sv as blessing is.
6476 HV *stash = (HV *) SvSTASH(sv);
6477 SV *rv = newRV_noinc(sv);
6478 if (stash && Gv_AMG(stash)) {
6480 TRACEME(("restored overloading on root reference"));
6482 TRACEME(("ended do_retrieve() with an object"));
6486 TRACEME(("regular do_retrieve() end"));
6488 return newRV_noinc(sv);
6494 * Retrieve data held in file and return the root object, undef on error.
6496 static SV *pretrieve(pTHX_ PerlIO *f)
6498 TRACEME(("pretrieve"));
6499 return do_retrieve(aTHX_ f, Nullsv, 0);
6505 * Retrieve data held in scalar and return the root object, undef on error.
6507 static SV *mretrieve(pTHX_ SV *sv)
6509 TRACEME(("mretrieve"));
6510 return do_retrieve(aTHX_ (PerlIO*) 0, sv, 0);
6520 * Deep clone: returns a fresh copy of the original referenced SV tree.
6522 * This is achieved by storing the object in memory and restoring from
6523 * there. Not that efficient, but it should be faster than doing it from
6526 static SV *dclone(pTHX_ SV *sv)
6530 stcxt_t *real_context;
6533 TRACEME(("dclone"));
6536 * Workaround for CROAK leak: if they enter with a "dirty" context,
6537 * free up memory for them now.
6542 clean_context(aTHX_ cxt);
6545 * Tied elements seem to need special handling.
6548 if ((SvTYPE(sv) == SVt_PVLV
6549 #if PERL_VERSION < 8
6550 || SvTYPE(sv) == SVt_PVMG
6552 ) && (SvFLAGS(sv) & (SVs_GMG|SVs_SMG|SVs_RMG)) ==
6553 (SVs_GMG|SVs_SMG|SVs_RMG) &&
6559 * do_store() optimizes for dclone by not freeing its context, should
6560 * we need to allocate one because we're deep cloning from a hook.
6563 if (!do_store(aTHX_ (PerlIO*) 0, sv, ST_CLONE, FALSE, (SV**) 0))
6564 return &PL_sv_undef; /* Error during store */
6567 * Because of the above optimization, we have to refresh the context,
6568 * since a new one could have been allocated and stacked by do_store().
6571 { dSTCXT; real_context = cxt; } /* Sub-block needed for macro */
6572 cxt = real_context; /* And we need this temporary... */
6575 * Now, 'cxt' may refer to a new context.
6579 ASSERT(!cxt->s_dirty, ("clean context"));
6580 ASSERT(!cxt->entry, ("entry will not cause new context allocation"));
6583 TRACEME(("dclone stored %d bytes", size));
6587 * Since we're passing do_retrieve() both a NULL file and sv, we need
6588 * to pre-compute the taintedness of the input by setting cxt->tainted
6589 * to whatever state our own input string was. -- RAM, 15/09/2000
6591 * do_retrieve() will free non-root context.
6594 cxt->s_tainted = SvTAINTED(sv);
6595 out = do_retrieve(aTHX_ (PerlIO*) 0, Nullsv, ST_CLONE);
6597 TRACEME(("dclone returns 0x%" UVxf, PTR2UV(out)));
6607 * The Perl IO GV object distinguishes between input and output for sockets
6608 * but not for plain files. To allow Storable to transparently work on
6609 * plain files and sockets transparently, we have to ask xsubpp to fetch the
6610 * right object for us. Hence the OutputStream and InputStream declarations.
6612 * Before perl 5.004_05, those entries in the standard typemap are not
6613 * defined in perl include files, so we do that here.
6616 #ifndef OutputStream
6617 #define OutputStream PerlIO *
6618 #define InputStream PerlIO *
6619 #endif /* !OutputStream */
6622 storable_free(pTHX_ SV *sv, MAGIC* mg) {
6623 stcxt_t *cxt = (stcxt_t *)SvPVX(sv);
6625 PERL_UNUSED_ARG(mg);
6628 if (!cxt->membuf_ro && mbase)
6630 if (cxt->membuf_ro && (cxt->msaved).arena)
6631 Safefree((cxt->msaved).arena);
6635 MODULE = Storable PACKAGE = Storable
6641 HV *stash = gv_stashpvn("Storable", 8, GV_ADD);
6642 newCONSTSUB(stash, "BIN_MAJOR", newSViv(STORABLE_BIN_MAJOR));
6643 newCONSTSUB(stash, "BIN_MINOR", newSViv(STORABLE_BIN_MINOR));
6644 newCONSTSUB(stash, "BIN_WRITE_MINOR", newSViv(STORABLE_BIN_WRITE_MINOR));
6646 init_perinterp(aTHX);
6647 gv_fetchpv("Storable::drop_utf8", GV_ADDMULTI, SVt_PV);
6649 /* Only disable the used only once warning if we are in debugging mode. */
6650 gv_fetchpv("Storable::DEBUGME", GV_ADDMULTI, SVt_PV);
6652 #ifdef USE_56_INTERWORK_KLUDGE
6653 gv_fetchpv("Storable::interwork_56_64bit", GV_ADDMULTI, SVt_PV);
6660 init_perinterp(aTHX);
6664 # Store the transitive data closure of given object to disk.
6665 # Returns undef on error, a true value otherwise.
6669 # Same as pstore(), but network order is used for integers and doubles are
6670 # emitted as strings.
6679 RETVAL = do_store(aTHX_ f, obj, 0, ix, (SV **)0) ? &PL_sv_yes : &PL_sv_undef;
6680 /* do_store() can reallocate the stack, so need a sequence point to ensure
6681 that ST(0) knows about it. Hence using two statements. */
6687 # Store the transitive data closure of given object to memory.
6688 # Returns undef on error, a scalar value containing the data otherwise.
6692 # Same as mstore(), but network order is used for integers and doubles are
6693 # emitted as strings.
6701 RETVAL = &PL_sv_undef;
6702 if (!do_store(aTHX_ (PerlIO*) 0, obj, 0, ix, &RETVAL))
6703 RETVAL = &PL_sv_undef;
6711 RETVAL = pretrieve(aTHX_ f);
6719 RETVAL = mretrieve(aTHX_ sv);
6727 RETVAL = dclone(aTHX_ sv);
6732 last_op_in_netorder()
6734 is_storing = ST_STORE
6735 is_retrieving = ST_RETRIEVE
6743 result = cxt->entry && (cxt->optype & ix) ? TRUE : FALSE;
6745 result = !!last_op_in_netorder(aTHX);
6747 ST(0) = boolSV(result);