1 /* -*- c-basic-offset: 4 -*-
3 * Fast store and retrieve mechanism.
5 * Copyright (c) 1995-2000, Raphael Manfredi
6 * Copyright (c) 2016, 2017 cPanel Inc
7 * Copyright (c) 2017 Reini Urban
9 * You may redistribute only under the same terms as Perl 5, as specified
10 * in the README file that comes with the distribution.
14 #define PERL_NO_GET_CONTEXT /* we want efficiency */
20 #include <patchlevel.h> /* Perl's one, needed since 5.6 */
23 #if !defined(PERL_VERSION) || PERL_VERSION < 10 || (PERL_VERSION == 10 && PERL_SUBVERSION < 1)
24 #define NEED_PL_parser
25 #define NEED_sv_2pv_flags
26 #define NEED_load_module
27 #define NEED_vload_module
28 #define NEED_newCONSTSUB
29 #define NEED_newSVpvn_flags
30 #define NEED_newRV_noinc
31 #include "ppport.h" /* handle old perls */
35 #define DEBUGME /* Debug mode, turns assertions on as well */
36 #define DASSERT /* Assertion mode */
40 * Pre PerlIO time when none of USE_PERLIO and PERLIO_IS_STDIO is defined
41 * Provide them with the necessary defines so they can build with pre-5.004.
44 #ifndef PERLIO_IS_STDIO
46 #define PerlIO_getc(x) getc(x)
47 #define PerlIO_putc(f,x) putc(x,f)
48 #define PerlIO_read(x,y,z) fread(y,1,z,x)
49 #define PerlIO_write(x,y,z) fwrite(y,1,z,x)
50 #define PerlIO_stdoutf printf
51 #endif /* PERLIO_IS_STDIO */
52 #endif /* USE_PERLIO */
55 * Earlier versions of perl might be used, we can't assume they have the latest!
58 #ifndef HvSHAREKEYS_off
59 #define HvSHAREKEYS_off(hv) /* Ignore */
62 /* perl <= 5.8.2 needs this */
64 # define SvIsCOW(sv) 0
68 # define HvRITER_set(hv,r) (HvRITER(hv) = r)
71 # define HvEITER_set(hv,r) (HvEITER(hv) = r)
75 # define HvRITER_get HvRITER
78 # define HvEITER_get HvEITER
81 #ifndef HvPLACEHOLDERS_get
82 # define HvPLACEHOLDERS_get HvPLACEHOLDERS
86 # define HvTOTALKEYS(hv) HvKEYS(hv)
90 # define HvUSEDKEYS(hv) HvKEYS(hv)
94 # define SvTRULYREADONLY(sv) SvREADONLY(sv)
96 # define SvTRULYREADONLY(sv) (SvREADONLY(sv) && !SvIsCOW(sv))
100 # define SvPVCLEAR(sv) sv_setpvs(sv, "")
104 # define strEQc(s,c) memEQ(s, ("" c ""), sizeof(c))
114 * TRACEME() will only output things when the $Storable::DEBUGME is true.
119 if (SvTRUE(get_sv("Storable::DEBUGME", GV_ADD))) \
120 { PerlIO_stdoutf x; PerlIO_stdoutf("\n"); } \
127 #define ASSERT(x,y) \
130 PerlIO_stdoutf("ASSERT FAILED (\"%s\", line %d): ", \
131 __FILE__, (int)__LINE__); \
132 PerlIO_stdoutf y; PerlIO_stdoutf("\n"); \
143 #define C(x) ((char) (x)) /* For markers with dynamic retrieval handling */
145 #define SX_OBJECT C(0) /* Already stored object */
146 #define SX_LSCALAR C(1) /* Scalar (large binary) follows (length, data) */
147 #define SX_ARRAY C(2) /* Array forthcoming (size, item list) */
148 #define SX_HASH C(3) /* Hash forthcoming (size, key/value pair list) */
149 #define SX_REF C(4) /* Reference to object forthcoming */
150 #define SX_UNDEF C(5) /* Undefined scalar */
151 #define SX_INTEGER C(6) /* Integer forthcoming */
152 #define SX_DOUBLE C(7) /* Double forthcoming */
153 #define SX_BYTE C(8) /* (signed) byte forthcoming */
154 #define SX_NETINT C(9) /* Integer in network order forthcoming */
155 #define SX_SCALAR C(10) /* Scalar (binary, small) follows (length, data) */
156 #define SX_TIED_ARRAY C(11) /* Tied array forthcoming */
157 #define SX_TIED_HASH C(12) /* Tied hash forthcoming */
158 #define SX_TIED_SCALAR C(13) /* Tied scalar forthcoming */
159 #define SX_SV_UNDEF C(14) /* Perl's immortal PL_sv_undef */
160 #define SX_SV_YES C(15) /* Perl's immortal PL_sv_yes */
161 #define SX_SV_NO C(16) /* Perl's immortal PL_sv_no */
162 #define SX_BLESS C(17) /* Object is blessed */
163 #define SX_IX_BLESS C(18) /* Object is blessed, classname given by index */
164 #define SX_HOOK C(19) /* Stored via hook, user-defined */
165 #define SX_OVERLOAD C(20) /* Overloaded reference */
166 #define SX_TIED_KEY C(21) /* Tied magic key forthcoming */
167 #define SX_TIED_IDX C(22) /* Tied magic index forthcoming */
168 #define SX_UTF8STR C(23) /* UTF-8 string forthcoming (small) */
169 #define SX_LUTF8STR C(24) /* UTF-8 string forthcoming (large) */
170 #define SX_FLAG_HASH C(25) /* Hash with flags forthcoming (size, flags, key/flags/value triplet list) */
171 #define SX_CODE C(26) /* Code references as perl source code */
172 #define SX_WEAKREF C(27) /* Weak reference to object forthcoming */
173 #define SX_WEAKOVERLOAD C(28) /* Overloaded weak reference */
174 #define SX_VSTRING C(29) /* vstring forthcoming (small) */
175 #define SX_LVSTRING C(30) /* vstring forthcoming (large) */
176 #define SX_SVUNDEF_ELEM C(31) /* array element set to &PL_sv_undef */
177 #define SX_ERROR C(32) /* Error */
178 #define SX_LOBJECT C(33) /* Large object: string, array or hash (size >2G) */
179 #define SX_LAST C(34) /* invalid. marker only */
182 * Those are only used to retrieve "old" pre-0.6 binary images.
184 #define SX_ITEM 'i' /* An array item introducer */
185 #define SX_IT_UNDEF 'I' /* Undefined array item */
186 #define SX_KEY 'k' /* A hash key introducer */
187 #define SX_VALUE 'v' /* A hash value introducer */
188 #define SX_VL_UNDEF 'V' /* Undefined hash value */
191 * Those are only used to retrieve "old" pre-0.7 binary images
194 #define SX_CLASS 'b' /* Object is blessed, class name length <255 */
195 #define SX_LG_CLASS 'B' /* Object is blessed, class name length >255 */
196 #define SX_STORED 'X' /* End of object */
199 * Limits between short/long length representation.
202 #define LG_SCALAR 255 /* Large scalar length limit */
203 #define LG_BLESS 127 /* Large classname bless limit */
209 #define ST_STORE 0x1 /* Store operation */
210 #define ST_RETRIEVE 0x2 /* Retrieval operation */
211 #define ST_CLONE 0x4 /* Deep cloning operation */
214 * The following structure is used for hash table key retrieval. Since, when
215 * retrieving objects, we'll be facing blessed hash references, it's best
216 * to pre-allocate that buffer once and resize it as the need arises, never
217 * freeing it (keys will be saved away someplace else anyway, so even large
218 * keys are not enough a motivation to reclaim that space).
220 * This structure is also used for memory store/retrieve operations which
221 * happen in a fixed place before being malloc'ed elsewhere if persistence
222 * is required. Hence the aptr pointer.
225 char *arena; /* Will hold hash key strings, resized as needed */
226 STRLEN asiz; /* Size of aforementioned buffer */
227 char *aptr; /* Arena pointer, for in-place read/write ops */
228 char *aend; /* First invalid address */
233 * A hash table records the objects which have already been stored.
234 * Those are referred to as SX_OBJECT in the file, and their "tag" (i.e.
235 * an arbitrary sequence number) is used to identify them.
238 * An array table records the objects which have already been retrieved,
239 * as seen by the tag determined by counting the objects themselves. The
240 * reference to that retrieved object is kept in the table, and is returned
241 * when an SX_OBJECT is found bearing that same tag.
243 * The same processing is used to record "classname" for blessed objects:
244 * indexing by a hash at store time, and via an array at retrieve time.
247 typedef unsigned long stag_t; /* Used by pre-0.6 binary format */
250 * The following "thread-safe" related defines were contributed by
251 * Murray Nesbitt <murray@activestate.com> and integrated by RAM, who
252 * only renamed things a little bit to ensure consistency with surrounding
253 * code. -- RAM, 14/09/1999
255 * The original patch suffered from the fact that the stcxt_t structure
256 * was global. Murray tried to minimize the impact on the code as much as
259 * Starting with 0.7, Storable can be re-entrant, via the STORABLE_xxx hooks
260 * on objects. Therefore, the notion of context needs to be generalized,
264 #define MY_VERSION "Storable(" XS_VERSION ")"
268 * Conditional UTF8 support.
272 #define STORE_UTF8STR(pv, len) STORE_PV_LEN(pv, len, SX_UTF8STR, SX_LUTF8STR)
273 #define HAS_UTF8_SCALARS
275 #define HAS_UTF8_HASHES
278 /* 5.6 perl has utf8 scalars but not hashes */
282 #define STORE_UTF8STR(pv, len) CROAK(("panic: storing UTF8 in non-UTF8 perl"))
285 #define UTF8_CROAK() CROAK(("Cannot retrieve UTF8 data in non-UTF8 perl"))
288 #define WEAKREF_CROAK() CROAK(("Cannot retrieve weak references in this perl"))
291 #define VSTRING_CROAK() CROAK(("Cannot retrieve vstring in this perl"))
294 #ifdef HvPLACEHOLDERS
295 #define HAS_RESTRICTED_HASHES
297 #define HVhek_PLACEHOLD 0x200
298 #define RESTRICTED_HASH_CROAK() CROAK(("Cannot retrieve restricted hash"))
302 #define HAS_HASH_KEY_FLAGS
306 #define USE_PTR_TABLE
309 /* Needed for 32bit with lengths > 2G - 4G, and 64bit */
315 * Fields s_tainted and s_dirty are prefixed with s_ because Perl's include
316 * files remap tainted and dirty when threading is enabled. That's bad for
317 * perl to remap such common words. -- RAM, 29/09/00
321 typedef struct stcxt {
322 int entry; /* flags recursion */
323 int optype; /* type of traversal operation */
324 /* which objects have been seen, store time.
325 tags are numbers, which are cast to (SV *) and stored directly */
327 /* use pseen if we have ptr_tables. We have to store tag+1, because
328 tag numbers start at 0, and we can't store (SV *) 0 in a ptr_table
329 without it being confused for a fetch lookup failure. */
330 struct ptr_tbl *pseen;
331 /* Still need hseen for the 0.6 file format code. */
334 AV *hook_seen; /* which SVs were returned by STORABLE_freeze() */
335 AV *aseen; /* which objects have been seen, retrieve time */
336 IV where_is_undef; /* index in aseen of PL_sv_undef */
337 HV *hclass; /* which classnames have been seen, store time */
338 AV *aclass; /* which classnames have been seen, retrieve time */
339 HV *hook; /* cache for hook methods per class name */
340 IV tagnum; /* incremented at store time for each seen object */
341 IV classnum; /* incremented at store time for each seen classname */
342 int netorder; /* true if network order used */
343 int s_tainted; /* true if input source is tainted, at retrieve time */
344 int forgive_me; /* whether to be forgiving... */
345 int deparse; /* whether to deparse code refs */
346 SV *eval; /* whether to eval source code */
347 int canonical; /* whether to store hashes sorted by key */
348 #ifndef HAS_RESTRICTED_HASHES
349 int derestrict; /* whether to downgrade restricted hashes */
352 int use_bytes; /* whether to bytes-ify utf8 */
354 int accept_future_minor; /* croak immediately on future minor versions? */
355 int s_dirty; /* context is dirty due to CROAK() -- can be cleaned */
356 int membuf_ro; /* true means membuf is read-only and msaved is rw */
357 struct extendable keybuf; /* for hash key retrieval */
358 struct extendable membuf; /* for memory store/retrieve operations */
359 struct extendable msaved; /* where potentially valid mbuf is saved */
360 PerlIO *fio; /* where I/O are performed, NULL for memory */
361 int ver_major; /* major of version for retrieved object */
362 int ver_minor; /* minor of version for retrieved object */
363 SV *(**retrieve_vtbl)(pTHX_ struct stcxt *, const char *); /* retrieve dispatch table */
364 SV *prev; /* contexts chained backwards in real recursion */
365 SV *my_sv; /* the blessed scalar who's SvPVX() I am */
366 SV *recur_sv; /* check only one recursive SV */
367 int in_retrieve_overloaded; /* performance hack for retrieving overloaded objects */
368 int flags; /* controls whether to bless or tie objects */
369 U16 recur_depth; /* avoid stack overflows RT #97526 */
372 /* Note: We dont count nested scalars. This will have to count all refs
373 without any recursion detection. */
374 /* JSON::XS has 512 */
375 /* sizes computed with stacksize. use some reserve for the croak cleanup. */
376 #include "stacksize.h"
377 /* esp. cygwin64 cannot 32, cygwin32 can. mingw needs more */
379 # define STACK_RESERVE 32
381 /* 8 should be enough, but some systems, esp. 32bit, need more */
382 # define STACK_RESERVE 16
384 #ifdef PST_STACK_MAX_DEPTH
385 # if (PERL_VERSION > 14) && !(defined(__CYGWIN__) && (PTRSIZE == 8))
386 # define MAX_DEPTH (PST_STACK_MAX_DEPTH - STACK_RESERVE)
387 # define MAX_DEPTH_HASH (PST_STACK_MAX_DEPTH_HASH - STACK_RESERVE)
389 /* within the exception we need another stack depth to recursively cleanup the hash */
390 # define MAX_DEPTH ((PST_STACK_MAX_DEPTH >> 1) - STACK_RESERVE)
391 # define MAX_DEPTH_HASH ((PST_STACK_MAX_DEPTH_HASH >> 1) - (STACK_RESERVE*2))
394 /* uninitialized (stacksize failed): safe */
395 # define MAX_DEPTH 512
396 # define MAX_DEPTH_HASH 256
398 #define MAX_DEPTH_ERROR "Max. recursion depth with nested structures exceeded"
400 static int storable_free(pTHX_ SV *sv, MAGIC* mg);
402 static MGVTBL vtbl_storable = {
419 /* From Digest::MD5. */
421 # define sv_magicext(sv, obj, type, vtbl, name, namlen) \
422 THX_sv_magicext(aTHX_ sv, obj, type, vtbl, name, namlen)
423 static MAGIC *THX_sv_magicext(pTHX_
424 SV *sv, SV *obj, int type,
425 MGVTBL const *vtbl, char const *name, I32 namlen)
429 /* exceeded intended usage of this reserve implementation */
432 mg->mg_virtual = (MGVTBL*)vtbl;
434 mg->mg_ptr = (char *)name;
436 (void) SvUPGRADE(sv, SVt_PVMG);
437 mg->mg_moremagic = SvMAGIC(sv);
445 #define NEW_STORABLE_CXT_OBJ(cxt) \
447 SV *self = newSV(sizeof(stcxt_t) - 1); \
448 SV *my_sv = newRV_noinc(self); \
449 sv_magicext(self, NULL, PERL_MAGIC_ext, &vtbl_storable, NULL, 0); \
450 cxt = (stcxt_t *)SvPVX(self); \
451 Zero(cxt, 1, stcxt_t); \
452 cxt->my_sv = my_sv; \
455 #if defined(MULTIPLICITY) || defined(PERL_OBJECT) || defined(PERL_CAPI)
457 #if (PATCHLEVEL <= 4) && (SUBVERSION < 68)
459 SV *perinterp_sv = get_sv(MY_VERSION, 0)
460 #else /* >= perl5.004_68 */
462 SV *perinterp_sv = *hv_fetch(PL_modglobal, \
463 MY_VERSION, sizeof(MY_VERSION)-1, TRUE)
464 #endif /* < perl5.004_68 */
466 #define dSTCXT_PTR(T,name) \
467 T name = ((perinterp_sv \
468 && SvIOK(perinterp_sv) && SvIVX(perinterp_sv) \
469 ? (T)SvPVX(SvRV(INT2PTR(SV*,SvIVX(perinterp_sv)))) : (T) 0))
472 dSTCXT_PTR(stcxt_t *, cxt)
476 NEW_STORABLE_CXT_OBJ(cxt); \
477 assert(perinterp_sv); \
478 sv_setiv(perinterp_sv, PTR2IV(cxt->my_sv))
480 #define SET_STCXT(x) \
483 sv_setiv(perinterp_sv, PTR2IV(x->my_sv)); \
486 #else /* !MULTIPLICITY && !PERL_OBJECT && !PERL_CAPI */
488 static stcxt_t *Context_ptr = NULL;
489 #define dSTCXT stcxt_t *cxt = Context_ptr
490 #define SET_STCXT(x) Context_ptr = x
493 NEW_STORABLE_CXT_OBJ(cxt); \
497 #endif /* MULTIPLICITY || PERL_OBJECT || PERL_CAPI */
501 * Croaking implies a memory leak, since we don't use setjmp/longjmp
502 * to catch the exit and free memory used during store or retrieve
503 * operations. This is not too difficult to fix, but I need to understand
504 * how Perl does it, and croaking is exceptional anyway, so I lack the
505 * motivation to do it.
507 * The current workaround is to mark the context as dirty when croaking,
508 * so that data structures can be freed whenever we renter Storable code
509 * (but only *then*: it's a workaround, not a fix).
511 * This is also imperfect, because we don't really know how far they trapped
512 * the croak(), and when we were recursing, we won't be able to clean anything
513 * but the topmost context stacked.
516 #define CROAK(x) STMT_START { cxt->s_dirty = 1; croak x; } STMT_END
519 * End of "thread-safe" related definitions.
525 * Keep only the low 32 bits of a pointer (used for tags, which are not
530 #define LOW_32BITS(x) ((I32) (x))
532 #define LOW_32BITS(x) ((I32) ((unsigned long) (x) & 0xffffffffUL))
538 * Hack for Crays, where sizeof(I32) == 8, and which are big-endians.
539 * Used in the WLEN and RLEN macros.
543 #define oI(x) ((I32 *) ((char *) (x) + 4))
544 #define oS(x) ((x) - 4)
546 #define oC(x) (x = 0)
556 * key buffer handling
558 #define kbuf (cxt->keybuf).arena
559 #define ksiz (cxt->keybuf).asiz
563 TRACEME(("** allocating kbuf of 128 bytes")); \
564 New(10003, kbuf, 128, char); \
572 CROAK(("Too large size > I32_MAX")); \
573 TRACEME(("** extending kbuf to %d bytes (had %d)", \
574 (int)(x+1), (int)ksiz)); \
575 Renew(kbuf, x+1, char); \
581 * memory buffer handling
583 #define mbase (cxt->membuf).arena
584 #define msiz (cxt->membuf).asiz
585 #define mptr (cxt->membuf).aptr
586 #define mend (cxt->membuf).aend
588 #define MGROW (1 << 13)
589 #define MMASK (MGROW - 1)
591 #define round_mgrow(x) \
592 ((STRLEN) (((STRLEN) (x) + MMASK) & ~MMASK))
593 #define trunc_int(x) \
594 ((unsigned long) ((unsigned long) (x) & ~(sizeof(int)-1)))
595 #define int_aligned(x) \
596 ((unsigned long) (x) == trunc_int(x))
598 #define MBUF_INIT(x) \
601 TRACEME(("** allocating mbase of %d bytes", MGROW)); \
602 New(10003, mbase, (int)MGROW, char); \
603 msiz = (STRLEN)MGROW; \
609 mend = mbase + msiz; \
612 #define MBUF_TRUNC(x) mptr = mbase + x
613 #define MBUF_SIZE() (mptr - mbase)
619 * Those macros are used in do_retrieve() to save the current memory
620 * buffer into cxt->msaved, before MBUF_LOAD() can be used to retrieve
621 * data from a string.
623 #define MBUF_SAVE_AND_LOAD(in) \
625 ASSERT(!cxt->membuf_ro, ("mbase not already saved")); \
626 cxt->membuf_ro = 1; \
627 TRACEME(("saving mbuf")); \
628 StructCopy(&cxt->membuf, &cxt->msaved, struct extendable); \
632 #define MBUF_RESTORE() \
634 ASSERT(cxt->membuf_ro, ("mbase is read-only")); \
635 cxt->membuf_ro = 0; \
636 TRACEME(("restoring mbuf")); \
637 StructCopy(&cxt->msaved, &cxt->membuf, struct extendable); \
641 * Use SvPOKp(), because SvPOK() fails on tainted scalars.
642 * See store_scalar() for other usage of this workaround.
644 #define MBUF_LOAD(v) \
646 ASSERT(cxt->membuf_ro, ("mbase is read-only")); \
648 CROAK(("Not a scalar string")); \
649 mptr = mbase = SvPV(v, msiz); \
650 mend = mbase + msiz; \
653 #define MBUF_XTEND(x) \
655 STRLEN nsz = (STRLEN) round_mgrow((x)+msiz); \
656 STRLEN offset = mptr - mbase; \
657 ASSERT(!cxt->membuf_ro, ("mbase is not read-only")); \
658 TRACEME(("** extending mbase from %ld to %ld bytes (wants %ld new)", \
659 (long)msiz, nsz, (long)(x))); \
660 Renew(mbase, nsz, char); \
662 mptr = mbase + offset; \
663 mend = mbase + nsz; \
666 #define MBUF_CHK(x) \
668 if ((mptr + (x)) > mend) \
672 #define MBUF_GETC(x) \
675 x = (int) (unsigned char) *mptr++; \
681 #define MBUF_GETINT(x) \
684 if ((mptr + 4) <= mend) { \
685 memcpy(oI(&x), mptr, 4); \
691 #define MBUF_GETINT(x) \
693 if ((mptr + sizeof(int)) <= mend) { \
694 if (int_aligned(mptr)) \
697 memcpy(&x, mptr, sizeof(int)); \
698 mptr += sizeof(int); \
704 #define MBUF_READ(x,s) \
706 if ((mptr + (s)) <= mend) { \
707 memcpy(x, mptr, s); \
713 #define MBUF_SAFEREAD(x,s,z) \
715 if ((mptr + (s)) <= mend) { \
716 memcpy(x, mptr, s); \
724 #define MBUF_SAFEPVREAD(x,s,z) \
726 if ((mptr + (s)) <= mend) { \
727 memcpy(x, mptr, s); \
735 #define MBUF_PUTC(c) \
738 *mptr++ = (char) c; \
741 *mptr++ = (char) c; \
746 #define MBUF_PUTINT(i) \
749 memcpy(mptr, oI(&i), 4); \
753 #define MBUF_PUTINT(i) \
755 MBUF_CHK(sizeof(int)); \
756 if (int_aligned(mptr)) \
759 memcpy(mptr, &i, sizeof(int)); \
760 mptr += sizeof(int); \
764 #define MBUF_PUTLONG(l) \
767 memcpy(mptr, &l, 8); \
770 #define MBUF_WRITE(x,s) \
773 memcpy(mptr, x, s); \
778 * Possible return values for sv_type().
782 #define svis_SCALAR 1
786 #define svis_TIED_ITEM 5
794 #define SHF_TYPE_MASK 0x03
795 #define SHF_LARGE_CLASSLEN 0x04
796 #define SHF_LARGE_STRLEN 0x08
797 #define SHF_LARGE_LISTLEN 0x10
798 #define SHF_IDX_CLASSNAME 0x20
799 #define SHF_NEED_RECURSE 0x40
800 #define SHF_HAS_LIST 0x80
803 * Types for SX_HOOK (last 2 bits in flags).
809 #define SHT_EXTRA 3 /* Read extra byte for type */
812 * The following are held in the "extra byte"...
815 #define SHT_TSCALAR 4 /* 4 + 0 -- tied scalar */
816 #define SHT_TARRAY 5 /* 4 + 1 -- tied array */
817 #define SHT_THASH 6 /* 4 + 2 -- tied hash */
820 * per hash flags for flagged hashes
823 #define SHV_RESTRICTED 0x01
826 * per key flags for flagged hashes
829 #define SHV_K_UTF8 0x01
830 #define SHV_K_WASUTF8 0x02
831 #define SHV_K_LOCKED 0x04
832 #define SHV_K_ISSV 0x08
833 #define SHV_K_PLACEHOLDER 0x10
836 * flags to allow blessing and/or tieing data the data we load
838 #define FLAG_BLESS_OK 2
839 #define FLAG_TIE_OK 4
842 * Before 0.6, the magic string was "perl-store" (binary version number 0).
844 * Since 0.6 introduced many binary incompatibilities, the magic string has
845 * been changed to "pst0" to allow an old image to be properly retrieved by
846 * a newer Storable, but ensure a newer image cannot be retrieved with an
849 * At 0.7, objects are given the ability to serialize themselves, and the
850 * set of markers is extended, backward compatibility is not jeopardized,
851 * so the binary version number could have remained unchanged. To correctly
852 * spot errors if a file making use of 0.7-specific extensions is given to
853 * 0.6 for retrieval, the binary version was moved to "2". And I'm introducing
854 * a "minor" version, to better track this kind of evolution from now on.
857 static const char old_magicstr[] = "perl-store"; /* Magic number before 0.6 */
858 static const char magicstr[] = "pst0"; /* Used as a magic number */
860 #define MAGICSTR_BYTES 'p','s','t','0'
861 #define OLDMAGICSTR_BYTES 'p','e','r','l','-','s','t','o','r','e'
863 /* 5.6.x introduced the ability to have IVs as long long.
864 However, Configure still defined BYTEORDER based on the size of a long.
865 Storable uses the BYTEORDER value as part of the header, but doesn't
866 explicitly store sizeof(IV) anywhere in the header. Hence on 5.6.x built
867 with IV as long long on a platform that uses Configure (ie most things
868 except VMS and Windows) headers are identical for the different IV sizes,
869 despite the files containing some fields based on sizeof(IV)
871 5.8 is consistent - the following redefinition kludge is only needed on
872 5.6.x, but the interwork is needed on 5.8 while data survives in files
877 #if defined (IVSIZE) && (IVSIZE == 8) && (LONGSIZE == 4)
878 #ifndef NO_56_INTERWORK_KLUDGE
879 #define USE_56_INTERWORK_KLUDGE
881 #if BYTEORDER == 0x1234
883 #define BYTEORDER 0x12345678
885 #if BYTEORDER == 0x4321
887 #define BYTEORDER 0x87654321
892 #if BYTEORDER == 0x1234
893 #define BYTEORDER_BYTES '1','2','3','4'
895 #if BYTEORDER == 0x12345678
896 #define BYTEORDER_BYTES '1','2','3','4','5','6','7','8'
897 #ifdef USE_56_INTERWORK_KLUDGE
898 #define BYTEORDER_BYTES_56 '1','2','3','4'
901 #if BYTEORDER == 0x87654321
902 #define BYTEORDER_BYTES '8','7','6','5','4','3','2','1'
903 #ifdef USE_56_INTERWORK_KLUDGE
904 #define BYTEORDER_BYTES_56 '4','3','2','1'
907 #if BYTEORDER == 0x4321
908 #define BYTEORDER_BYTES '4','3','2','1'
910 #error Unknown byteorder. Please append your byteorder to Storable.xs
917 # define INT32_MAX 2147483647
919 #if IVSIZE > 4 && !defined(INT64_MAX)
920 # define INT64_MAX 9223372036854775807LL
923 static const char byteorderstr[] = {BYTEORDER_BYTES, 0};
924 #ifdef USE_56_INTERWORK_KLUDGE
925 static const char byteorderstr_56[] = {BYTEORDER_BYTES_56, 0};
928 #define STORABLE_BIN_MAJOR 2 /* Binary major "version" */
929 #define STORABLE_BIN_MINOR 11 /* Binary minor "version" */
931 #if (PATCHLEVEL <= 5)
932 #define STORABLE_BIN_WRITE_MINOR 4
933 #elif !defined (SvVOK)
935 * Perl 5.6.0-5.8.0 can do weak references, but not vstring magic.
937 #define STORABLE_BIN_WRITE_MINOR 8
938 #elif PATCHLEVEL >= 19
939 /* Perl 5.19 takes away the special meaning of PL_sv_undef in arrays. */
940 /* With 3.x we added LOBJECT */
941 #define STORABLE_BIN_WRITE_MINOR 11
943 #define STORABLE_BIN_WRITE_MINOR 9
944 #endif /* (PATCHLEVEL <= 5) */
946 #if (PATCHLEVEL < 8 || (PATCHLEVEL == 8 && SUBVERSION < 1))
947 #define PL_sv_placeholder PL_sv_undef
951 * Useful store shortcuts...
955 * Note that if you put more than one mark for storing a particular
956 * type of thing, *and* in the retrieve_foo() function you mark both
957 * the thingy's you get off with SEEN(), you *must* increase the
958 * tagnum with cxt->tagnum++ along with this macro!
965 else if (PerlIO_putc(cxt->fio, x) == EOF) \
969 #define WRITE_I32(x) \
971 ASSERT(sizeof(x) == sizeof(I32), ("writing an I32")); \
974 else if (PerlIO_write(cxt->fio, oI(&x), \
975 oS(sizeof(x))) != oS(sizeof(x))) \
979 #define WRITE_U64(x) \
981 ASSERT(sizeof(x) == sizeof(UV), ("writing an UV")); \
984 else if (PerlIO_write(cxt->fio, oL(&x), \
985 oS(sizeof(x))) != oS(sizeof(x))) \
992 ASSERT(sizeof(x) == sizeof(int), ("WLEN writing an int")); \
993 if (cxt->netorder) { \
994 int y = (int) htonl(x); \
997 else if (PerlIO_write(cxt->fio,oI(&y),oS(sizeof(y))) != oS(sizeof(y))) \
1002 else if (PerlIO_write(cxt->fio,oI(&x), \
1003 oS(sizeof(x))) != oS(sizeof(x))) \
1009 ASSERT(sizeof(x) == 8, ("W64LEN writing a U64")); \
1010 if (cxt->netorder) { \
1011 union u64_t { U32 a; U32 b; } y; \
1012 y.b = htonl(x & 0xffffffffUL); \
1013 y.a = htonl(x >> 32); \
1016 else if (PerlIO_write(cxt->fio,oI(&y), \
1017 oS(sizeof(y))) != oS(sizeof(y))) \
1022 else if (PerlIO_write(cxt->fio,oI(&x), \
1023 oS(sizeof(x))) != oS(sizeof(x))) \
1028 #define WLEN(x) WRITE_I32(x)
1030 #define W64LEN(x) WRITE_U64(x)
1032 #define W64LEN(x) CROAK(("no 64bit UVs"))
1036 #define WRITE(x,y) \
1040 else if (PerlIO_write(cxt->fio, x, y) != (SSize_t)y) \
1044 #define STORE_PV_LEN(pv, len, small, large) \
1046 if (len <= LG_SCALAR) { \
1047 int ilen = (int) len; \
1048 unsigned char clen = (unsigned char) len; \
1053 } else if (sizeof(len) > 4 && len > INT32_MAX) { \
1054 PUTMARK(SX_LOBJECT); \
1059 int ilen = (int) len; \
1066 #define STORE_SCALAR(pv, len) STORE_PV_LEN(pv, len, SX_SCALAR, SX_LSCALAR)
1069 * Store &PL_sv_undef in arrays without recursing through store(). We
1070 * actually use this to represent nonexistent elements, for historical
1073 #define STORE_SV_UNDEF() \
1076 PUTMARK(SX_SV_UNDEF); \
1080 * Useful retrieve shortcuts...
1084 (cxt->fio ? PerlIO_getc(cxt->fio) \
1085 : (mptr >= mend ? EOF : (int) *mptr++))
1087 #define GETMARK(x) \
1091 else if ((int) (x = PerlIO_getc(cxt->fio)) == EOF) \
1095 #define READ_I32(x) \
1097 ASSERT(sizeof(x) == sizeof(I32), ("reading an I32")); \
1101 else if (PerlIO_read(cxt->fio, oI(&x), \
1102 oS(sizeof(x))) != oS(sizeof(x))) \
1112 else if (PerlIO_read(cxt->fio, oI(&x), \
1113 oS(sizeof(x))) != oS(sizeof(x))) \
1115 if (cxt->netorder) \
1116 x = (int) ntohl(x); \
1119 #define RLEN(x) READ_I32(x)
1126 else if (PerlIO_read(cxt->fio, x, y) != (SSize_t)y) \
1130 #define SAFEREAD(x,y,z) \
1133 MBUF_SAFEREAD(x,y,z); \
1134 else if (PerlIO_read(cxt->fio, x, y) != (SSize_t)y) { \
1140 #define SAFEPVREAD(x,y,z) \
1143 MBUF_SAFEPVREAD(x,y,z); \
1144 else if (PerlIO_read(cxt->fio, x, y) != y) { \
1151 * SEEN() is used at retrieve time, to remember where object 'y', bearing a
1152 * given tag 'tagnum', has been retrieved. Next time we see an SX_OBJECT marker,
1153 * we'll therefore know where it has been retrieved and will be able to
1154 * share the same reference, as in the original stored memory image.
1156 * We also need to bless objects ASAP for hooks (which may compute "ref $x"
1157 * on the objects given to STORABLE_thaw and expect that to be defined), and
1158 * also for overloaded objects (for which we might not find the stash if the
1159 * object is not blessed yet--this might occur for overloaded objects that
1160 * refer to themselves indirectly: if we blessed upon return from a sub
1161 * retrieve(), the SX_OBJECT marker we'd found could not have overloading
1162 * restored on it because the underlying object would not be blessed yet!).
1164 * To achieve that, the class name of the last retrieved object is passed down
1165 * recursively, and the first SEEN() call for which the class name is not NULL
1166 * will bless the object.
1168 * i should be true iff sv is immortal (ie PL_sv_yes, PL_sv_no or PL_sv_undef)
1170 * SEEN0() is a short-cut where stash is always NULL.
1172 * The _NN variants dont check for y being null
1174 #define SEEN0_NN(y,i) \
1176 if (av_store(cxt->aseen, cxt->tagnum++, i ? (SV*)(y) \
1177 : SvREFCNT_inc(y)) == 0) \
1179 TRACEME(("aseen(#%d) = 0x%" UVxf " (refcnt=%d)", \
1180 (int)cxt->tagnum-1, \
1181 PTR2UV(y), (int)SvREFCNT(y)-1)); \
1184 #define SEEN0(y,i) \
1191 #define SEEN_NN(y,stash,i) \
1195 BLESS((SV *)(y), (HV *)(stash)); \
1198 #define SEEN(y,stash,i) \
1202 SEEN_NN(y,stash, i); \
1206 * Bless 's' in 'p', via a temporary reference, required by sv_bless().
1207 * "A" magic is added before the sv_bless for overloaded classes, this avoids
1208 * an expensive call to S_reset_amagic in sv_bless.
1210 #define BLESS(s,stash) \
1213 if (cxt->flags & FLAG_BLESS_OK) { \
1214 TRACEME(("blessing 0x%" UVxf " in %s", PTR2UV(s), \
1215 HvNAME_get(stash))); \
1216 ref = newRV_noinc(s); \
1217 if (cxt->in_retrieve_overloaded && Gv_AMG(stash)) { \
1218 cxt->in_retrieve_overloaded = 0; \
1221 (void) sv_bless(ref, stash); \
1222 SvRV_set(ref, NULL); \
1223 SvREFCNT_dec(ref); \
1226 TRACEME(("not blessing 0x%" UVxf " in %s", PTR2UV(s), \
1227 (HvNAME_get(stash)))); \
1231 * sort (used in store_hash) - conditionally use qsort when
1232 * sortsv is not available ( <= 5.6.1 ).
1235 #if (PATCHLEVEL <= 6)
1237 #if defined(USE_ITHREADS)
1239 #define STORE_HASH_SORT \
1241 PerlInterpreter *orig_perl = PERL_GET_CONTEXT; \
1242 SAVESPTR(orig_perl); \
1243 PERL_SET_CONTEXT(aTHX); \
1244 qsort((char *) AvARRAY(av), len, sizeof(SV *), sortcmp);\
1247 #else /* ! USE_ITHREADS */
1249 #define STORE_HASH_SORT \
1250 qsort((char *) AvARRAY(av), len, sizeof(SV *), sortcmp);
1252 #endif /* USE_ITHREADS */
1254 #else /* PATCHLEVEL > 6 */
1256 #define STORE_HASH_SORT \
1257 sortsv(AvARRAY(av), len, Perl_sv_cmp);
1259 #endif /* PATCHLEVEL <= 6 */
1261 static int store(pTHX_ stcxt_t *cxt, SV *sv);
1262 static SV *retrieve(pTHX_ stcxt_t *cxt, const char *cname);
1266 av_pop(cxt->aseen); \
1271 * Dynamic dispatching table for SV store.
1274 static int store_ref(pTHX_ stcxt_t *cxt, SV *sv);
1275 static int store_scalar(pTHX_ stcxt_t *cxt, SV *sv);
1276 static int store_array(pTHX_ stcxt_t *cxt, AV *av);
1277 static int store_hash(pTHX_ stcxt_t *cxt, HV *hv);
1278 static int store_tied(pTHX_ stcxt_t *cxt, SV *sv);
1279 static int store_tied_item(pTHX_ stcxt_t *cxt, SV *sv);
1280 static int store_code(pTHX_ stcxt_t *cxt, CV *cv);
1281 static int store_other(pTHX_ stcxt_t *cxt, SV *sv);
1282 static int store_blessed(pTHX_ stcxt_t *cxt, SV *sv, int type, HV *pkg);
1284 typedef int (*sv_store_t)(pTHX_ stcxt_t *cxt, SV *sv);
1286 static const sv_store_t sv_store[] = {
1287 (sv_store_t)store_ref, /* svis_REF */
1288 (sv_store_t)store_scalar, /* svis_SCALAR */
1289 (sv_store_t)store_array, /* svis_ARRAY */
1290 (sv_store_t)store_hash, /* svis_HASH */
1291 (sv_store_t)store_tied, /* svis_TIED */
1292 (sv_store_t)store_tied_item,/* svis_TIED_ITEM */
1293 (sv_store_t)store_code, /* svis_CODE */
1294 (sv_store_t)store_other, /* svis_OTHER */
1297 #define SV_STORE(x) (*sv_store[x])
1300 * Dynamic dispatching tables for SV retrieval.
1303 static SV *retrieve_lscalar(pTHX_ stcxt_t *cxt, const char *cname);
1304 static SV *retrieve_lutf8str(pTHX_ stcxt_t *cxt, const char *cname);
1305 static SV *old_retrieve_array(pTHX_ stcxt_t *cxt, const char *cname);
1306 static SV *old_retrieve_hash(pTHX_ stcxt_t *cxt, const char *cname);
1307 static SV *retrieve_ref(pTHX_ stcxt_t *cxt, const char *cname);
1308 static SV *retrieve_undef(pTHX_ stcxt_t *cxt, const char *cname);
1309 static SV *retrieve_integer(pTHX_ stcxt_t *cxt, const char *cname);
1310 static SV *retrieve_double(pTHX_ stcxt_t *cxt, const char *cname);
1311 static SV *retrieve_byte(pTHX_ stcxt_t *cxt, const char *cname);
1312 static SV *retrieve_netint(pTHX_ stcxt_t *cxt, const char *cname);
1313 static SV *retrieve_scalar(pTHX_ stcxt_t *cxt, const char *cname);
1314 static SV *retrieve_utf8str(pTHX_ stcxt_t *cxt, const char *cname);
1315 static SV *retrieve_tied_array(pTHX_ stcxt_t *cxt, const char *cname);
1316 static SV *retrieve_tied_hash(pTHX_ stcxt_t *cxt, const char *cname);
1317 static SV *retrieve_tied_scalar(pTHX_ stcxt_t *cxt, const char *cname);
1318 static SV *retrieve_other(pTHX_ stcxt_t *cxt, const char *cname);
1319 static SV *retrieve_lobject(pTHX_ stcxt_t *cxt, const char *cname);
1321 /* helpers for U64 lobjects */
1323 static SV *get_lstring(pTHX_ stcxt_t *cxt, UV len, int isutf8, const char *cname);
1324 static SV *get_larray(pTHX_ stcxt_t *cxt, UV len, const char *cname);
1326 static SV *get_lhash(pTHX_ stcxt_t *cxt, UV len, int flagged, const char *cname);
1327 static int store_lhash(pTHX_ stcxt_t *cxt, HV *hv, unsigned char hash_flags);
1329 static int store_hentry(pTHX_ stcxt_t *cxt, HV* hv, UV i, HE *he, unsigned char hash_flags);
1331 typedef SV* (*sv_retrieve_t)(pTHX_ stcxt_t *cxt, const char *name);
1333 static const sv_retrieve_t sv_old_retrieve[] = {
1334 0, /* SX_OBJECT -- entry unused dynamically */
1335 (sv_retrieve_t)retrieve_lscalar, /* SX_LSCALAR */
1336 (sv_retrieve_t)old_retrieve_array, /* SX_ARRAY -- for pre-0.6 binaries */
1337 (sv_retrieve_t)old_retrieve_hash, /* SX_HASH -- for pre-0.6 binaries */
1338 (sv_retrieve_t)retrieve_ref, /* SX_REF */
1339 (sv_retrieve_t)retrieve_undef, /* SX_UNDEF */
1340 (sv_retrieve_t)retrieve_integer, /* SX_INTEGER */
1341 (sv_retrieve_t)retrieve_double, /* SX_DOUBLE */
1342 (sv_retrieve_t)retrieve_byte, /* SX_BYTE */
1343 (sv_retrieve_t)retrieve_netint, /* SX_NETINT */
1344 (sv_retrieve_t)retrieve_scalar, /* SX_SCALAR */
1345 (sv_retrieve_t)retrieve_tied_array, /* SX_TIED_ARRAY */
1346 (sv_retrieve_t)retrieve_tied_hash, /* SX_TIED_HASH */
1347 (sv_retrieve_t)retrieve_tied_scalar,/* SX_TIED_SCALAR */
1348 (sv_retrieve_t)retrieve_other, /* SX_SV_UNDEF not supported */
1349 (sv_retrieve_t)retrieve_other, /* SX_SV_YES not supported */
1350 (sv_retrieve_t)retrieve_other, /* SX_SV_NO not supported */
1351 (sv_retrieve_t)retrieve_other, /* SX_BLESS not supported */
1352 (sv_retrieve_t)retrieve_other, /* SX_IX_BLESS not supported */
1353 (sv_retrieve_t)retrieve_other, /* SX_HOOK not supported */
1354 (sv_retrieve_t)retrieve_other, /* SX_OVERLOADED not supported */
1355 (sv_retrieve_t)retrieve_other, /* SX_TIED_KEY not supported */
1356 (sv_retrieve_t)retrieve_other, /* SX_TIED_IDX not supported */
1357 (sv_retrieve_t)retrieve_other, /* SX_UTF8STR not supported */
1358 (sv_retrieve_t)retrieve_other, /* SX_LUTF8STR not supported */
1359 (sv_retrieve_t)retrieve_other, /* SX_FLAG_HASH not supported */
1360 (sv_retrieve_t)retrieve_other, /* SX_CODE not supported */
1361 (sv_retrieve_t)retrieve_other, /* SX_WEAKREF not supported */
1362 (sv_retrieve_t)retrieve_other, /* SX_WEAKOVERLOAD not supported */
1363 (sv_retrieve_t)retrieve_other, /* SX_VSTRING not supported */
1364 (sv_retrieve_t)retrieve_other, /* SX_LVSTRING not supported */
1365 (sv_retrieve_t)retrieve_other, /* SX_SVUNDEF_ELEM not supported */
1366 (sv_retrieve_t)retrieve_other, /* SX_ERROR */
1367 (sv_retrieve_t)retrieve_other, /* SX_LOBJECT not supported */
1370 static SV *retrieve_array(pTHX_ stcxt_t *cxt, const char *cname);
1371 static SV *retrieve_hash(pTHX_ stcxt_t *cxt, const char *cname);
1372 static SV *retrieve_sv_undef(pTHX_ stcxt_t *cxt, const char *cname);
1373 static SV *retrieve_sv_yes(pTHX_ stcxt_t *cxt, const char *cname);
1374 static SV *retrieve_sv_no(pTHX_ stcxt_t *cxt, const char *cname);
1375 static SV *retrieve_blessed(pTHX_ stcxt_t *cxt, const char *cname);
1376 static SV *retrieve_idx_blessed(pTHX_ stcxt_t *cxt, const char *cname);
1377 static SV *retrieve_hook(pTHX_ stcxt_t *cxt, const char *cname);
1378 static SV *retrieve_overloaded(pTHX_ stcxt_t *cxt, const char *cname);
1379 static SV *retrieve_tied_key(pTHX_ stcxt_t *cxt, const char *cname);
1380 static SV *retrieve_tied_idx(pTHX_ stcxt_t *cxt, const char *cname);
1381 static SV *retrieve_flag_hash(pTHX_ stcxt_t *cxt, const char *cname);
1382 static SV *retrieve_code(pTHX_ stcxt_t *cxt, const char *cname);
1383 static SV *retrieve_weakref(pTHX_ stcxt_t *cxt, const char *cname);
1384 static SV *retrieve_weakoverloaded(pTHX_ stcxt_t *cxt, const char *cname);
1385 static SV *retrieve_vstring(pTHX_ stcxt_t *cxt, const char *cname);
1386 static SV *retrieve_lvstring(pTHX_ stcxt_t *cxt, const char *cname);
1387 static SV *retrieve_svundef_elem(pTHX_ stcxt_t *cxt, const char *cname);
1389 static const sv_retrieve_t sv_retrieve[] = {
1390 0, /* SX_OBJECT -- entry unused dynamically */
1391 (sv_retrieve_t)retrieve_lscalar, /* SX_LSCALAR */
1392 (sv_retrieve_t)retrieve_array, /* SX_ARRAY */
1393 (sv_retrieve_t)retrieve_hash, /* SX_HASH */
1394 (sv_retrieve_t)retrieve_ref, /* SX_REF */
1395 (sv_retrieve_t)retrieve_undef, /* SX_UNDEF */
1396 (sv_retrieve_t)retrieve_integer, /* SX_INTEGER */
1397 (sv_retrieve_t)retrieve_double, /* SX_DOUBLE */
1398 (sv_retrieve_t)retrieve_byte, /* SX_BYTE */
1399 (sv_retrieve_t)retrieve_netint, /* SX_NETINT */
1400 (sv_retrieve_t)retrieve_scalar, /* SX_SCALAR */
1401 (sv_retrieve_t)retrieve_tied_array, /* SX_TIED_ARRAY */
1402 (sv_retrieve_t)retrieve_tied_hash, /* SX_TIED_HASH */
1403 (sv_retrieve_t)retrieve_tied_scalar,/* SX_TIED_SCALAR */
1404 (sv_retrieve_t)retrieve_sv_undef, /* SX_SV_UNDEF */
1405 (sv_retrieve_t)retrieve_sv_yes, /* SX_SV_YES */
1406 (sv_retrieve_t)retrieve_sv_no, /* SX_SV_NO */
1407 (sv_retrieve_t)retrieve_blessed, /* SX_BLESS */
1408 (sv_retrieve_t)retrieve_idx_blessed,/* SX_IX_BLESS */
1409 (sv_retrieve_t)retrieve_hook, /* SX_HOOK */
1410 (sv_retrieve_t)retrieve_overloaded, /* SX_OVERLOAD */
1411 (sv_retrieve_t)retrieve_tied_key, /* SX_TIED_KEY */
1412 (sv_retrieve_t)retrieve_tied_idx, /* SX_TIED_IDX */
1413 (sv_retrieve_t)retrieve_utf8str, /* SX_UTF8STR */
1414 (sv_retrieve_t)retrieve_lutf8str, /* SX_LUTF8STR */
1415 (sv_retrieve_t)retrieve_flag_hash, /* SX_HASH */
1416 (sv_retrieve_t)retrieve_code, /* SX_CODE */
1417 (sv_retrieve_t)retrieve_weakref, /* SX_WEAKREF */
1418 (sv_retrieve_t)retrieve_weakoverloaded,/* SX_WEAKOVERLOAD */
1419 (sv_retrieve_t)retrieve_vstring, /* SX_VSTRING */
1420 (sv_retrieve_t)retrieve_lvstring, /* SX_LVSTRING */
1421 (sv_retrieve_t)retrieve_svundef_elem,/* SX_SVUNDEF_ELEM */
1422 (sv_retrieve_t)retrieve_other, /* SX_ERROR */
1423 (sv_retrieve_t)retrieve_lobject, /* SX_LOBJECT */
1426 #define RETRIEVE(c,x) (*(c)->retrieve_vtbl[(x) >= SX_LAST ? SX_ERROR : (x)])
1428 static SV *mbuf2sv(pTHX);
1431 *** Context management.
1437 * Called once per "thread" (interpreter) to initialize some global context.
1439 static void init_perinterp(pTHX)
1443 cxt->netorder = 0; /* true if network order used */
1444 cxt->forgive_me = -1; /* whether to be forgiving... */
1445 cxt->accept_future_minor = -1; /* would otherwise occur too late */
1451 * Called at the end of every context cleaning, to perform common reset
1454 static void reset_context(stcxt_t *cxt)
1458 cxt->recur_sv = NULL;
1459 cxt->recur_depth = 0;
1460 cxt->optype &= ~(ST_STORE|ST_RETRIEVE); /* Leave ST_CLONE alone */
1464 * init_store_context
1466 * Initialize a new store context for real recursion.
1468 static void init_store_context(pTHX_
1474 TRACEME(("init_store_context"));
1476 cxt->netorder = network_order;
1477 cxt->forgive_me = -1; /* Fetched from perl if needed */
1478 cxt->deparse = -1; /* Idem */
1479 cxt->eval = NULL; /* Idem */
1480 cxt->canonical = -1; /* Idem */
1481 cxt->tagnum = -1; /* Reset tag numbers */
1482 cxt->classnum = -1; /* Reset class numbers */
1483 cxt->fio = f; /* Where I/O are performed */
1484 cxt->optype = optype; /* A store, or a deep clone */
1485 cxt->entry = 1; /* No recursion yet */
1488 * The 'hseen' table is used to keep track of each SV stored and their
1489 * associated tag numbers is special. It is "abused" because the
1490 * values stored are not real SV, just integers cast to (SV *),
1491 * which explains the freeing below.
1493 * It is also one possible bottleneck to achieve good storing speed,
1494 * so the "shared keys" optimization is turned off (unlikely to be
1495 * of any use here), and the hash table is "pre-extended". Together,
1496 * those optimizations increase the throughput by 12%.
1499 #ifdef USE_PTR_TABLE
1500 cxt->pseen = ptr_table_new();
1503 cxt->hseen = newHV(); /* Table where seen objects are stored */
1504 HvSHAREKEYS_off(cxt->hseen);
1507 * The following does not work well with perl5.004_04, and causes
1508 * a core dump later on, in a completely unrelated spot, which
1509 * makes me think there is a memory corruption going on.
1511 * Calling hv_ksplit(hseen, HBUCKETS) instead of manually hacking
1512 * it below does not make any difference. It seems to work fine
1513 * with perl5.004_68 but given the probable nature of the bug,
1514 * that does not prove anything.
1516 * It's a shame because increasing the amount of buckets raises
1517 * store() throughput by 5%, but until I figure this out, I can't
1518 * allow for this to go into production.
1520 * It is reported fixed in 5.005, hence the #if.
1522 #if PERL_VERSION >= 5
1523 #define HBUCKETS 4096 /* Buckets for %hseen */
1524 #ifndef USE_PTR_TABLE
1525 HvMAX(cxt->hseen) = HBUCKETS - 1; /* keys %hseen = $HBUCKETS; */
1530 * The 'hclass' hash uses the same settings as 'hseen' above, but it is
1531 * used to assign sequential tags (numbers) to class names for blessed
1534 * We turn the shared key optimization on.
1537 cxt->hclass = newHV(); /* Where seen classnames are stored */
1539 #if PERL_VERSION >= 5
1540 HvMAX(cxt->hclass) = HBUCKETS - 1; /* keys %hclass = $HBUCKETS; */
1544 * The 'hook' hash table is used to keep track of the references on
1545 * the STORABLE_freeze hook routines, when found in some class name.
1547 * It is assumed that the inheritance tree will not be changed during
1548 * storing, and that no new method will be dynamically created by the
1552 cxt->hook = newHV(); /* Table where hooks are cached */
1555 * The 'hook_seen' array keeps track of all the SVs returned by
1556 * STORABLE_freeze hooks for us to serialize, so that they are not
1557 * reclaimed until the end of the serialization process. Each SV is
1558 * only stored once, the first time it is seen.
1561 cxt->hook_seen = newAV(); /* Lists SVs returned by STORABLE_freeze */
1565 * clean_store_context
1567 * Clean store context by
1569 static void clean_store_context(pTHX_ stcxt_t *cxt)
1573 TRACEME(("clean_store_context"));
1575 ASSERT(cxt->optype & ST_STORE, ("was performing a store()"));
1578 * Insert real values into hashes where we stored faked pointers.
1581 #ifndef USE_PTR_TABLE
1583 hv_iterinit(cxt->hseen);
1584 while ((he = hv_iternext(cxt->hseen))) /* Extra () for -Wall */
1585 HeVAL(he) = &PL_sv_undef;
1590 hv_iterinit(cxt->hclass);
1591 while ((he = hv_iternext(cxt->hclass))) /* Extra () for -Wall */
1592 HeVAL(he) = &PL_sv_undef;
1596 * And now dispose of them...
1598 * The surrounding if() protection has been added because there might be
1599 * some cases where this routine is called more than once, during
1600 * exceptional events. This was reported by Marc Lehmann when Storable
1601 * is executed from mod_perl, and the fix was suggested by him.
1602 * -- RAM, 20/12/2000
1605 #ifdef USE_PTR_TABLE
1607 struct ptr_tbl *pseen = cxt->pseen;
1609 ptr_table_free(pseen);
1611 assert(!cxt->hseen);
1614 HV *hseen = cxt->hseen;
1617 sv_free((SV *) hseen);
1622 HV *hclass = cxt->hclass;
1625 sv_free((SV *) hclass);
1629 HV *hook = cxt->hook;
1632 sv_free((SV *) hook);
1635 if (cxt->hook_seen) {
1636 AV *hook_seen = cxt->hook_seen;
1638 av_undef(hook_seen);
1639 sv_free((SV *) hook_seen);
1642 cxt->forgive_me = -1; /* Fetched from perl if needed */
1643 cxt->deparse = -1; /* Idem */
1645 SvREFCNT_dec(cxt->eval);
1647 cxt->eval = NULL; /* Idem */
1648 cxt->canonical = -1; /* Idem */
1654 * init_retrieve_context
1656 * Initialize a new retrieve context for real recursion.
1658 static void init_retrieve_context(pTHX_
1659 stcxt_t *cxt, int optype, int is_tainted)
1661 TRACEME(("init_retrieve_context"));
1664 * The hook hash table is used to keep track of the references on
1665 * the STORABLE_thaw hook routines, when found in some class name.
1667 * It is assumed that the inheritance tree will not be changed during
1668 * storing, and that no new method will be dynamically created by the
1672 cxt->hook = newHV(); /* Caches STORABLE_thaw */
1674 #ifdef USE_PTR_TABLE
1679 * If retrieving an old binary version, the cxt->retrieve_vtbl variable
1680 * was set to sv_old_retrieve. We'll need a hash table to keep track of
1681 * the correspondence between the tags and the tag number used by the
1682 * new retrieve routines.
1685 cxt->hseen = (((void*)cxt->retrieve_vtbl == (void*)sv_old_retrieve)
1688 cxt->aseen = newAV(); /* Where retrieved objects are kept */
1689 cxt->where_is_undef = -1; /* Special case for PL_sv_undef */
1690 cxt->aclass = newAV(); /* Where seen classnames are kept */
1691 cxt->tagnum = 0; /* Have to count objects... */
1692 cxt->classnum = 0; /* ...and class names as well */
1693 cxt->optype = optype;
1694 cxt->s_tainted = is_tainted;
1695 cxt->entry = 1; /* No recursion yet */
1696 #ifndef HAS_RESTRICTED_HASHES
1697 cxt->derestrict = -1; /* Fetched from perl if needed */
1699 #ifndef HAS_UTF8_ALL
1700 cxt->use_bytes = -1; /* Fetched from perl if needed */
1702 cxt->accept_future_minor = -1;/* Fetched from perl if needed */
1703 cxt->in_retrieve_overloaded = 0;
1707 * clean_retrieve_context
1709 * Clean retrieve context by
1711 static void clean_retrieve_context(pTHX_ stcxt_t *cxt)
1713 TRACEME(("clean_retrieve_context"));
1715 ASSERT(cxt->optype & ST_RETRIEVE, ("was performing a retrieve()"));
1718 AV *aseen = cxt->aseen;
1721 sv_free((SV *) aseen);
1723 cxt->where_is_undef = -1;
1726 AV *aclass = cxt->aclass;
1729 sv_free((SV *) aclass);
1733 HV *hook = cxt->hook;
1736 sv_free((SV *) hook);
1740 HV *hseen = cxt->hseen;
1743 sv_free((SV *) hseen); /* optional HV, for backward compat. */
1746 #ifndef HAS_RESTRICTED_HASHES
1747 cxt->derestrict = -1; /* Fetched from perl if needed */
1749 #ifndef HAS_UTF8_ALL
1750 cxt->use_bytes = -1; /* Fetched from perl if needed */
1752 cxt->accept_future_minor = -1; /* Fetched from perl if needed */
1754 cxt->in_retrieve_overloaded = 0;
1761 * A workaround for the CROAK bug: cleanup the last context.
1763 static void clean_context(pTHX_ stcxt_t *cxt)
1765 TRACEME(("clean_context"));
1767 ASSERT(cxt->s_dirty, ("dirty context"));
1772 ASSERT(!cxt->membuf_ro, ("mbase is not read-only"));
1774 if (cxt->optype & ST_RETRIEVE)
1775 clean_retrieve_context(aTHX_ cxt);
1776 else if (cxt->optype & ST_STORE)
1777 clean_store_context(aTHX_ cxt);
1781 ASSERT(!cxt->s_dirty, ("context is clean"));
1782 ASSERT(cxt->entry == 0, ("context is reset"));
1788 * Allocate a new context and push it on top of the parent one.
1789 * This new context is made globally visible via SET_STCXT().
1791 static stcxt_t *allocate_context(pTHX_ stcxt_t *parent_cxt)
1795 TRACEME(("allocate_context"));
1797 ASSERT(!parent_cxt->s_dirty, ("parent context clean"));
1799 NEW_STORABLE_CXT_OBJ(cxt);
1800 cxt->prev = parent_cxt->my_sv;
1803 ASSERT(!cxt->s_dirty, ("clean context"));
1811 * Free current context, which cannot be the "root" one.
1812 * Make the context underneath globally visible via SET_STCXT().
1814 static void free_context(pTHX_ stcxt_t *cxt)
1816 stcxt_t *prev = (stcxt_t *)(cxt->prev ? SvPVX(SvRV(cxt->prev)) : 0);
1818 TRACEME(("free_context"));
1820 ASSERT(!cxt->s_dirty, ("clean context"));
1821 ASSERT(prev, ("not freeing root context"));
1824 SvREFCNT_dec(cxt->my_sv);
1827 ASSERT(cxt, ("context not void"));
1834 /* these two functions are currently only used within asserts */
1839 * Tells whether we're in the middle of a store operation.
1841 static int is_storing(pTHX)
1845 return cxt->entry && (cxt->optype & ST_STORE);
1851 * Tells whether we're in the middle of a retrieve operation.
1853 static int is_retrieving(pTHX)
1857 return cxt->entry && (cxt->optype & ST_RETRIEVE);
1862 * last_op_in_netorder
1864 * Returns whether last operation was made using network order.
1866 * This is typically out-of-band information that might prove useful
1867 * to people wishing to convert native to network order data when used.
1869 static int last_op_in_netorder(pTHX)
1874 return cxt->netorder;
1878 *** Hook lookup and calling routines.
1884 * A wrapper on gv_fetchmethod_autoload() which caches results.
1886 * Returns the routine reference as an SV*, or null if neither the package
1887 * nor its ancestors know about the method.
1889 static SV *pkg_fetchmeth(pTHX_
1896 const char *hvname = HvNAME_get(pkg);
1900 * The following code is the same as the one performed by UNIVERSAL::can
1904 gv = gv_fetchmethod_autoload(pkg, method, FALSE);
1905 if (gv && isGV(gv)) {
1906 sv = newRV_inc((SV*) GvCV(gv));
1907 TRACEME(("%s->%s: 0x%" UVxf, hvname, method, PTR2UV(sv)));
1909 sv = newSVsv(&PL_sv_undef);
1910 TRACEME(("%s->%s: not found", hvname, method));
1914 * Cache the result, ignoring failure: if we can't store the value,
1915 * it just won't be cached.
1918 (void) hv_store(cache, hvname, strlen(hvname), sv, 0);
1920 return SvOK(sv) ? sv : (SV *) 0;
1926 * Force cached value to be undef: hook ignored even if present.
1928 static void pkg_hide(pTHX_
1933 const char *hvname = HvNAME_get(pkg);
1934 PERL_UNUSED_ARG(method);
1935 (void) hv_store(cache,
1936 hvname, strlen(hvname), newSVsv(&PL_sv_undef), 0);
1942 * Discard cached value: a whole fetch loop will be retried at next lookup.
1944 static void pkg_uncache(pTHX_
1949 const char *hvname = HvNAME_get(pkg);
1950 PERL_UNUSED_ARG(method);
1951 (void) hv_delete(cache, hvname, strlen(hvname), G_DISCARD);
1957 * Our own "UNIVERSAL::can", which caches results.
1959 * Returns the routine reference as an SV*, or null if the object does not
1960 * know about the method.
1962 static SV *pkg_can(pTHX_
1969 const char *hvname = HvNAME_get(pkg);
1971 TRACEME(("pkg_can for %s->%s", hvname, method));
1974 * Look into the cache to see whether we already have determined
1975 * where the routine was, if any.
1977 * NOTA BENE: we don't use 'method' at all in our lookup, since we know
1978 * that only one hook (i.e. always the same) is cached in a given cache.
1981 svh = hv_fetch(cache, hvname, strlen(hvname), FALSE);
1985 TRACEME(("cached %s->%s: not found", hvname, method));
1988 TRACEME(("cached %s->%s: 0x%" UVxf,
1989 hvname, method, PTR2UV(sv)));
1994 TRACEME(("not cached yet"));
1995 return pkg_fetchmeth(aTHX_ cache, pkg, method); /* Fetch and cache */
2001 * Call routine as obj->hook(av) in scalar context.
2002 * Propagates the single returned value if not called in void context.
2004 static SV *scalar_call(pTHX_
2015 TRACEME(("scalar_call (cloning=%d)", cloning));
2022 XPUSHs(sv_2mortal(newSViv(cloning))); /* Cloning flag */
2024 SV **ary = AvARRAY(av);
2025 SSize_t cnt = AvFILLp(av) + 1;
2027 XPUSHs(ary[0]); /* Frozen string */
2028 for (i = 1; i < cnt; i++) {
2029 TRACEME(("pushing arg #%d (0x%" UVxf ")...",
2030 (int)i, PTR2UV(ary[i])));
2031 XPUSHs(sv_2mortal(newRV_inc(ary[i])));
2036 TRACEME(("calling..."));
2037 count = call_sv(hook, flags); /* Go back to Perl code */
2038 TRACEME(("count = %d", count));
2044 SvREFCNT_inc(sv); /* We're returning it, must stay alive! */
2057 * Call routine obj->hook(cloning) in list context.
2058 * Returns the list of returned values in an array.
2060 static AV *array_call(pTHX_
2070 TRACEME(("array_call (cloning=%d)", cloning));
2076 XPUSHs(obj); /* Target object */
2077 XPUSHs(sv_2mortal(newSViv(cloning))); /* Cloning flag */
2080 count = call_sv(hook, G_ARRAY); /* Go back to Perl code */
2085 for (i = count - 1; i >= 0; i--) {
2087 av_store(av, i, SvREFCNT_inc(sv));
2097 #if PERL_VERSION < 15
2099 cleanup_recursive_av(pTHX_ AV* av) {
2100 SSize_t i = AvFILLp(av);
2101 SV** arr = AvARRAY(av);
2102 if (SvMAGICAL(av)) return;
2105 #if PERL_VERSION < 14
2108 SvREFCNT_dec(arr[i]);
2115 #ifndef SvREFCNT_IMMORTAL
2117 /* exercise the immortal resurrection code in sv_free2() */
2118 # define SvREFCNT_IMMORTAL 1000
2120 # define SvREFCNT_IMMORTAL ((~(U32)0)/2)
2125 cleanup_recursive_hv(pTHX_ HV* hv) {
2126 SSize_t i = HvTOTALKEYS(hv);
2127 HE** arr = HvARRAY(hv);
2128 if (SvMAGICAL(hv)) return;
2131 SvREFCNT(HeVAL(arr[i])) = SvREFCNT_IMMORTAL;
2132 arr[i] = NULL; /* let it leak. too dangerous to clean it up here */
2136 #if PERL_VERSION < 8
2137 ((XPVHV*)SvANY(hv))->xhv_array = NULL;
2141 HvTOTALKEYS(hv) = 0;
2144 cleanup_recursive_rv(pTHX_ SV* sv) {
2145 if (sv && SvROK(sv))
2146 SvREFCNT_dec(SvRV(sv));
2149 cleanup_recursive_data(pTHX_ SV* sv) {
2150 if (SvTYPE(sv) == SVt_PVAV) {
2151 cleanup_recursive_av(aTHX_ (AV*)sv);
2153 else if (SvTYPE(sv) == SVt_PVHV) {
2154 cleanup_recursive_hv(aTHX_ (HV*)sv);
2157 cleanup_recursive_rv(aTHX_ sv);
2165 * Lookup the class name in the 'hclass' table and either assign it a new ID
2166 * or return the existing one, by filling in 'classnum'.
2168 * Return true if the class was known, false if the ID was just generated.
2170 static int known_class(pTHX_
2172 char *name, /* Class name */
2173 int len, /* Name length */
2177 HV *hclass = cxt->hclass;
2179 TRACEME(("known_class (%s)", name));
2182 * Recall that we don't store pointers in this hash table, but tags.
2183 * Therefore, we need LOW_32BITS() to extract the relevant parts.
2186 svh = hv_fetch(hclass, name, len, FALSE);
2188 *classnum = LOW_32BITS(*svh);
2193 * Unknown classname, we need to record it.
2197 if (!hv_store(hclass, name, len, INT2PTR(SV*, cxt->classnum), 0))
2198 CROAK(("Unable to record new classname"));
2200 *classnum = cxt->classnum;
2205 *** Specific store routines.
2211 * Store a reference.
2212 * Layout is SX_REF <object> or SX_OVERLOAD <object>.
2214 static int store_ref(pTHX_ stcxt_t *cxt, SV *sv)
2218 TRACEME(("store_ref (0x%" UVxf ")", PTR2UV(sv)));
2221 * Follow reference, and check if target is overloaded.
2227 TRACEME(("ref (0x%" UVxf ") is%s weak", PTR2UV(sv),
2228 is_weak ? "" : "n't"));
2233 HV *stash = (HV *) SvSTASH(sv);
2234 if (stash && Gv_AMG(stash)) {
2235 TRACEME(("ref (0x%" UVxf ") is overloaded", PTR2UV(sv)));
2236 PUTMARK(is_weak ? SX_WEAKOVERLOAD : SX_OVERLOAD);
2238 PUTMARK(is_weak ? SX_WEAKREF : SX_REF);
2240 PUTMARK(is_weak ? SX_WEAKREF : SX_REF);
2242 TRACEME(("recur_depth %u, recur_sv (0x%" UVxf ")", cxt->recur_depth,
2243 PTR2UV(cxt->recur_sv)));
2244 if (cxt->entry && cxt->recur_sv == sv) {
2245 if (++cxt->recur_depth > MAX_DEPTH) {
2246 #if PERL_VERSION < 15
2247 cleanup_recursive_data(aTHX_ (SV*)sv);
2249 CROAK((MAX_DEPTH_ERROR));
2254 retval = store(aTHX_ cxt, sv);
2255 if (cxt->entry && cxt->recur_sv == sv && cxt->recur_depth > 0) {
2256 TRACEME(("recur_depth --%u", cxt->recur_depth));
2267 * Layout is SX_LSCALAR <length> <data>, SX_SCALAR <length> <data> or SX_UNDEF.
2268 * SX_LUTF8STR and SX_UTF8STR are used for UTF-8 strings.
2269 * The <data> section is omitted if <length> is 0.
2271 * For vstrings, the vstring portion is stored first with
2272 * SX_LVSTRING <length> <data> or SX_VSTRING <length> <data>, followed by
2273 * SX_(L)SCALAR or SX_(L)UTF8STR with the actual PV.
2275 * If integer or double, the layout is SX_INTEGER <data> or SX_DOUBLE <data>.
2276 * Small integers (within [-127, +127]) are stored as SX_BYTE <byte>.
2278 * For huge strings use SX_LOBJECT SX_type SX_U64 <type> <data>
2280 static int store_scalar(pTHX_ stcxt_t *cxt, SV *sv)
2285 U32 flags = SvFLAGS(sv); /* "cc -O" may put it in register */
2287 TRACEME(("store_scalar (0x%" UVxf ")", PTR2UV(sv)));
2290 * For efficiency, break the SV encapsulation by peaking at the flags
2291 * directly without using the Perl macros to avoid dereferencing
2292 * sv->sv_flags each time we wish to check the flags.
2295 if (!(flags & SVf_OK)) { /* !SvOK(sv) */
2296 if (sv == &PL_sv_undef) {
2297 TRACEME(("immortal undef"));
2298 PUTMARK(SX_SV_UNDEF);
2300 TRACEME(("undef at 0x%" UVxf, PTR2UV(sv)));
2307 * Always store the string representation of a scalar if it exists.
2308 * Gisle Aas provided me with this test case, better than a long speach:
2310 * perl -MDevel::Peek -le '$a="abc"; $a+0; Dump($a)'
2311 * SV = PVNV(0x80c8520)
2313 * FLAGS = (NOK,POK,pNOK,pPOK)
2316 * PV = 0x80c83d0 "abc"\0
2320 * Write SX_SCALAR, length, followed by the actual data.
2322 * Otherwise, write an SX_BYTE, SX_INTEGER or an SX_DOUBLE as
2323 * appropriate, followed by the actual (binary) data. A double
2324 * is written as a string if network order, for portability.
2326 * NOTE: instead of using SvNOK(sv), we test for SvNOKp(sv).
2327 * The reason is that when the scalar value is tainted, the SvNOK(sv)
2330 * The test for a read-only scalar with both POK and NOK set is meant
2331 * to quickly detect &PL_sv_yes and &PL_sv_no without having to pay the
2332 * address comparison for each scalar we store.
2335 #define SV_MAYBE_IMMORTAL (SVf_READONLY|SVf_POK|SVf_NOK)
2337 if ((flags & SV_MAYBE_IMMORTAL) == SV_MAYBE_IMMORTAL) {
2338 if (sv == &PL_sv_yes) {
2339 TRACEME(("immortal yes"));
2341 } else if (sv == &PL_sv_no) {
2342 TRACEME(("immortal no"));
2345 pv = SvPV(sv, len); /* We know it's SvPOK */
2346 goto string; /* Share code below */
2348 } else if (flags & SVf_POK) {
2349 /* public string - go direct to string read. */
2350 goto string_readlen;
2352 #if (PATCHLEVEL <= 6)
2353 /* For 5.6 and earlier NV flag trumps IV flag, so only use integer
2354 direct if NV flag is off. */
2355 (flags & (SVf_NOK | SVf_IOK)) == SVf_IOK
2357 /* 5.7 rules are that if IV public flag is set, IV value is as
2358 good, if not better, than NV value. */
2364 * Will come here from below with iv set if double is an integer.
2368 /* Sorry. This isn't in 5.005_56 (IIRC) or earlier. */
2370 /* Need to do this out here, else 0xFFFFFFFF becomes iv of -1
2371 * (for example) and that ends up in the optimised small integer
2374 if ((flags & SVf_IVisUV) && SvUV(sv) > IV_MAX) {
2375 TRACEME(("large unsigned integer as string, value = %" UVuf,
2377 goto string_readlen;
2381 * Optimize small integers into a single byte, otherwise store as
2382 * a real integer (converted into network order if they asked).
2385 if (iv >= -128 && iv <= 127) {
2386 unsigned char siv = (unsigned char) (iv + 128); /* [0,255] */
2389 TRACEME(("small integer stored as %d", (int)siv));
2390 } else if (cxt->netorder) {
2392 TRACEME(("no htonl, fall back to string for integer"));
2393 goto string_readlen;
2401 /* Sorry. This isn't in 5.005_56 (IIRC) or earlier. */
2402 ((flags & SVf_IVisUV) && SvUV(sv) > (UV)0x7FFFFFFF) ||
2404 (iv > (IV)0x7FFFFFFF) || (iv < -(IV)0x80000000)) {
2405 /* Bigger than 32 bits. */
2406 TRACEME(("large network order integer as string, value = %" IVdf, iv));
2407 goto string_readlen;
2411 niv = (I32) htonl((I32) iv);
2412 TRACEME(("using network order"));
2417 PUTMARK(SX_INTEGER);
2418 WRITE(&iv, sizeof(iv));
2421 TRACEME(("ok (integer 0x%" UVxf ", value = %" IVdf ")", PTR2UV(sv), iv));
2422 } else if (flags & SVf_NOK) {
2424 #if (PATCHLEVEL <= 6)
2427 * Watch for number being an integer in disguise.
2429 if (nv == (NV) (iv = I_V(nv))) {
2430 TRACEME(("double %" NVff " is actually integer %" IVdf, nv, iv));
2431 goto integer; /* Share code above */
2436 if (SvIOK_notUV(sv)) {
2438 goto integer; /* Share code above */
2443 if (cxt->netorder) {
2444 TRACEME(("double %" NVff " stored as string", nv));
2445 goto string_readlen; /* Share code below */
2449 WRITE(&nv, sizeof(nv));
2451 TRACEME(("ok (double 0x%" UVxf ", value = %" NVff ")", PTR2UV(sv), nv));
2453 } else if (flags & (SVp_POK | SVp_NOK | SVp_IOK)) {
2457 UV wlen; /* For 64-bit machines */
2463 * Will come here from above if it was readonly, POK and NOK but
2464 * neither &PL_sv_yes nor &PL_sv_no.
2469 if (SvMAGICAL(sv) && (mg = mg_find(sv, 'V'))) {
2470 /* The macro passes this by address, not value, and a lot of
2471 called code assumes that it's 32 bits without checking. */
2472 const SSize_t len = mg->mg_len;
2473 STORE_PV_LEN((const char *)mg->mg_ptr,
2474 len, SX_VSTRING, SX_LVSTRING);
2480 STORE_UTF8STR(pv, wlen);
2482 STORE_SCALAR(pv, wlen);
2483 TRACEME(("ok (scalar 0x%" UVxf " '%s', length = %" UVuf ")",
2484 PTR2UV(sv), len >= 2048 ? "<string too long>" : SvPVX(sv),
2487 CROAK(("Can't determine type of %s(0x%" UVxf ")",
2488 sv_reftype(sv, FALSE),
2491 return 0; /* Ok, no recursion on scalars */
2499 * Layout is SX_ARRAY <size> followed by each item, in increasing index order.
2500 * Each item is stored as <object>.
2502 static int store_array(pTHX_ stcxt_t *cxt, AV *av)
2505 UV len = av_len(av) + 1;
2509 TRACEME(("store_array (0x%" UVxf ")", PTR2UV(av)));
2512 if (len > 0x7fffffffu) {
2514 * Large array by emitting SX_LOBJECT 1 U64 data
2516 PUTMARK(SX_LOBJECT);
2519 TRACEME(("lobject size = %lu", (unsigned long)len));
2524 * Normal array by emitting SX_ARRAY, followed by the array length.
2529 TRACEME(("size = %d", (int)l));
2532 TRACEME(("recur_depth %u, recur_sv (0x%" UVxf ")", cxt->recur_depth,
2533 PTR2UV(cxt->recur_sv)));
2534 if (cxt->entry && cxt->recur_sv == (SV*)av) {
2535 if (++cxt->recur_depth > MAX_DEPTH) {
2536 /* with <= 5.14 it recurses in the cleanup also, needing 2x stack size */
2537 #if PERL_VERSION < 15
2538 cleanup_recursive_data(aTHX_ (SV*)av);
2540 CROAK((MAX_DEPTH_ERROR));
2543 cxt->recur_sv = (SV*)av;
2546 * Now store each item recursively.
2549 for (i = 0; i < len; i++) {
2550 sav = av_fetch(av, i, 0);
2552 TRACEME(("(#%d) nonexistent item", (int)i));
2556 #if PATCHLEVEL >= 19
2557 /* In 5.19.3 and up, &PL_sv_undef can actually be stored in
2558 * an array; it no longer represents nonexistent elements.
2559 * Historically, we have used SX_SV_UNDEF in arrays for
2560 * nonexistent elements, so we use SX_SVUNDEF_ELEM for
2561 * &PL_sv_undef itself. */
2562 if (*sav == &PL_sv_undef) {
2563 TRACEME(("(#%d) undef item", (int)i));
2565 PUTMARK(SX_SVUNDEF_ELEM);
2569 TRACEME(("(#%d) item", (int)i));
2570 if ((ret = store(aTHX_ cxt, *sav))) /* Extra () for -Wall */
2574 if (cxt->entry && cxt->recur_sv == (SV*)av && cxt->recur_depth > 0) {
2575 TRACEME(("recur_depth --%u", cxt->recur_depth));
2578 TRACEME(("ok (array)"));
2584 #if (PATCHLEVEL <= 6)
2590 * Borrowed from perl source file pp_ctl.c, where it is used by pp_sort.
2593 sortcmp(const void *a, const void *b)
2595 #if defined(USE_ITHREADS)
2597 #endif /* USE_ITHREADS */
2598 return sv_cmp(*(SV * const *) a, *(SV * const *) b);
2601 #endif /* PATCHLEVEL <= 6 */
2606 * Store a hash table.
2608 * For a "normal" hash (not restricted, no utf8 keys):
2610 * Layout is SX_HASH <size> followed by each key/value pair, in random order.
2611 * Values are stored as <object>.
2612 * Keys are stored as <length> <data>, the <data> section being omitted
2615 * For a "fancy" hash (restricted or utf8 keys):
2617 * Layout is SX_FLAG_HASH <size> <hash flags> followed by each key/value pair,
2619 * Values are stored as <object>.
2620 * Keys are stored as <flags> <length> <data>, the <data> section being omitted
2622 * Currently the only hash flag is "restricted"
2623 * Key flags are as for hv.h
2625 static int store_hash(pTHX_ stcxt_t *cxt, HV *hv)
2628 UV len = (UV)HvTOTALKEYS(hv);
2633 int flagged_hash = ((SvREADONLY(hv)
2634 #ifdef HAS_HASH_KEY_FLAGS
2638 unsigned char hash_flags = (SvREADONLY(hv) ? SHV_RESTRICTED : 0);
2641 * Signal hash by emitting SX_HASH, followed by the table length.
2642 * Max number of keys per perl version:
2644 * STRLEN 5.14 - 5.24 (size_t: U32/U64)
2645 * SSize_t 5.22c - 5.24c (I32/I64)
2649 if (len > 0x7fffffffu) { /* keys > I32_MAX */
2651 * Large hash: SX_LOBJECT type hashflags? U64 data
2653 * Stupid limitation:
2654 * Note that perl5 can store more than 2G keys, but only iterate
2655 * over 2G max. (cperl can)
2656 * We need to manually iterate over it then, unsorted.
2657 * But until perl itself cannot do that, skip that.
2659 TRACEME(("lobject size = %lu", (unsigned long)len));
2661 PUTMARK(SX_LOBJECT);
2663 PUTMARK(SX_FLAG_HASH);
2664 PUTMARK(hash_flags);
2669 return store_lhash(aTHX_ cxt, hv, hash_flags);
2671 /* <5.12 you could store larger hashes, but cannot iterate over them.
2672 So we reject them, it's a bug. */
2673 CROAK(("Cannot store large objects on a 32bit system"));
2678 TRACEME(("store_hash (0x%" UVxf ") (flags %x)", PTR2UV(hv),
2679 (unsigned int)hash_flags));
2680 PUTMARK(SX_FLAG_HASH);
2681 PUTMARK(hash_flags);
2683 TRACEME(("store_hash (0x%" UVxf ")", PTR2UV(hv)));
2687 TRACEME(("size = %d, used = %d", (int)l, (int)HvUSEDKEYS(hv)));
2690 TRACEME(("recur_depth %u, recur_sv (0x%" UVxf ")", cxt->recur_depth,
2691 PTR2UV(cxt->recur_sv)));
2692 if (cxt->entry && cxt->recur_sv == (SV*)hv) {
2693 if (++cxt->recur_depth > MAX_DEPTH_HASH) {
2694 #if PERL_VERSION < 15
2695 cleanup_recursive_data(aTHX_ (SV*)hv);
2697 CROAK((MAX_DEPTH_ERROR));
2700 cxt->recur_sv = (SV*)hv;
2703 * Save possible iteration state via each() on that table.
2705 * Note that perl as of 5.24 *can* store more than 2G keys, but *not*
2707 * Lengths of hash keys are also limited to I32, which is good.
2710 riter = HvRITER_get(hv);
2711 eiter = HvEITER_get(hv);
2715 * Now store each item recursively.
2717 * If canonical is defined to some true value then store each
2718 * key/value pair in sorted order otherwise the order is random.
2719 * Canonical order is irrelevant when a deep clone operation is performed.
2721 * Fetch the value from perl only once per store() operation, and only
2726 !(cxt->optype & ST_CLONE)
2727 && (cxt->canonical == 1
2728 || (cxt->canonical < 0
2729 && (cxt->canonical =
2730 (SvTRUE(get_sv("Storable::canonical", GV_ADD))
2734 * Storing in order, sorted by key.
2735 * Run through the hash, building up an array of keys in a
2736 * mortal array, sort the array and then run through the
2740 av_extend (av, len);
2742 TRACEME(("using canonical order"));
2744 for (i = 0; i < len; i++) {
2745 #ifdef HAS_RESTRICTED_HASHES
2746 HE *he = hv_iternext_flags(hv, HV_ITERNEXT_WANTPLACEHOLDERS);
2748 HE *he = hv_iternext(hv);
2750 av_store(av, i, hv_iterkeysv(he));
2755 for (i = 0; i < len; i++) {
2756 #ifdef HAS_RESTRICTED_HASHES
2757 int placeholders = (int)HvPLACEHOLDERS_get(hv);
2759 unsigned char flags = 0;
2763 SV *key = av_shift(av);
2764 /* This will fail if key is a placeholder.
2765 Track how many placeholders we have, and error if we
2767 HE *he = hv_fetch_ent(hv, key, 0, 0);
2771 if (!(val = HeVAL(he))) {
2772 /* Internal error, not I/O error */
2776 #ifdef HAS_RESTRICTED_HASHES
2777 /* Should be a placeholder. */
2778 if (placeholders-- < 0) {
2779 /* This should not happen - number of
2780 retrieves should be identical to
2781 number of placeholders. */
2784 /* Value is never needed, and PL_sv_undef is
2785 more space efficient to store. */
2788 ("Flags not 0 but %d", (int)flags));
2789 flags = SHV_K_PLACEHOLDER;
2796 * Store value first.
2799 TRACEME(("(#%d) value 0x%" UVxf, (int)i, PTR2UV(val)));
2801 if ((ret = store(aTHX_ cxt, val))) /* Extra () for -Wall, grr... */
2806 * Keys are written after values to make sure retrieval
2807 * can be optimal in terms of memory usage, where keys are
2808 * read into a fixed unique buffer called kbuf.
2809 * See retrieve_hash() for details.
2812 /* Implementation of restricted hashes isn't nicely
2814 if ((hash_flags & SHV_RESTRICTED)
2815 && SvTRULYREADONLY(val)) {
2816 flags |= SHV_K_LOCKED;
2819 keyval = SvPV(key, keylen_tmp);
2820 keylen = keylen_tmp;
2821 #ifdef HAS_UTF8_HASHES
2822 /* If you build without optimisation on pre 5.6
2823 then nothing spots that SvUTF8(key) is always 0,
2824 so the block isn't optimised away, at which point
2825 the linker dislikes the reference to
2828 const char *keysave = keyval;
2829 bool is_utf8 = TRUE;
2831 /* Just casting the &klen to (STRLEN) won't work
2832 well if STRLEN and I32 are of different widths.
2834 keyval = (char*)bytes_from_utf8((U8*)keyval,
2838 /* If we were able to downgrade here, then than
2839 means that we have a key which only had chars
2840 0-255, but was utf8 encoded. */
2842 if (keyval != keysave) {
2843 keylen = keylen_tmp;
2844 flags |= SHV_K_WASUTF8;
2846 /* keylen_tmp can't have changed, so no need
2847 to assign back to keylen. */
2848 flags |= SHV_K_UTF8;
2855 TRACEME(("(#%d) key '%s' flags %x %u", (int)i, keyval, flags, *keyval));
2857 /* This is a workaround for a bug in 5.8.0
2858 that causes the HEK_WASUTF8 flag to be
2859 set on an HEK without the hash being
2860 marked as having key flags. We just
2861 cross our fingers and drop the flag.
2863 assert (flags == 0 || flags == SHV_K_WASUTF8);
2864 TRACEME(("(#%d) key '%s'", (int)i, keyval));
2868 WRITE(keyval, keylen);
2869 if (flags & SHV_K_WASUTF8)
2874 * Free up the temporary array
2883 * Storing in "random" order (in the order the keys are stored
2884 * within the hash). This is the default and will be faster!
2887 for (i = 0; i < len; i++) {
2888 #ifdef HV_ITERNEXT_WANTPLACEHOLDERS
2889 HE *he = hv_iternext_flags(hv, HV_ITERNEXT_WANTPLACEHOLDERS);
2891 HE *he = hv_iternext(hv);
2893 SV *val = (he ? hv_iterval(hv, he) : 0);
2896 return 1; /* Internal error, not I/O error */
2898 if ((ret = store_hentry(aTHX_ cxt, hv, i, he, hash_flags)))
2901 /* Implementation of restricted hashes isn't nicely
2903 flags = (((hash_flags & SHV_RESTRICTED)
2904 && SvTRULYREADONLY(val))
2905 ? SHV_K_LOCKED : 0);
2907 if (val == &PL_sv_placeholder) {
2908 flags |= SHV_K_PLACEHOLDER;
2913 * Store value first.
2916 TRACEME(("(#%d) value 0x%" UVxf, (int)i, PTR2UV(val)));
2918 if ((ret = store(aTHX_ cxt, val))) /* Extra () for -Wall */
2922 hek = HeKEY_hek(he);
2924 if (len == HEf_SVKEY) {
2925 /* This is somewhat sick, but the internal APIs are
2926 * such that XS code could put one of these in in
2928 * Maybe we should be capable of storing one if
2931 key_sv = HeKEY_sv(he);
2932 flags |= SHV_K_ISSV;
2934 /* Regular string key. */
2935 #ifdef HAS_HASH_KEY_FLAGS
2937 flags |= SHV_K_UTF8;
2938 if (HEK_WASUTF8(hek))
2939 flags |= SHV_K_WASUTF8;
2945 * Keys are written after values to make sure retrieval
2946 * can be optimal in terms of memory usage, where keys are
2947 * read into a fixed unique buffer called kbuf.
2948 * See retrieve_hash() for details.
2953 TRACEME(("(#%d) key '%s' flags %x", (int)i, key, flags));
2955 /* This is a workaround for a bug in 5.8.0
2956 that causes the HEK_WASUTF8 flag to be
2957 set on an HEK without the hash being
2958 marked as having key flags. We just
2959 cross our fingers and drop the flag.
2961 assert (flags == 0 || flags == SHV_K_WASUTF8);
2962 TRACEME(("(#%d) key '%s'", (int)i, key));
2964 if (flags & SHV_K_ISSV) {
2966 if ((ret = store(aTHX_ cxt, key_sv)))
2977 TRACEME(("ok (hash 0x%" UVxf ")", PTR2UV(hv)));
2980 if (cxt->entry && cxt->recur_sv == (SV*)hv && cxt->recur_depth > 0) {
2981 TRACEME(("recur_depth --%u", cxt->recur_depth));
2984 HvRITER_set(hv, riter); /* Restore hash iterator state */
2985 HvEITER_set(hv, eiter);
2990 static int store_hentry(pTHX_
2991 stcxt_t *cxt, HV* hv, UV i, HE *he, unsigned char hash_flags)
2994 SV* val = hv_iterval(hv, he);
2995 int flagged_hash = ((SvREADONLY(hv)
2996 #ifdef HAS_HASH_KEY_FLAGS
3000 unsigned char flags = (((hash_flags & SHV_RESTRICTED)
3001 && SvTRULYREADONLY(val))
3002 ? SHV_K_LOCKED : 0);
3006 if (val == &PL_sv_placeholder) {
3007 flags |= SHV_K_PLACEHOLDER;
3012 * Store value first.
3015 TRACEME(("(#%d) value 0x%" UVxf, (int)i, PTR2UV(val)));
3018 HEK* hek = HeKEY_hek(he);
3019 I32 len = HEK_LEN(hek);
3023 if ((ret = store(aTHX_ cxt, val)))
3025 if (len == HEf_SVKEY) {
3026 key_sv = HeKEY_sv(he);
3027 flags |= SHV_K_ISSV;
3029 /* Regular string key. */
3030 #ifdef HAS_HASH_KEY_FLAGS
3032 flags |= SHV_K_UTF8;
3033 if (HEK_WASUTF8(hek))
3034 flags |= SHV_K_WASUTF8;
3040 * Keys are written after values to make sure retrieval
3041 * can be optimal in terms of memory usage, where keys are
3042 * read into a fixed unique buffer called kbuf.
3043 * See retrieve_hash() for details.
3048 TRACEME(("(#%d) key '%s' flags %x", (int)i, key, flags));
3050 /* This is a workaround for a bug in 5.8.0
3051 that causes the HEK_WASUTF8 flag to be
3052 set on an HEK without the hash being
3053 marked as having key flags. We just
3054 cross our fingers and drop the flag.
3056 assert (flags == 0 || flags == SHV_K_WASUTF8);
3057 TRACEME(("(#%d) key '%s'", (int)i, key));
3059 if (flags & SHV_K_ISSV) {
3060 if ((ret = store(aTHX_ cxt, key_sv)))
3076 * Store a overlong hash table, with >2G keys, which we cannot iterate
3077 * over with perl5. xhv_eiter is only I32 there. (only cperl can)
3078 * and we also do not want to sort it.
3079 * So we walk the buckets and chains manually.
3081 * type, len and flags are already written.
3084 static int store_lhash(pTHX_ stcxt_t *cxt, HV *hv, unsigned char hash_flags)
3092 UV len = (UV)HvTOTALKEYS(hv);
3095 TRACEME(("store_lhash (0x%" UVxf ") (flags %x)", PTR2UV(hv),
3098 TRACEME(("store_lhash (0x%" UVxf ")", PTR2UV(hv)));
3100 TRACEME(("size = %" UVuf ", used = %" UVuf, len, (UV)HvUSEDKEYS(hv)));
3102 TRACEME(("recur_depth %u, recur_sv (0x%" UVxf ")", cxt->recur_depth,
3103 PTR2UV(cxt->recur_sv)));
3104 if (cxt->entry && cxt->recur_sv == (SV*)hv) {
3105 if (++cxt->recur_depth > MAX_DEPTH_HASH) {
3106 #if PERL_VERSION < 15
3107 cleanup_recursive_data(aTHX_ (SV*)hv);
3109 CROAK((MAX_DEPTH_ERROR));
3112 cxt->recur_sv = (SV*)hv;
3114 array = HvARRAY(hv);
3115 for (i = 0; i <= (Size_t)HvMAX(hv); i++) {
3116 HE* entry = array[i];
3117 if (!entry) continue;
3118 if ((ret = store_hentry(aTHX_ cxt, hv, ix++, entry, hash_flags)))
3120 while ((entry = HeNEXT(entry))) {
3121 if ((ret = store_hentry(aTHX_ cxt, hv, ix++, entry, hash_flags)))
3125 if (cxt->entry && cxt->recur_sv == (SV*)hv && cxt->recur_depth > 0) {
3126 TRACEME(("recur_depth --%u", cxt->recur_depth));
3137 * Store a code reference.
3139 * Layout is SX_CODE <length> followed by a scalar containing the perl
3140 * source code of the code reference.
3142 static int store_code(pTHX_ stcxt_t *cxt, CV *cv)
3144 #if PERL_VERSION < 6
3146 * retrieve_code does not work with perl 5.005 or less
3148 return store_other(aTHX_ cxt, (SV*)cv);
3152 STRLEN count, reallen;
3153 SV *text, *bdeparse;
3155 TRACEME(("store_code (0x%" UVxf ")", PTR2UV(cv)));
3158 cxt->deparse == 0 ||
3159 (cxt->deparse < 0 &&
3161 SvTRUE(get_sv("Storable::Deparse", GV_ADD)) ? 1 : 0))
3163 return store_other(aTHX_ cxt, (SV*)cv);
3167 * Require B::Deparse. At least B::Deparse 0.61 is needed for
3168 * blessed code references.
3170 /* Ownership of both SVs is passed to load_module, which frees them. */
3171 load_module(PERL_LOADMOD_NOIMPORT, newSVpvs("B::Deparse"), newSVnv(0.61));
3178 * create the B::Deparse object
3182 XPUSHs(newSVpvs_flags("B::Deparse", SVs_TEMP));
3184 count = call_method("new", G_SCALAR);
3187 CROAK(("Unexpected return value from B::Deparse::new\n"));
3191 * call the coderef2text method
3195 XPUSHs(bdeparse); /* XXX is this already mortal? */
3196 XPUSHs(sv_2mortal(newRV_inc((SV*)cv)));
3198 count = call_method("coderef2text", G_SCALAR);
3201 CROAK(("Unexpected return value from B::Deparse::coderef2text\n"));
3205 reallen = strlen(SvPV_nolen(text));
3208 * Empty code references or XS functions are deparsed as
3209 * "(prototype) ;" or ";".
3212 if (len == 0 || *(SvPV_nolen(text)+reallen-1) == ';') {
3213 CROAK(("The result of B::Deparse::coderef2text was empty - maybe you're trying to serialize an XS function?\n"));
3217 * Signal code by emitting SX_CODE.
3221 cxt->tagnum++; /* necessary, as SX_CODE is a SEEN() candidate */
3222 TRACEME(("size = %d", (int)len));
3223 TRACEME(("code = %s", SvPV_nolen(text)));
3226 * Now store the source code.
3230 STORE_UTF8STR(SvPV_nolen(text), len);
3232 STORE_SCALAR(SvPV_nolen(text), len);
3237 TRACEME(("ok (code)"));
3246 * When storing a tied object (be it a tied scalar, array or hash), we lay out
3247 * a special mark, followed by the underlying tied object. For instance, when
3248 * dealing with a tied hash, we store SX_TIED_HASH <hash object>, where
3249 * <hash object> stands for the serialization of the tied hash.
3251 static int store_tied(pTHX_ stcxt_t *cxt, SV *sv)
3256 int svt = SvTYPE(sv);
3259 TRACEME(("store_tied (0x%" UVxf ")", PTR2UV(sv)));
3262 * We have a small run-time penalty here because we chose to factorise
3263 * all tieds objects into the same routine, and not have a store_tied_hash,
3264 * a store_tied_array, etc...
3266 * Don't use a switch() statement, as most compilers don't optimize that
3267 * well for 2/3 values. An if() else if() cascade is just fine. We put
3268 * tied hashes first, as they are the most likely beasts.
3271 if (svt == SVt_PVHV) {
3272 TRACEME(("tied hash"));
3273 PUTMARK(SX_TIED_HASH); /* Introduces tied hash */
3274 } else if (svt == SVt_PVAV) {
3275 TRACEME(("tied array"));
3276 PUTMARK(SX_TIED_ARRAY); /* Introduces tied array */
3278 TRACEME(("tied scalar"));
3279 PUTMARK(SX_TIED_SCALAR); /* Introduces tied scalar */
3283 if (!(mg = mg_find(sv, mtype)))
3284 CROAK(("No magic '%c' found while storing tied %s", mtype,
3285 (svt == SVt_PVHV) ? "hash" :
3286 (svt == SVt_PVAV) ? "array" : "scalar"));
3289 * The mg->mg_obj found by mg_find() above actually points to the
3290 * underlying tied Perl object implementation. For instance, if the
3291 * original SV was that of a tied array, then mg->mg_obj is an AV.
3293 * Note that we store the Perl object as-is. We don't call its FETCH
3294 * method along the way. At retrieval time, we won't call its STORE
3295 * method either, but the tieing magic will be re-installed. In itself,
3296 * that ensures that the tieing semantics are preserved since further
3297 * accesses on the retrieved object will indeed call the magic methods...
3300 /* [#17040] mg_obj is NULL for scalar self-ties. AMS 20030416 */
3301 obj = mg->mg_obj ? mg->mg_obj : newSV(0);
3302 if ((ret = store(aTHX_ cxt, obj)))
3305 TRACEME(("ok (tied)"));
3313 * Stores a reference to an item within a tied structure:
3315 * . \$h{key}, stores both the (tied %h) object and 'key'.
3316 * . \$a[idx], stores both the (tied @a) object and 'idx'.
3318 * Layout is therefore either:
3319 * SX_TIED_KEY <object> <key>
3320 * SX_TIED_IDX <object> <index>
3322 static int store_tied_item(pTHX_ stcxt_t *cxt, SV *sv)
3327 TRACEME(("store_tied_item (0x%" UVxf ")", PTR2UV(sv)));
3329 if (!(mg = mg_find(sv, 'p')))
3330 CROAK(("No magic 'p' found while storing reference to tied item"));
3333 * We discriminate between \$h{key} and \$a[idx] via mg_ptr.
3337 TRACEME(("store_tied_item: storing a ref to a tied hash item"));
3338 PUTMARK(SX_TIED_KEY);
3339 TRACEME(("store_tied_item: storing OBJ 0x%" UVxf, PTR2UV(mg->mg_obj)));
3341 if ((ret = store(aTHX_ cxt, mg->mg_obj))) /* Extra () for -Wall, grr... */
3344 TRACEME(("store_tied_item: storing PTR 0x%" UVxf, PTR2UV(mg->mg_ptr)));
3346 if ((ret = store(aTHX_ cxt, (SV *) mg->mg_ptr))) /* Idem, for -Wall */
3349 I32 idx = mg->mg_len;
3351 TRACEME(("store_tied_item: storing a ref to a tied array item "));
3352 PUTMARK(SX_TIED_IDX);
3353 TRACEME(("store_tied_item: storing OBJ 0x%" UVxf, PTR2UV(mg->mg_obj)));
3355 if ((ret = store(aTHX_ cxt, mg->mg_obj))) /* Idem, for -Wall */
3358 TRACEME(("store_tied_item: storing IDX %d", (int)idx));
3363 TRACEME(("ok (tied item)"));
3369 * store_hook -- dispatched manually, not via sv_store[]
3371 * The blessed SV is serialized by a hook.
3375 * SX_HOOK <flags> <len> <classname> <len2> <str> [<len3> <object-IDs>]
3377 * where <flags> indicates how long <len>, <len2> and <len3> are, whether
3378 * the trailing part [] is present, the type of object (scalar, array or hash).
3379 * There is also a bit which says how the classname is stored between:
3384 * and when the <index> form is used (classname already seen), the "large
3385 * classname" bit in <flags> indicates how large the <index> is.
3387 * The serialized string returned by the hook is of length <len2> and comes
3388 * next. It is an opaque string for us.
3390 * Those <len3> object IDs which are listed last represent the extra references
3391 * not directly serialized by the hook, but which are linked to the object.
3393 * When recursion is mandated to resolve object-IDs not yet seen, we have
3394 * instead, with <header> being flags with bits set to indicate the object type
3395 * and that recursion was indeed needed:
3397 * SX_HOOK <header> <object> <header> <object> <flags>
3399 * that same header being repeated between serialized objects obtained through
3400 * recursion, until we reach flags indicating no recursion, at which point
3401 * we know we've resynchronized with a single layout, after <flags>.
3403 * When storing a blessed ref to a tied variable, the following format is
3406 * SX_HOOK <flags> <extra> ... [<len3> <object-IDs>] <magic object>
3408 * The first <flags> indication carries an object of type SHT_EXTRA, and the
3409 * real object type is held in the <extra> flag. At the very end of the
3410 * serialization stream, the underlying magic object is serialized, just like
3411 * any other tied variable.
3413 static int store_hook(
3427 int count; /* really len3 + 1 */
3428 unsigned char flags;
3431 int recursed = 0; /* counts recursion */
3432 int obj_type; /* object type, on 2 bits */
3435 int clone = cxt->optype & ST_CLONE;
3436 char mtype = '\0'; /* for blessed ref to tied structures */
3437 unsigned char eflags = '\0'; /* used when object type is SHT_EXTRA */
3439 TRACEME(("store_hook, classname \"%s\", tagged #%d", HvNAME_get(pkg), (int)cxt->tagnum));
3442 * Determine object type on 2 bits.
3448 obj_type = SHT_SCALAR;
3451 obj_type = SHT_ARRAY;
3454 obj_type = SHT_HASH;
3458 * Produced by a blessed ref to a tied data structure, $o in the
3459 * following Perl code.
3463 * my $o = bless \%h, 'BAR';
3465 * Signal the tie-ing magic by setting the object type as SHT_EXTRA
3466 * (since we have only 2 bits in <flags> to store the type), and an
3467 * <extra> byte flag will be emitted after the FIRST <flags> in the
3468 * stream, carrying what we put in 'eflags'.
3470 obj_type = SHT_EXTRA;
3471 switch (SvTYPE(sv)) {
3473 eflags = (unsigned char) SHT_THASH;
3477 eflags = (unsigned char) SHT_TARRAY;
3481 eflags = (unsigned char) SHT_TSCALAR;
3487 CROAK(("Unexpected object type (%d) in store_hook()", type));
3489 flags = SHF_NEED_RECURSE | obj_type;
3491 classname = HvNAME_get(pkg);
3492 len = strlen(classname);
3495 * To call the hook, we need to fake a call like:
3497 * $object->STORABLE_freeze($cloning);
3499 * but we don't have the $object here. For instance, if $object is
3500 * a blessed array, what we have in 'sv' is the array, and we can't
3501 * call a method on those.
3503 * Therefore, we need to create a temporary reference to the object and
3504 * make the call on that reference.
3507 TRACEME(("about to call STORABLE_freeze on class %s", classname));
3509 ref = newRV_inc(sv); /* Temporary reference */
3510 av = array_call(aTHX_ ref, hook, clone); /* @a = $object->STORABLE_freeze($c) */
3511 SvREFCNT_dec(ref); /* Reclaim temporary reference */
3513 count = AvFILLp(av) + 1;
3514 TRACEME(("store_hook, array holds %d items", count));
3517 * If they return an empty list, it means they wish to ignore the
3518 * hook for this class (and not just this instance -- that's for them
3519 * to handle if they so wish).
3521 * Simply disable the cached entry for the hook (it won't be recomputed
3522 * since it's present in the cache) and recurse to store_blessed().
3526 /* free empty list returned by the hook */
3531 * They must not change their mind in the middle of a serialization.
3534 if (hv_fetch(cxt->hclass, classname, len, FALSE))
3535 CROAK(("Too late to ignore hooks for %s class \"%s\"",
3536 (cxt->optype & ST_CLONE) ? "cloning" : "storing",
3539 pkg_hide(aTHX_ cxt->hook, pkg, "STORABLE_freeze");
3541 ASSERT(!pkg_can(aTHX_ cxt->hook, pkg, "STORABLE_freeze"),
3542 ("hook invisible"));
3543 TRACEME(("ignoring STORABLE_freeze in class \"%s\"", classname));
3545 return store_blessed(aTHX_ cxt, sv, type, pkg);
3549 * Get frozen string.
3553 pv = SvPV(ary[0], len2);
3554 /* We can't use pkg_can here because it only caches one method per
3557 GV* gv = gv_fetchmethod_autoload(pkg, "STORABLE_attach", FALSE);
3558 if (gv && isGV(gv)) {
3560 CROAK(("Freeze cannot return references if %s class is using STORABLE_attach", classname));
3566 * If they returned more than one item, we need to serialize some
3567 * extra references if not already done.
3569 * Loop over the array, starting at position #1, and for each item,
3570 * ensure it is a reference, serialize it if not already done, and
3571 * replace the entry with the tag ID of the corresponding serialized
3574 * We CHEAT by not calling av_fetch() and read directly within the
3578 for (i = 1; i < count; i++) {
3579 #ifdef USE_PTR_TABLE
3587 AV *av_hook = cxt->hook_seen;
3590 CROAK(("Item #%d returned by STORABLE_freeze "
3591 "for %s is not a reference", (int)i, classname));
3592 xsv = SvRV(rsv); /* Follow ref to know what to look for */
3595 * Look in hseen and see if we have a tag already.
3596 * Serialize entry if not done already, and get its tag.
3599 #ifdef USE_PTR_TABLE
3600 /* Fakery needed because ptr_table_fetch returns zero for a
3601 failure, whereas the existing code assumes that it can
3602 safely store a tag zero. So for ptr_tables we store tag+1
3604 if ((fake_tag = (char *)ptr_table_fetch(cxt->pseen, xsv)))
3605 goto sv_seen; /* Avoid moving code too far to the right */
3607 if ((svh = hv_fetch(cxt->hseen, (char *) &xsv, sizeof(xsv), FALSE)))
3608 goto sv_seen; /* Avoid moving code too far to the right */
3611 TRACEME(("listed object %d at 0x%" UVxf " is unknown", i-1,
3615 * We need to recurse to store that object and get it to be known
3616 * so that we can resolve the list of object-IDs at retrieve time.
3618 * The first time we do this, we need to emit the proper header
3619 * indicating that we recursed, and what the type of object is (the
3620 * object we're storing via a user-hook). Indeed, during retrieval,
3621 * we'll have to create the object before recursing to retrieve the
3622 * others, in case those would point back at that object.
3625 /* [SX_HOOK] <flags> [<extra>] <object>*/
3629 if (obj_type == SHT_EXTRA)
3634 if ((ret = store(aTHX_ cxt, xsv))) /* Given by hook for us to store */
3637 #ifdef USE_PTR_TABLE
3638 fake_tag = (char *)ptr_table_fetch(cxt->pseen, xsv);
3640 CROAK(("Could not serialize item #%d from hook in %s",
3641 (int)i, classname));
3643 svh = hv_fetch(cxt->hseen, (char *) &xsv, sizeof(xsv), FALSE);
3645 CROAK(("Could not serialize item #%d from hook in %s",
3646 (int)i, classname));
3649 * It was the first time we serialized 'xsv'.
3651 * Keep this SV alive until the end of the serialization: if we
3652 * disposed of it right now by decrementing its refcount, and it was
3653 * a temporary value, some next temporary value allocated during
3654 * another STORABLE_freeze might take its place, and we'd wrongly
3655 * assume that new SV was already serialized, based on its presence
3658 * Therefore, push it away in cxt->hook_seen.
3661 av_store(av_hook, AvFILLp(av_hook)+1, SvREFCNT_inc(xsv));
3665 * Dispose of the REF they returned. If we saved the 'xsv' away
3666 * in the array of returned SVs, that will not cause the underlying
3667 * referenced SV to be reclaimed.
3670 ASSERT(SvREFCNT(xsv) > 1, ("SV will survive disposal of its REF"));
3671 SvREFCNT_dec(rsv); /* Dispose of reference */
3674 * Replace entry with its tag (not a real SV, so no refcnt increment)
3677 #ifdef USE_PTR_TABLE
3678 tag = (SV *)--fake_tag;
3683 TRACEME(("listed object %d at 0x%" UVxf " is tag #%" UVuf,
3684 i-1, PTR2UV(xsv), PTR2UV(tag)));
3688 * Allocate a class ID if not already done.
3690 * This needs to be done after the recursion above, since at retrieval
3691 * time, we'll see the inner objects first. Many thanks to
3692 * Salvador Ortiz Garcia <sog@msg.com.mx> who spot that bug and
3693 * proposed the right fix. -- RAM, 15/09/2000
3697 if (!known_class(aTHX_ cxt, classname, len, &classnum)) {
3698 TRACEME(("first time we see class %s, ID = %d", classname, (int)classnum));
3699 classnum = -1; /* Mark: we must store classname */
3701 TRACEME(("already seen class %s, ID = %d", classname, (int)classnum));
3705 * Compute leading flags.
3709 if (((classnum == -1) ? len : classnum) > LG_SCALAR)
3710 flags |= SHF_LARGE_CLASSLEN;
3712 flags |= SHF_IDX_CLASSNAME;
3713 if (len2 > LG_SCALAR)
3714 flags |= SHF_LARGE_STRLEN;
3716 flags |= SHF_HAS_LIST;
3717 if (count > (LG_SCALAR + 1))
3718 flags |= SHF_LARGE_LISTLEN;
3721 * We're ready to emit either serialized form:
3723 * SX_HOOK <flags> <len> <classname> <len2> <str> [<len3> <object-IDs>]
3724 * SX_HOOK <flags> <index> <len2> <str> [<len3> <object-IDs>]
3726 * If we recursed, the SX_HOOK has already been emitted.
3729 TRACEME(("SX_HOOK (recursed=%d) flags=0x%x "
3730 "class=%" IVdf " len=%" IVdf " len2=%" IVdf " len3=%d",
3731 recursed, flags, (IV)classnum, (IV)len, (IV)len2, count-1));
3733 /* SX_HOOK <flags> [<extra>] */
3737 if (obj_type == SHT_EXTRA)
3742 /* <len> <classname> or <index> */
3743 if (flags & SHF_IDX_CLASSNAME) {
3744 if (flags & SHF_LARGE_CLASSLEN)
3747 unsigned char cnum = (unsigned char) classnum;
3751 if (flags & SHF_LARGE_CLASSLEN)
3754 unsigned char clen = (unsigned char) len;
3757 WRITE(classname, len); /* Final \0 is omitted */
3760 /* <len2> <frozen-str> */
3761 if (flags & SHF_LARGE_STRLEN) {
3762 I32 wlen2 = len2; /* STRLEN might be 8 bytes */
3763 WLEN(wlen2); /* Must write an I32 for 64-bit machines */
3765 unsigned char clen = (unsigned char) len2;
3769 WRITE(pv, (SSize_t)len2); /* Final \0 is omitted */
3771 /* [<len3> <object-IDs>] */
3772 if (flags & SHF_HAS_LIST) {
3773 int len3 = count - 1;
3774 if (flags & SHF_LARGE_LISTLEN)
3777 unsigned char clen = (unsigned char) len3;
3782 * NOTA BENE, for 64-bit machines: the ary[i] below does not yield a
3783 * real pointer, rather a tag number, well under the 32-bit limit.
3786 for (i = 1; i < count; i++) {
3787 I32 tagval = htonl(LOW_32BITS(ary[i]));
3789 TRACEME(("object %d, tag #%d", i-1, ntohl(tagval)));
3794 * Free the array. We need extra care for indices after 0, since they
3795 * don't hold real SVs but integers cast.
3799 AvFILLp(av) = 0; /* Cheat, nothing after 0 interests us */
3804 * If object was tied, need to insert serialization of the magic object.
3807 if (obj_type == SHT_EXTRA) {
3810 if (!(mg = mg_find(sv, mtype))) {
3811 int svt = SvTYPE(sv);
3812 CROAK(("No magic '%c' found while storing ref to tied %s with hook",
3813 mtype, (svt == SVt_PVHV) ? "hash" :
3814 (svt == SVt_PVAV) ? "array" : "scalar"));
3817 TRACEME(("handling the magic object 0x%" UVxf " part of 0x%" UVxf,
3818 PTR2UV(mg->mg_obj), PTR2UV(sv)));
3823 if ((ret = store(aTHX_ cxt, mg->mg_obj)))
3831 * store_blessed -- dispatched manually, not via sv_store[]
3833 * Check whether there is a STORABLE_xxx hook defined in the class or in one
3834 * of its ancestors. If there is, then redispatch to store_hook();
3836 * Otherwise, the blessed SV is stored using the following layout:
3838 * SX_BLESS <flag> <len> <classname> <object>
3840 * where <flag> indicates whether <len> is stored on 0 or 4 bytes, depending
3841 * on the high-order bit in flag: if 1, then length follows on 4 bytes.
3842 * Otherwise, the low order bits give the length, thereby giving a compact
3843 * representation for class names less than 127 chars long.
3845 * Each <classname> seen is remembered and indexed, so that the next time
3846 * an object in the blessed in the same <classname> is stored, the following
3849 * SX_IX_BLESS <flag> <index> <object>
3851 * where <index> is the classname index, stored on 0 or 4 bytes depending
3852 * on the high-order bit in flag (same encoding as above for <len>).
3854 static int store_blessed(
3866 TRACEME(("store_blessed, type %d, class \"%s\"", type, HvNAME_get(pkg)));
3869 * Look for a hook for this blessed SV and redirect to store_hook()
3873 hook = pkg_can(aTHX_ cxt->hook, pkg, "STORABLE_freeze");
3875 return store_hook(aTHX_ cxt, sv, type, pkg, hook);
3878 * This is a blessed SV without any serialization hook.
3881 classname = HvNAME_get(pkg);
3882 len = strlen(classname);
3884 TRACEME(("blessed 0x%" UVxf " in %s, no hook: tagged #%d",
3885 PTR2UV(sv), classname, (int)cxt->tagnum));
3888 * Determine whether it is the first time we see that class name (in which
3889 * case it will be stored in the SX_BLESS form), or whether we already
3890 * saw that class name before (in which case the SX_IX_BLESS form will be
3894 if (known_class(aTHX_ cxt, classname, len, &classnum)) {
3895 TRACEME(("already seen class %s, ID = %d", classname, (int)classnum));
3896 PUTMARK(SX_IX_BLESS);
3897 if (classnum <= LG_BLESS) {
3898 unsigned char cnum = (unsigned char) classnum;
3901 unsigned char flag = (unsigned char) 0x80;
3906 TRACEME(("first time we see class %s, ID = %d", classname,
3909 if (len <= LG_BLESS) {
3910 unsigned char clen = (unsigned char) len;
3913 unsigned char flag = (unsigned char) 0x80;
3915 WLEN(len); /* Don't BER-encode, this should be rare */
3917 WRITE(classname, len); /* Final \0 is omitted */
3921 * Now emit the <object> part.
3924 return SV_STORE(type)(aTHX_ cxt, sv);
3930 * We don't know how to store the item we reached, so return an error condition.
3931 * (it's probably a GLOB, some CODE reference, etc...)
3933 * If they defined the 'forgive_me' variable at the Perl level to some
3934 * true value, then don't croak, just warn, and store a placeholder string
3937 static int store_other(pTHX_ stcxt_t *cxt, SV *sv)
3942 TRACEME(("store_other"));
3945 * Fetch the value from perl only once per store() operation.
3949 cxt->forgive_me == 0 ||
3950 (cxt->forgive_me < 0 &&
3951 !(cxt->forgive_me = SvTRUE
3952 (get_sv("Storable::forgive_me", GV_ADD)) ? 1 : 0))
3954 CROAK(("Can't store %s items", sv_reftype(sv, FALSE)));
3956 warn("Can't store item %s(0x%" UVxf ")",
3957 sv_reftype(sv, FALSE), PTR2UV(sv));
3960 * Store placeholder string as a scalar instead...
3963 (void) sprintf(buf, "You lost %s(0x%" UVxf ")%c", sv_reftype(sv, FALSE),
3964 PTR2UV(sv), (char) 0);
3968 STORE_SCALAR(buf, len);
3969 TRACEME(("ok (dummy \"%s\", length = %" IVdf ")", buf, (IV) len));
3975 *** Store driving routines
3981 * WARNING: partially duplicates Perl's sv_reftype for speed.
3983 * Returns the type of the SV, identified by an integer. That integer
3984 * may then be used to index the dynamic routine dispatch table.
3986 static int sv_type(pTHX_ SV *sv)
3988 switch (SvTYPE(sv)) {
3990 #if PERL_VERSION <= 10
3995 * No need to check for ROK, that can't be set here since there
3996 * is no field capable of hodling the xrv_rv reference.
4000 #if PERL_VERSION <= 10
4008 * Starting from SVt_PV, it is possible to have the ROK flag
4009 * set, the pointer to the other SV being either stored in
4010 * the xrv_rv (in the case of a pure SVt_RV), or as the
4011 * xpv_pv field of an SVt_PV and its heirs.
4013 * However, those SV cannot be magical or they would be an
4014 * SVt_PVMG at least.
4016 return SvROK(sv) ? svis_REF : svis_SCALAR;
4018 case SVt_PVLV: /* Workaround for perl5.004_04 "LVALUE" bug */
4019 if ((SvFLAGS(sv) & (SVs_GMG|SVs_SMG|SVs_RMG)) ==
4020 (SVs_GMG|SVs_SMG|SVs_RMG) &&
4022 return svis_TIED_ITEM;
4024 #if PERL_VERSION < 9
4027 if ((SvFLAGS(sv) & (SVs_GMG|SVs_SMG|SVs_RMG)) ==
4028 (SVs_GMG|SVs_SMG|SVs_RMG) &&
4031 return SvROK(sv) ? svis_REF : svis_SCALAR;
4033 if (SvRMAGICAL(sv) && (mg_find(sv, 'P')))
4037 if (SvRMAGICAL(sv) && (mg_find(sv, 'P')))
4042 #if PERL_VERSION > 8
4043 /* case SVt_INVLIST: */
4055 * Recursively store objects pointed to by the sv to the specified file.
4057 * Layout is <content> or SX_OBJECT <tagnum> if we reach an already stored
4058 * object (one for which storage has started -- it may not be over if we have
4059 * a self-referenced structure). This data set forms a stored <object>.
4061 static int store(pTHX_ stcxt_t *cxt, SV *sv)
4066 #ifdef USE_PTR_TABLE
4067 struct ptr_tbl *pseen = cxt->pseen;
4069 HV *hseen = cxt->hseen;
4072 TRACEME(("store (0x%" UVxf ")", PTR2UV(sv)));
4075 * If object has already been stored, do not duplicate data.
4076 * Simply emit the SX_OBJECT marker followed by its tag data.
4077 * The tag is always written in network order.
4079 * NOTA BENE, for 64-bit machines: the "*svh" below does not yield a
4080 * real pointer, rather a tag number (watch the insertion code below).
4081 * That means it probably safe to assume it is well under the 32-bit
4082 * limit, and makes the truncation safe.
4083 * -- RAM, 14/09/1999
4086 #ifdef USE_PTR_TABLE
4087 svh = (SV **)ptr_table_fetch(pseen, sv);
4089 svh = hv_fetch(hseen, (char *) &sv, sizeof(sv), FALSE);
4094 if (sv == &PL_sv_undef) {
4095 /* We have seen PL_sv_undef before, but fake it as
4098 Not the simplest solution to making restricted
4099 hashes work on 5.8.0, but it does mean that
4100 repeated references to the one true undef will
4101 take up less space in the output file.
4103 /* Need to jump past the next hv_store, because on the
4104 second store of undef the old hash value will be
4105 SvREFCNT_dec()ed, and as Storable cheats horribly
4106 by storing non-SVs in the hash a SEGV will ensure.
4107 Need to increase the tag number so that the
4108 receiver has no idea what games we're up to. This
4109 special casing doesn't affect hooks that store
4110 undef, as the hook routine does its own lookup into
4111 hseen. Also this means that any references back
4112 to PL_sv_undef (from the pathological case of hooks
4113 storing references to it) will find the seen hash
4114 entry for the first time, as if we didn't have this
4115 hackery here. (That hseen lookup works even on 5.8.0
4116 because it's a key of &PL_sv_undef and a value
4117 which is a tag number, not a value which is
4121 goto undef_special_case;
4124 #ifdef USE_PTR_TABLE
4125 tagval = htonl(LOW_32BITS(((char *)svh)-1));
4127 tagval = htonl(LOW_32BITS(*svh));
4130 TRACEME(("object 0x%" UVxf " seen as #%d", PTR2UV(sv),
4139 * Allocate a new tag and associate it with the address of the sv being
4140 * stored, before recursing...
4142 * In order to avoid creating new SvIVs to hold the tagnum we just
4143 * cast the tagnum to an SV pointer and store that in the hash. This
4144 * means that we must clean up the hash manually afterwards, but gives
4145 * us a 15% throughput increase.
4150 #ifdef USE_PTR_TABLE
4151 ptr_table_store(pseen, sv, INT2PTR(SV*, 1 + cxt->tagnum));
4153 if (!hv_store(hseen,
4154 (char *) &sv, sizeof(sv), INT2PTR(SV*, cxt->tagnum), 0))
4159 * Store 'sv' and everything beneath it, using appropriate routine.
4160 * Abort immediately if we get a non-zero status back.
4163 type = sv_type(aTHX_ sv);
4166 TRACEME(("storing 0x%" UVxf " tag #%d, type %d...",
4167 PTR2UV(sv), (int)cxt->tagnum, (int)type));
4170 HV *pkg = SvSTASH(sv);
4171 ret = store_blessed(aTHX_ cxt, sv, type, pkg);
4173 ret = SV_STORE(type)(aTHX_ cxt, sv);
4175 TRACEME(("%s (stored 0x%" UVxf ", refcnt=%d, %s)",
4176 ret ? "FAILED" : "ok", PTR2UV(sv),
4177 (int)SvREFCNT(sv), sv_reftype(sv, FALSE)));
4185 * Write magic number and system information into the file.
4186 * Layout is <magic> <network> [<len> <byteorder> <sizeof int> <sizeof long>
4187 * <sizeof ptr>] where <len> is the length of the byteorder hexa string.
4188 * All size and lengths are written as single characters here.
4190 * Note that no byte ordering info is emitted when <network> is true, since
4191 * integers will be emitted in network order in that case.
4193 static int magic_write(pTHX_ stcxt_t *cxt)
4196 * Starting with 0.6, the "use_network_order" byte flag is also used to
4197 * indicate the version number of the binary image, encoded in the upper
4198 * bits. The bit 0 is always used to indicate network order.
4201 * Starting with 0.7, a full byte is dedicated to the minor version of
4202 * the binary format, which is incremented only when new markers are
4203 * introduced, for instance, but when backward compatibility is preserved.
4206 /* Make these at compile time. The WRITE() macro is sufficiently complex
4207 that it saves about 200 bytes doing it this way and only using it
4209 static const unsigned char network_file_header[] = {
4211 (STORABLE_BIN_MAJOR << 1) | 1,
4212 STORABLE_BIN_WRITE_MINOR
4214 static const unsigned char file_header[] = {
4216 (STORABLE_BIN_MAJOR << 1) | 0,
4217 STORABLE_BIN_WRITE_MINOR,
4218 /* sizeof the array includes the 0 byte at the end: */
4219 (char) sizeof (byteorderstr) - 1,
4221 (unsigned char) sizeof(int),
4222 (unsigned char) sizeof(long),
4223 (unsigned char) sizeof(char *),
4224 (unsigned char) sizeof(NV)
4226 #ifdef USE_56_INTERWORK_KLUDGE
4227 static const unsigned char file_header_56[] = {
4229 (STORABLE_BIN_MAJOR << 1) | 0,
4230 STORABLE_BIN_WRITE_MINOR,
4231 /* sizeof the array includes the 0 byte at the end: */
4232 (char) sizeof (byteorderstr_56) - 1,
4234 (unsigned char) sizeof(int),
4235 (unsigned char) sizeof(long),
4236 (unsigned char) sizeof(char *),
4237 (unsigned char) sizeof(NV)
4240 const unsigned char *header;
4243 TRACEME(("magic_write on fd=%d", cxt->fio ? PerlIO_fileno(cxt->fio) : -1));
4245 if (cxt->netorder) {
4246 header = network_file_header;
4247 length = sizeof (network_file_header);
4249 #ifdef USE_56_INTERWORK_KLUDGE
4250 if (SvTRUE(get_sv("Storable::interwork_56_64bit", GV_ADD))) {
4251 header = file_header_56;
4252 length = sizeof (file_header_56);
4256 header = file_header;
4257 length = sizeof (file_header);
4262 /* sizeof the array includes the 0 byte at the end. */
4263 header += sizeof (magicstr) - 1;
4264 length -= sizeof (magicstr) - 1;
4267 WRITE( (unsigned char*) header, length);
4269 if (!cxt->netorder) {
4270 TRACEME(("ok (magic_write byteorder = 0x%lx [%d], I%d L%d P%d D%d)",
4271 (unsigned long) BYTEORDER, (int) sizeof (byteorderstr) - 1,
4272 (int) sizeof(int), (int) sizeof(long),
4273 (int) sizeof(char *), (int) sizeof(NV)));
4281 * Common code for store operations.
4283 * When memory store is requested (f = NULL) and a non null SV* is given in
4284 * 'res', it is filled with a new SV created out of the memory buffer.
4286 * It is required to provide a non-null 'res' when the operation type is not
4287 * dclone() and store() is performed to memory.
4289 static int do_store(pTHX_
4299 ASSERT(!(f == 0 && !(optype & ST_CLONE)) || res,
4300 ("must supply result SV pointer for real recursion to memory"));
4302 TRACEME(("do_store (optype=%d, netorder=%d)",
4303 optype, network_order));
4308 * Workaround for CROAK leak: if they enter with a "dirty" context,
4309 * free up memory for them now.
4314 clean_context(aTHX_ cxt);
4317 * Now that STORABLE_xxx hooks exist, it is possible that they try to
4318 * re-enter store() via the hooks. We need to stack contexts.
4322 cxt = allocate_context(aTHX_ cxt);
4326 ASSERT(cxt->entry == 1, ("starting new recursion"));
4327 ASSERT(!cxt->s_dirty, ("clean context"));
4330 * Ensure sv is actually a reference. From perl, we called something
4332 * pstore(aTHX_ FILE, \@array);
4333 * so we must get the scalar value behind that reference.
4337 CROAK(("Not a reference"));
4338 sv = SvRV(sv); /* So follow it to know what to store */
4341 * If we're going to store to memory, reset the buffer.
4348 * Prepare context and emit headers.
4351 init_store_context(aTHX_ cxt, f, optype, network_order);
4353 if (-1 == magic_write(aTHX_ cxt)) /* Emit magic and ILP info */
4354 return 0; /* Error */
4357 * Recursively store object...
4360 ASSERT(is_storing(aTHX), ("within store operation"));
4362 status = store(aTHX_ cxt, sv); /* Just do it! */
4365 * If they asked for a memory store and they provided an SV pointer,
4366 * make an SV string out of the buffer and fill their pointer.
4368 * When asking for ST_REAL, it's MANDATORY for the caller to provide
4369 * an SV, since context cleanup might free the buffer if we did recurse.
4370 * (unless caller is dclone(), which is aware of that).
4373 if (!cxt->fio && res)
4374 *res = mbuf2sv(aTHX);
4379 * The "root" context is never freed, since it is meant to be always
4380 * handy for the common case where no recursion occurs at all (i.e.
4381 * we enter store() outside of any Storable code and leave it, period).
4382 * We know it's the "root" context because there's nothing stacked
4387 * When deep cloning, we don't free the context: doing so would force
4388 * us to copy the data in the memory buffer. Sicne we know we're
4389 * about to enter do_retrieve...
4392 clean_store_context(aTHX_ cxt);
4393 if (cxt->prev && !(cxt->optype & ST_CLONE))
4394 free_context(aTHX_ cxt);
4396 TRACEME(("do_store returns %d", status));
4408 * Build a new SV out of the content of the internal memory buffer.
4410 static SV *mbuf2sv(pTHX)
4415 return newSVpv(mbase, MBUF_SIZE());
4419 *** Specific retrieve callbacks.
4425 * Return an error via croak, since it is not possible that we get here
4426 * under normal conditions, when facing a file produced via pstore().
4428 static SV *retrieve_other(pTHX_ stcxt_t *cxt, const char *cname)
4430 PERL_UNUSED_ARG(cname);
4432 cxt->ver_major != STORABLE_BIN_MAJOR &&
4433 cxt->ver_minor != STORABLE_BIN_MINOR
4435 CROAK(("Corrupted storable %s (binary v%d.%d), current is v%d.%d",
4436 cxt->fio ? "file" : "string",
4437 cxt->ver_major, cxt->ver_minor,
4438 STORABLE_BIN_MAJOR, STORABLE_BIN_MINOR));
4440 CROAK(("Corrupted storable %s (binary v%d.%d)",
4441 cxt->fio ? "file" : "string",
4442 cxt->ver_major, cxt->ver_minor));
4445 return (SV *) 0; /* Just in case */
4449 * retrieve_idx_blessed
4451 * Layout is SX_IX_BLESS <index> <object> with SX_IX_BLESS already read.
4452 * <index> can be coded on either 1 or 5 bytes.
4454 static SV *retrieve_idx_blessed(pTHX_ stcxt_t *cxt, const char *cname)
4457 const char *classname;
4461 PERL_UNUSED_ARG(cname);
4462 TRACEME(("retrieve_idx_blessed (#%d)", (int)cxt->tagnum));
4463 ASSERT(!cname, ("no bless-into class given here, got %s", cname));
4465 GETMARK(idx); /* Index coded on a single char? */
4470 * Fetch classname in 'aclass'
4473 sva = av_fetch(cxt->aclass, idx, FALSE);
4475 CROAK(("Class name #%" IVdf " should have been seen already",
4478 classname = SvPVX(*sva); /* We know it's a PV, by construction */
4480 TRACEME(("class ID %d => %s", (int)idx, classname));
4483 * Retrieve object and bless it.
4486 sv = retrieve(aTHX_ cxt, classname); /* First SV which is SEEN
4495 * Layout is SX_BLESS <len> <classname> <object> with SX_BLESS already read.
4496 * <len> can be coded on either 1 or 5 bytes.
4498 static SV *retrieve_blessed(pTHX_ stcxt_t *cxt, const char *cname)
4502 char buf[LG_BLESS + 1]; /* Avoid malloc() if possible */
4503 char *classname = buf;
4504 char *malloced_classname = NULL;
4506 PERL_UNUSED_ARG(cname);
4507 TRACEME(("retrieve_blessed (#%d)", (int)cxt->tagnum));
4508 ASSERT(!cname, ("no bless-into class given here, got %s", cname));
4511 * Decode class name length and read that name.
4513 * Short classnames have two advantages: their length is stored on one
4514 * single byte, and the string can be read on the stack.
4517 GETMARK(len); /* Length coded on a single char? */
4520 TRACEME(("** allocating %ld bytes for class name", (long)len+1));
4522 CROAK(("Corrupted classname length %lu", (long)len));
4523 PL_nomemok = TRUE; /* handle error by ourselves */
4524 New(10003, classname, len+1, char);
4527 CROAK(("Out of memory with len %ld", (long)len));
4529 malloced_classname = classname;
4531 SAFEPVREAD(classname, (I32)len, malloced_classname);
4532 classname[len] = '\0'; /* Mark string end */
4535 * It's a new classname, otherwise it would have been an SX_IX_BLESS.
4538 TRACEME(("new class name \"%s\" will bear ID = %d", classname,
4539 (int)cxt->classnum));
4541 if (!av_store(cxt->aclass, cxt->classnum++, newSVpvn(classname, len))) {
4542 Safefree(malloced_classname);
4547 * Retrieve object and bless it.
4550 sv = retrieve(aTHX_ cxt, classname); /* First SV which is SEEN will be blessed */
4551 if (malloced_classname)
4552 Safefree(malloced_classname);
4560 * Layout: SX_HOOK <flags> <len> <classname> <len2> <str> [<len3> <object-IDs>]
4561 * with leading mark already read, as usual.
4563 * When recursion was involved during serialization of the object, there
4564 * is an unknown amount of serialized objects after the SX_HOOK mark. Until
4565 * we reach a <flags> marker with the recursion bit cleared.
4567 * If the first <flags> byte contains a type of SHT_EXTRA, then the real type
4568 * is held in the <extra> byte, and if the object is tied, the serialized
4569 * magic object comes at the very end:
4571 * SX_HOOK <flags> <extra> ... [<len3> <object-IDs>] <magic object>
4573 * This means the STORABLE_thaw hook will NOT get a tied variable during its
4574 * processing (since we won't have seen the magic object by the time the hook
4575 * is called). See comments below for why it was done that way.
4577 static SV *retrieve_hook(pTHX_ stcxt_t *cxt, const char *cname)
4580 char buf[LG_BLESS + 1]; /* Avoid malloc() if possible */
4581 char *classname = buf;
4593 int clone = cxt->optype & ST_CLONE;
4595 unsigned int extra_type = 0;
4597 PERL_UNUSED_ARG(cname);
4598 TRACEME(("retrieve_hook (#%d)", (int)cxt->tagnum));
4599 ASSERT(!cname, ("no bless-into class given here, got %s", cname));
4602 * Read flags, which tell us about the type, and whether we need
4609 * Create the (empty) object, and mark it as seen.
4611 * This must be done now, because tags are incremented, and during
4612 * serialization, the object tag was affected before recursion could
4616 obj_type = flags & SHF_TYPE_MASK;
4622 sv = (SV *) newAV();
4625 sv = (SV *) newHV();
4629 * Read <extra> flag to know the type of the object.
4630 * Record associated magic type for later.
4632 GETMARK(extra_type);
4633 switch (extra_type) {
4639 sv = (SV *) newAV();
4643 sv = (SV *) newHV();
4647 return retrieve_other(aTHX_ cxt, 0);/* Let it croak */
4651 return retrieve_other(aTHX_ cxt, 0); /* Let it croak */
4653 SEEN0_NN(sv, 0); /* Don't bless yet */
4656 * Whilst flags tell us to recurse, do so.
4658 * We don't need to remember the addresses returned by retrieval, because
4659 * all the references will be obtained through indirection via the object
4660 * tags in the object-ID list.
4662 * We need to decrement the reference count for these objects
4663 * because, if the user doesn't save a reference to them in the hook,
4664 * they must be freed when this context is cleaned.
4667 while (flags & SHF_NEED_RECURSE) {
4668 TRACEME(("retrieve_hook recursing..."));
4669 rv = retrieve(aTHX_ cxt, 0);
4673 TRACEME(("retrieve_hook back with rv=0x%" UVxf,
4678 if (flags & SHF_IDX_CLASSNAME) {
4683 * Fetch index from 'aclass'
4686 if (flags & SHF_LARGE_CLASSLEN)
4691 sva = av_fetch(cxt->aclass, idx, FALSE);
4693 CROAK(("Class name #%" IVdf " should have been seen already",
4696 classname = SvPVX(*sva); /* We know it's a PV, by construction */
4697 TRACEME(("class ID %d => %s", (int)idx, classname));
4701 * Decode class name length and read that name.
4703 * NOTA BENE: even if the length is stored on one byte, we don't read
4704 * on the stack. Just like retrieve_blessed(), we limit the name to
4705 * LG_BLESS bytes. This is an arbitrary decision.
4707 char *malloced_classname = NULL;
4709 if (flags & SHF_LARGE_CLASSLEN)
4714 TRACEME(("** allocating %ld bytes for class name", (long)len+1));
4715 if (len > I32_MAX) /* security */
4716 CROAK(("Corrupted classname length %lu", (long)len));
4717 else if (len > LG_BLESS) { /* security: signed len */
4718 PL_nomemok = TRUE; /* handle error by ourselves */
4719 New(10003, classname, len+1, char);
4722 CROAK(("Out of memory with len %u", (unsigned)len+1));
4723 malloced_classname = classname;
4726 SAFEPVREAD(classname, (I32)len, malloced_classname);
4727 classname[len] = '\0'; /* Mark string end */
4730 * Record new classname.
4733 if (!av_store(cxt->aclass, cxt->classnum++,
4734 newSVpvn(classname, len))) {
4735 Safefree(malloced_classname);
4740 TRACEME(("class name: %s", classname));
4743 * Decode user-frozen string length and read it in an SV.
4745 * For efficiency reasons, we read data directly into the SV buffer.
4746 * To understand that code, read retrieve_scalar()
4749 if (flags & SHF_LARGE_STRLEN)
4754 frozen = NEWSV(10002, len2);
4756 SAFEREAD(SvPVX(frozen), len2, frozen);
4757 SvCUR_set(frozen, len2);
4758 *SvEND(frozen) = '\0';
4760 (void) SvPOK_only(frozen); /* Validates string pointer */
4761 if (cxt->s_tainted) /* Is input source tainted? */
4764 TRACEME(("frozen string: %d bytes", (int)len2));
4767 * Decode object-ID list length, if present.
4770 if (flags & SHF_HAS_LIST) {
4771 if (flags & SHF_LARGE_LISTLEN)
4777 av_extend(av, len3 + 1); /* Leave room for [0] */
4778 AvFILLp(av) = len3; /* About to be filled anyway */
4782 TRACEME(("has %d object IDs to link", (int)len3));
4785 * Read object-ID list into array.
4786 * Because we pre-extended it, we can cheat and fill it manually.
4788 * We read object tags and we can convert them into SV* on the fly
4789 * because we know all the references listed in there (as tags)
4790 * have been already serialized, hence we have a valid correspondence
4791 * between each of those tags and the recreated SV.
4795 SV **ary = AvARRAY(av);
4797 for (i = 1; i <= len3; i++) { /* We leave [0] alone */
4804 svh = av_fetch(cxt->aseen, tag, FALSE);
4806 if (tag == cxt->where_is_undef) {
4807 /* av_fetch uses PL_sv_undef internally, hence this
4808 somewhat gruesome hack. */
4812 CROAK(("Object #%" IVdf
4813 " should have been retrieved already",
4818 ary[i] = SvREFCNT_inc(xsv);
4823 * Look up the STORABLE_attach hook
4824 * If blessing is disabled, just return what we've got.
4826 if (!(cxt->flags & FLAG_BLESS_OK)) {
4827 TRACEME(("skipping bless because flags is %d", cxt->flags));
4832 * Bless the object and look up the STORABLE_thaw hook.
4834 stash = gv_stashpv(classname, GV_ADD);
4836 /* Handle attach case; again can't use pkg_can because it only
4837 * caches one method */
4838 attach = gv_fetchmethod_autoload(stash, "STORABLE_attach", FALSE);
4839 if (attach && isGV(attach)) {
4841 SV* attach_hook = newRV_inc((SV*) GvCV(attach));
4844 CROAK(("STORABLE_attach called with unexpected references"));
4848 AvARRAY(av)[0] = SvREFCNT_inc(frozen);
4849 rv = newSVpv(classname, 0);
4850 attached = scalar_call(aTHX_ rv, attach_hook, clone, av, G_SCALAR);
4851 /* Free memory after a call */
4853 SvREFCNT_dec(frozen);
4856 SvREFCNT_dec(attach_hook);
4859 sv_derived_from(attached, classname)
4862 /* refcnt of unneeded sv is 2 at this point
4863 (one from newHV, second from SEEN call) */
4866 /* we need to free RV but preserve value that RV point to */
4867 sv = SvRV(attached);
4869 SvRV_set(attached, NULL);
4870 SvREFCNT_dec(attached);
4871 if (!(flags & SHF_IDX_CLASSNAME) && classname != buf)
4872 Safefree(classname);
4875 CROAK(("STORABLE_attach did not return a %s object", classname));
4879 * Bless the object and look up the STORABLE_thaw hook.
4884 hook = pkg_can(aTHX_ cxt->hook, stash, "STORABLE_thaw");
4887 * Hook not found. Maybe they did not require the module where this
4888 * hook is defined yet?
4890 * If the load below succeeds, we'll be able to find the hook.
4891 * Still, it only works reliably when each class is defined in a
4895 TRACEME(("No STORABLE_thaw defined for objects of class %s", classname));
4896 TRACEME(("Going to load module '%s'", classname));
4897 load_module(PERL_LOADMOD_NOIMPORT, newSVpv(classname, 0), Nullsv);
4900 * We cache results of pkg_can, so we need to uncache before attempting
4904 pkg_uncache(aTHX_ cxt->hook, SvSTASH(sv), "STORABLE_thaw");
4905 hook = pkg_can(aTHX_ cxt->hook, SvSTASH(sv), "STORABLE_thaw");
4908 CROAK(("No STORABLE_thaw defined for objects of class %s "
4909 "(even after a \"require %s;\")", classname, classname));
4913 * If we don't have an 'av' yet, prepare one.
4914 * Then insert the frozen string as item [0].
4922 AvARRAY(av)[0] = SvREFCNT_inc(frozen);
4927 * $object->STORABLE_thaw($cloning, $frozen, @refs);
4929 * where $object is our blessed (empty) object, $cloning is a boolean
4930 * telling whether we're running a deep clone, $frozen is the frozen
4931 * string the user gave us in his serializing hook, and @refs, which may
4932 * be empty, is the list of extra references he returned along for us
4935 * In effect, the hook is an alternate creation routine for the class,
4936 * the object itself being already created by the runtime.
4939 TRACEME(("calling STORABLE_thaw on %s at 0x%" UVxf " (%" IVdf " args)",
4940 classname, PTR2UV(sv), (IV) AvFILLp(av) + 1));
4943 (void) scalar_call(aTHX_ rv, hook, clone, av, G_SCALAR|G_DISCARD);
4950 SvREFCNT_dec(frozen);
4953 if (!(flags & SHF_IDX_CLASSNAME) && classname != buf)
4954 Safefree(classname);
4957 * If we had an <extra> type, then the object was not as simple, and
4958 * we need to restore extra magic now.
4964 TRACEME(("retrieving magic object for 0x%" UVxf "...", PTR2UV(sv)));
4966 rv = retrieve(aTHX_ cxt, 0); /* Retrieve <magic object> */
4968 TRACEME(("restoring the magic object 0x%" UVxf " part of 0x%" UVxf,
4969 PTR2UV(rv), PTR2UV(sv)));
4971 switch (extra_type) {
4973 sv_upgrade(sv, SVt_PVMG);
4976 sv_upgrade(sv, SVt_PVAV);
4977 AvREAL_off((AV *)sv);
4980 sv_upgrade(sv, SVt_PVHV);
4983 CROAK(("Forgot to deal with extra type %d", extra_type));
4988 * Adding the magic only now, well after the STORABLE_thaw hook was called
4989 * means the hook cannot know it deals with an object whose variable is
4990 * tied. But this is happening when retrieving $o in the following case:
4994 * my $o = bless \%h, 'BAR';
4996 * The 'BAR' class is NOT the one where %h is tied into. Therefore, as
4997 * far as the 'BAR' class is concerned, the fact that %h is not a REAL
4998 * hash but a tied one should not matter at all, and remain transparent.
4999 * This means the magic must be restored by Storable AFTER the hook is
5002 * That looks very reasonable to me, but then I've come up with this
5003 * after a bug report from David Nesting, who was trying to store such
5004 * an object and caused Storable to fail. And unfortunately, it was
5005 * also the easiest way to retrofit support for blessed ref to tied objects
5006 * into the existing design. -- RAM, 17/02/2001
5009 sv_magic(sv, rv, mtype, (char *)NULL, 0);
5010 SvREFCNT_dec(rv); /* Undo refcnt inc from sv_magic() */
5018 * Retrieve reference to some other scalar.
5019 * Layout is SX_REF <object>, with SX_REF already read.
5021 static SV *retrieve_ref(pTHX_ stcxt_t *cxt, const char *cname)
5027 TRACEME(("retrieve_ref (#%d)", (int)cxt->tagnum));
5030 * We need to create the SV that holds the reference to the yet-to-retrieve
5031 * object now, so that we may record the address in the seen table.
5032 * Otherwise, if the object to retrieve references us, we won't be able
5033 * to resolve the SX_OBJECT we'll see at that point! Hence we cannot
5034 * do the retrieve first and use rv = newRV(sv) since it will be too late
5035 * for SEEN() recording.
5038 rv = NEWSV(10002, 0);
5040 stash = gv_stashpv(cname, GV_ADD);
5043 SEEN_NN(rv, stash, 0); /* Will return if rv is null */
5044 sv = retrieve(aTHX_ cxt, 0);/* Retrieve <object> */
5046 return (SV *) 0; /* Failed */
5049 * WARNING: breaks RV encapsulation.
5051 * Now for the tricky part. We have to upgrade our existing SV, so that
5052 * it is now an RV on sv... Again, we cheat by duplicating the code
5053 * held in newSVrv(), since we already got our SV from retrieve().
5057 * SvRV(rv) = SvREFCNT_inc(sv);
5059 * here because the reference count we got from retrieve() above is
5060 * already correct: if the object was retrieved from the file, then
5061 * its reference count is one. Otherwise, if it was retrieved via
5062 * an SX_OBJECT indication, a ref count increment was done.
5066 /* No need to do anything, as rv will already be PVMG. */
5067 assert (SvTYPE(rv) == SVt_RV || SvTYPE(rv) >= SVt_PV);
5069 sv_upgrade(rv, SVt_RV);
5072 SvRV_set(rv, sv); /* $rv = \$sv */
5074 /*if (cxt->entry && ++cxt->ref_cnt > MAX_REF_CNT) {
5075 CROAK(("Max. recursion depth with nested refs exceeded"));
5078 TRACEME(("ok (retrieve_ref at 0x%" UVxf ")", PTR2UV(rv)));
5086 * Retrieve weak reference to some other scalar.
5087 * Layout is SX_WEAKREF <object>, with SX_WEAKREF already read.
5089 static SV *retrieve_weakref(pTHX_ stcxt_t *cxt, const char *cname)
5093 TRACEME(("retrieve_weakref (#%d)", (int)cxt->tagnum));
5095 sv = retrieve_ref(aTHX_ cxt, cname);
5107 * retrieve_overloaded
5109 * Retrieve reference to some other scalar with overloading.
5110 * Layout is SX_OVERLOAD <object>, with SX_OVERLOAD already read.
5112 static SV *retrieve_overloaded(pTHX_ stcxt_t *cxt, const char *cname)
5118 TRACEME(("retrieve_overloaded (#%d)", (int)cxt->tagnum));
5121 * Same code as retrieve_ref(), duplicated to avoid extra call.
5124 rv = NEWSV(10002, 0);
5125 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5126 SEEN_NN(rv, stash, 0); /* Will return if rv is null */
5127 cxt->in_retrieve_overloaded = 1; /* so sv_bless doesn't call S_reset_amagic */
5128 sv = retrieve(aTHX_ cxt, 0); /* Retrieve <object> */
5129 cxt->in_retrieve_overloaded = 0;
5131 return (SV *) 0; /* Failed */
5134 * WARNING: breaks RV encapsulation.
5137 SvUPGRADE(rv, SVt_RV);
5138 SvRV_set(rv, sv); /* $rv = \$sv */
5142 * Restore overloading magic.
5145 stash = SvTYPE(sv) ? (HV *) SvSTASH (sv) : 0;
5147 CROAK(("Cannot restore overloading on %s(0x%" UVxf
5148 ") (package <unknown>)",
5149 sv_reftype(sv, FALSE),
5152 if (!Gv_AMG(stash)) {
5153 const char *package = HvNAME_get(stash);
5154 TRACEME(("No overloading defined for package %s", package));
5155 TRACEME(("Going to load module '%s'", package));
5156 load_module(PERL_LOADMOD_NOIMPORT, newSVpv(package, 0), Nullsv);
5157 if (!Gv_AMG(stash)) {
5158 CROAK(("Cannot restore overloading on %s(0x%" UVxf
5159 ") (package %s) (even after a \"require %s;\")",
5160 sv_reftype(sv, FALSE),
5168 TRACEME(("ok (retrieve_overloaded at 0x%" UVxf ")", PTR2UV(rv)));
5174 * retrieve_weakoverloaded
5176 * Retrieve weak overloaded reference to some other scalar.
5177 * Layout is SX_WEAKOVERLOADED <object>, with SX_WEAKOVERLOADED already read.
5179 static SV *retrieve_weakoverloaded(pTHX_ stcxt_t *cxt, const char *cname)
5183 TRACEME(("retrieve_weakoverloaded (#%d)", (int)cxt->tagnum));
5185 sv = retrieve_overloaded(aTHX_ cxt, cname);
5197 * retrieve_tied_array
5199 * Retrieve tied array
5200 * Layout is SX_TIED_ARRAY <object>, with SX_TIED_ARRAY already read.
5202 static SV *retrieve_tied_array(pTHX_ stcxt_t *cxt, const char *cname)
5208 TRACEME(("retrieve_tied_array (#%d)", (int)cxt->tagnum));
5210 if (!(cxt->flags & FLAG_TIE_OK)) {
5211 CROAK(("Tying is disabled."));
5214 tv = NEWSV(10002, 0);
5215 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5216 SEEN_NN(tv, stash, 0); /* Will return if tv is null */
5217 sv = retrieve(aTHX_ cxt, 0); /* Retrieve <object> */
5219 return (SV *) 0; /* Failed */
5221 sv_upgrade(tv, SVt_PVAV);
5222 sv_magic(tv, sv, 'P', (char *)NULL, 0);
5223 SvREFCNT_dec(sv); /* Undo refcnt inc from sv_magic() */
5225 TRACEME(("ok (retrieve_tied_array at 0x%" UVxf ")", PTR2UV(tv)));
5231 * retrieve_tied_hash
5233 * Retrieve tied hash
5234 * Layout is SX_TIED_HASH <object>, with SX_TIED_HASH already read.
5236 static SV *retrieve_tied_hash(pTHX_ stcxt_t *cxt, const char *cname)
5242 TRACEME(("retrieve_tied_hash (#%d)", (int)cxt->tagnum));
5244 if (!(cxt->flags & FLAG_TIE_OK)) {
5245 CROAK(("Tying is disabled."));
5248 tv = NEWSV(10002, 0);
5249 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5250 SEEN_NN(tv, stash, 0); /* Will return if tv is null */
5251 sv = retrieve(aTHX_ cxt, 0); /* Retrieve <object> */
5253 return (SV *) 0; /* Failed */
5255 sv_upgrade(tv, SVt_PVHV);
5256 sv_magic(tv, sv, 'P', (char *)NULL, 0);
5257 SvREFCNT_dec(sv); /* Undo refcnt inc from sv_magic() */
5259 TRACEME(("ok (retrieve_tied_hash at 0x%" UVxf ")", PTR2UV(tv)));
5265 * retrieve_tied_scalar
5267 * Retrieve tied scalar
5268 * Layout is SX_TIED_SCALAR <object>, with SX_TIED_SCALAR already read.
5270 static SV *retrieve_tied_scalar(pTHX_ stcxt_t *cxt, const char *cname)
5273 SV *sv, *obj = NULL;
5276 TRACEME(("retrieve_tied_scalar (#%d)", (int)cxt->tagnum));
5278 if (!(cxt->flags & FLAG_TIE_OK)) {
5279 CROAK(("Tying is disabled."));
5282 tv = NEWSV(10002, 0);
5283 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5284 SEEN_NN(tv, stash, 0); /* Will return if rv is null */
5285 sv = retrieve(aTHX_ cxt, 0); /* Retrieve <object> */
5287 return (SV *) 0; /* Failed */
5289 else if (SvTYPE(sv) != SVt_NULL) {
5293 sv_upgrade(tv, SVt_PVMG);
5294 sv_magic(tv, obj, 'q', (char *)NULL, 0);
5297 /* Undo refcnt inc from sv_magic() */
5301 TRACEME(("ok (retrieve_tied_scalar at 0x%" UVxf ")", PTR2UV(tv)));
5309 * Retrieve reference to value in a tied hash.
5310 * Layout is SX_TIED_KEY <object> <key>, with SX_TIED_KEY already read.
5312 static SV *retrieve_tied_key(pTHX_ stcxt_t *cxt, const char *cname)
5319 TRACEME(("retrieve_tied_key (#%d)", (int)cxt->tagnum));
5321 if (!(cxt->flags & FLAG_TIE_OK)) {
5322 CROAK(("Tying is disabled."));
5325 tv = NEWSV(10002, 0);
5326 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5327 SEEN_NN(tv, stash, 0); /* Will return if tv is null */
5328 sv = retrieve(aTHX_ cxt, 0); /* Retrieve <object> */
5330 return (SV *) 0; /* Failed */
5332 key = retrieve(aTHX_ cxt, 0); /* Retrieve <key> */
5334 return (SV *) 0; /* Failed */
5336 sv_upgrade(tv, SVt_PVMG);
5337 sv_magic(tv, sv, 'p', (char *)key, HEf_SVKEY);
5338 SvREFCNT_dec(key); /* Undo refcnt inc from sv_magic() */
5339 SvREFCNT_dec(sv); /* Undo refcnt inc from sv_magic() */
5347 * Retrieve reference to value in a tied array.
5348 * Layout is SX_TIED_IDX <object> <idx>, with SX_TIED_IDX already read.
5350 static SV *retrieve_tied_idx(pTHX_ stcxt_t *cxt, const char *cname)
5357 TRACEME(("retrieve_tied_idx (#%d)", (int)cxt->tagnum));
5359 if (!(cxt->flags & FLAG_TIE_OK)) {
5360 CROAK(("Tying is disabled."));
5363 tv = NEWSV(10002, 0);
5364 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5365 SEEN_NN(tv, stash, 0); /* Will return if tv is null */
5366 sv = retrieve(aTHX_ cxt, 0); /* Retrieve <object> */
5368 return (SV *) 0; /* Failed */
5370 RLEN(idx); /* Retrieve <idx> */
5372 sv_upgrade(tv, SVt_PVMG);
5373 sv_magic(tv, sv, 'p', (char *)NULL, idx);
5374 SvREFCNT_dec(sv); /* Undo refcnt inc from sv_magic() */
5382 * Helper to read a string
5384 static SV *get_lstring(pTHX_ stcxt_t *cxt, UV len, int isutf8, const char *cname)
5389 TRACEME(("get_lstring (#%d), len = %" UVuf, (int)cxt->tagnum, len));
5392 * Allocate an empty scalar of the suitable length.
5395 sv = NEWSV(10002, len);
5396 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5397 SEEN_NN(sv, stash, 0); /* Associate this new scalar with tag "tagnum" */
5405 * WARNING: duplicates parts of sv_setpv and breaks SV data encapsulation.
5407 * Now, for efficiency reasons, read data directly inside the SV buffer,
5408 * and perform the SV final settings directly by duplicating the final
5409 * work done by sv_setpv. Since we're going to allocate lots of scalars
5410 * this way, it's worth the hassle and risk.
5413 SAFEREAD(SvPVX(sv), len, sv);
5414 SvCUR_set(sv, len); /* Record C string length */
5415 *SvEND(sv) = '\0'; /* Ensure it's null terminated anyway */
5416 (void) SvPOK_only(sv); /* Validate string pointer */
5417 if (cxt->s_tainted) /* Is input source tainted? */
5418 SvTAINT(sv); /* External data cannot be trusted */
5420 /* Check for CVE-215-1592 */
5421 if (cname && len == 13 && strEQc(cname, "CGITempFile")
5422 && strEQc(SvPVX(sv), "mt-config.cgi")) {
5423 #if defined(USE_CPERL) && defined(WARN_SECURITY)
5424 Perl_warn_security(aTHX_
5425 "Movable-Type CVE-2015-1592 Storable metasploit attack");
5428 "SECURITY: Movable-Type CVE-2015-1592 Storable metasploit attack");
5433 TRACEME(("large utf8 string len %" UVuf " '%s'", len,
5434 len >= 2048 ? "<string too long>" : SvPVX(sv)));
5435 #ifdef HAS_UTF8_SCALARS
5438 if (cxt->use_bytes < 0)
5440 = (SvTRUE(get_sv("Storable::drop_utf8", GV_ADD))
5442 if (cxt->use_bytes == 0)
5446 TRACEME(("large string len %" UVuf " '%s'", len,
5447 len >= 2048 ? "<string too long>" : SvPVX(sv)));
5449 TRACEME(("ok (get_lstring at 0x%" UVxf ")", PTR2UV(sv)));
5457 * Retrieve defined long (string) scalar.
5459 * Layout is SX_LSCALAR <length> <data>, with SX_LSCALAR already read.
5460 * The scalar is "long" in that <length> is larger than LG_SCALAR so it
5461 * was not stored on a single byte, but in 4 bytes. For strings longer than
5462 * 4 byte (>2GB) see retrieve_lobject.
5464 static SV *retrieve_lscalar(pTHX_ stcxt_t *cxt, const char *cname)
5468 return get_lstring(aTHX_ cxt, len, 0, cname);
5474 * Retrieve defined short (string) scalar.
5476 * Layout is SX_SCALAR <length> <data>, with SX_SCALAR already read.
5477 * The scalar is "short" so <length> is single byte. If it is 0, there
5478 * is no <data> section.
5480 static SV *retrieve_scalar(pTHX_ stcxt_t *cxt, const char *cname)
5487 TRACEME(("retrieve_scalar (#%d), len = %d", (int)cxt->tagnum, len));
5488 return get_lstring(aTHX_ cxt, (UV)len, 0, cname);
5494 * Like retrieve_scalar(), but tag result as utf8.
5495 * If we're retrieving UTF8 data in a non-UTF8 perl, croaks.
5497 static SV *retrieve_utf8str(pTHX_ stcxt_t *cxt, const char *cname)
5502 TRACEME(("retrieve_utf8str"));
5504 return get_lstring(aTHX_ cxt, (UV)len, 1, cname);
5510 * Like retrieve_lscalar(), but tag result as utf8.
5511 * If we're retrieving UTF8 data in a non-UTF8 perl, croaks.
5513 static SV *retrieve_lutf8str(pTHX_ stcxt_t *cxt, const char *cname)
5517 TRACEME(("retrieve_lutf8str"));
5520 return get_lstring(aTHX_ cxt, (UV)len, 1, cname);
5526 * Retrieve a vstring, and then retrieve the stringy scalar following it,
5527 * attaching the vstring to the scalar via magic.
5528 * If we're retrieving a vstring in a perl without vstring magic, croaks.
5530 * The vstring layout mirrors an SX_SCALAR string:
5531 * SX_VSTRING <length> <data> with SX_VSTRING already read.
5533 static SV *retrieve_vstring(pTHX_ stcxt_t *cxt, const char *cname)
5541 TRACEME(("retrieve_vstring (#%d), len = %d", (int)cxt->tagnum, len));
5544 sv = retrieve(aTHX_ cxt, cname);
5546 return (SV *) 0; /* Failed */
5547 sv_magic(sv,NULL,PERL_MAGIC_vstring,s,len);
5548 /* 5.10.0 and earlier seem to need this */
5551 TRACEME(("ok (retrieve_vstring at 0x%" UVxf ")", PTR2UV(sv)));
5562 * Like retrieve_vstring, but for longer vstrings.
5564 static SV *retrieve_lvstring(pTHX_ stcxt_t *cxt, const char *cname)
5572 TRACEME(("retrieve_lvstring (#%d), len = %" IVdf,
5573 (int)cxt->tagnum, (IV)len));
5575 New(10003, s, len+1, char);
5576 SAFEPVREAD(s, len, s);
5578 sv = retrieve(aTHX_ cxt, cname);
5581 return (SV *) 0; /* Failed */
5583 sv_magic(sv,NULL,PERL_MAGIC_vstring,s,len);
5584 /* 5.10.0 and earlier seem to need this */
5589 TRACEME(("ok (retrieve_lvstring at 0x%" UVxf ")", PTR2UV(sv)));
5600 * Retrieve defined integer.
5601 * Layout is SX_INTEGER <data>, whith SX_INTEGER already read.
5603 static SV *retrieve_integer(pTHX_ stcxt_t *cxt, const char *cname)
5609 TRACEME(("retrieve_integer (#%d)", (int)cxt->tagnum));
5611 READ(&iv, sizeof(iv));
5613 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5614 SEEN_NN(sv, stash, 0); /* Associate this new scalar with tag "tagnum" */
5616 TRACEME(("integer %" IVdf, iv));
5617 TRACEME(("ok (retrieve_integer at 0x%" UVxf ")", PTR2UV(sv)));
5625 * Retrieve overlong scalar, array or hash.
5626 * Layout is SX_LOBJECT type U64_len ...
5628 static SV *retrieve_lobject(pTHX_ stcxt_t *cxt, const char *cname)
5634 TRACEME(("retrieve_lobject (#%d)", (int)cxt->tagnum));
5637 TRACEME(("object type %d", type));
5642 /* little-endian: ignore lower word */
5643 # if (BYTEORDER == 0x1234 || BYTEORDER == 0x12345678)
5647 CROAK(("Invalid large object for this 32bit system"));
5649 TRACEME(("wlen %" UVuf, len));
5652 sv = get_lstring(aTHX_ cxt, len, 0, cname);
5655 sv = get_lstring(aTHX_ cxt, len, 1, cname);
5658 sv = get_larray(aTHX_ cxt, len, cname);
5660 /* <5.12 you could store larger hashes, but cannot iterate over them.
5661 So we reject them, it's a bug. */
5664 sv = get_lhash(aTHX_ cxt, len, 1, cname);
5666 CROAK(("Invalid large object for this 32bit system"));
5671 sv = get_lhash(aTHX_ cxt, len, 0, cname);
5673 CROAK(("Invalid large object for this 32bit system"));
5677 CROAK(("Unexpected type %d in retrieve_lobject\n", type));
5680 TRACEME(("ok (retrieve_lobject at 0x%" UVxf ")", PTR2UV(sv)));
5687 * Retrieve defined integer in network order.
5688 * Layout is SX_NETINT <data>, whith SX_NETINT already read.
5690 static SV *retrieve_netint(pTHX_ stcxt_t *cxt, const char *cname)
5696 TRACEME(("retrieve_netint (#%d)", (int)cxt->tagnum));
5700 sv = newSViv((int) ntohl(iv));
5701 TRACEME(("network integer %d", (int) ntohl(iv)));
5704 TRACEME(("network integer (as-is) %d", iv));
5706 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5707 SEEN_NN(sv, stash, 0); /* Associate this new scalar with tag "tagnum" */
5709 TRACEME(("ok (retrieve_netint at 0x%" UVxf ")", PTR2UV(sv)));
5717 * Retrieve defined double.
5718 * Layout is SX_DOUBLE <data>, whith SX_DOUBLE already read.
5720 static SV *retrieve_double(pTHX_ stcxt_t *cxt, const char *cname)
5726 TRACEME(("retrieve_double (#%d)", (int)cxt->tagnum));
5728 READ(&nv, sizeof(nv));
5730 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5731 SEEN_NN(sv, stash, 0); /* Associate this new scalar with tag "tagnum" */
5733 TRACEME(("double %" NVff, nv));
5734 TRACEME(("ok (retrieve_double at 0x%" UVxf ")", PTR2UV(sv)));
5742 * Retrieve defined byte (small integer within the [-128, +127] range).
5743 * Layout is SX_BYTE <data>, whith SX_BYTE already read.
5745 static SV *retrieve_byte(pTHX_ stcxt_t *cxt, const char *cname)
5750 signed char tmp; /* Workaround for AIX cc bug --H.Merijn Brand */
5752 TRACEME(("retrieve_byte (#%d)", (int)cxt->tagnum));
5755 TRACEME(("small integer read as %d", (unsigned char) siv));
5756 tmp = (unsigned char) siv - 128;
5758 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5759 SEEN_NN(sv, stash, 0); /* Associate this new scalar with tag "tagnum" */
5761 TRACEME(("byte %d", tmp));
5762 TRACEME(("ok (retrieve_byte at 0x%" UVxf ")", PTR2UV(sv)));
5770 * Return the undefined value.
5772 static SV *retrieve_undef(pTHX_ stcxt_t *cxt, const char *cname)
5777 TRACEME(("retrieve_undef"));
5780 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5781 SEEN_NN(sv, stash, 0);
5789 * Return the immortal undefined value.
5791 static SV *retrieve_sv_undef(pTHX_ stcxt_t *cxt, const char *cname)
5793 SV *sv = &PL_sv_undef;
5796 TRACEME(("retrieve_sv_undef"));
5798 /* Special case PL_sv_undef, as av_fetch uses it internally to mark
5799 deleted elements, and will return NULL (fetch failed) whenever it
5801 if (cxt->where_is_undef == -1) {
5802 cxt->where_is_undef = (int)cxt->tagnum;
5804 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5805 SEEN_NN(sv, stash, 1);
5812 * Return the immortal yes value.
5814 static SV *retrieve_sv_yes(pTHX_ stcxt_t *cxt, const char *cname)
5816 SV *sv = &PL_sv_yes;
5819 TRACEME(("retrieve_sv_yes"));
5821 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5822 SEEN_NN(sv, stash, 1);
5829 * Return the immortal no value.
5831 static SV *retrieve_sv_no(pTHX_ stcxt_t *cxt, const char *cname)
5836 TRACEME(("retrieve_sv_no"));
5838 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5839 SEEN_NN(sv, stash, 1);
5844 * retrieve_svundef_elem
5846 * Return &PL_sv_placeholder, representing &PL_sv_undef in an array. This
5847 * is a bit of a hack, but we already use SX_SV_UNDEF to mean a nonexistent
5848 * element, for historical reasons.
5850 static SV *retrieve_svundef_elem(pTHX_ stcxt_t *cxt, const char *cname)
5852 TRACEME(("retrieve_svundef_elem"));
5854 /* SEEN reads the contents of its SV argument, which we are not
5855 supposed to do with &PL_sv_placeholder. */
5856 SEEN_NN(&PL_sv_undef, cname, 1);
5858 return &PL_sv_placeholder;
5864 * Retrieve a whole array.
5865 * Layout is SX_ARRAY <size> followed by each item, in increasing index order.
5866 * Each item is stored as <object>.
5868 * When we come here, SX_ARRAY has been read already.
5870 static SV *retrieve_array(pTHX_ stcxt_t *cxt, const char *cname)
5876 bool seen_null = FALSE;
5878 TRACEME(("retrieve_array (#%d)", (int)cxt->tagnum));
5881 * Read length, and allocate array, then pre-extend it.
5885 TRACEME(("size = %d", (int)len));
5887 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5888 SEEN_NN(av, stash, 0); /* Will return if array not allocated nicely */
5892 return (SV *) av; /* No data follow if array is empty */
5895 * Now get each item in turn...
5898 for (i = 0; i < len; i++) {
5899 TRACEME(("(#%d) item", (int)i));
5900 sv = retrieve(aTHX_ cxt, 0); /* Retrieve item */
5903 if (sv == &PL_sv_undef) {
5907 if (sv == &PL_sv_placeholder)
5909 if (av_store(av, i, sv) == 0)
5912 if (seen_null) av_fill(av, len-1);
5914 TRACEME(("ok (retrieve_array at 0x%" UVxf ")", PTR2UV(av)));
5919 /* internal method with len already read */
5921 static SV *get_larray(pTHX_ stcxt_t *cxt, UV len, const char *cname)
5927 bool seen_null = FALSE;
5929 TRACEME(("get_larray (#%d) %lu", (int)cxt->tagnum, (unsigned long)len));
5932 * allocate array, then pre-extend it.
5936 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
5937 SEEN_NN(av, stash, 0); /* Will return if array not allocated nicely */
5942 * Now get each item in turn...
5945 for (i = 0; i < len; i++) {
5946 TRACEME(("(#%d) item", (int)i));
5947 sv = retrieve(aTHX_ cxt, 0); /* Retrieve item */
5950 if (sv == &PL_sv_undef) {
5954 if (sv == &PL_sv_placeholder)
5956 if (av_store(av, i, sv) == 0)
5959 if (seen_null) av_fill(av, len-1);
5961 TRACEME(("ok (get_larray at 0x%" UVxf ")", PTR2UV(av)));
5970 * Retrieve a overlong hash table.
5971 * <len> is already read. What follows is each key/value pair, in random order.
5972 * Keys are stored as <length> <data>, the <data> section being omitted
5974 * Values are stored as <object>.
5977 static SV *get_lhash(pTHX_ stcxt_t *cxt, UV len, int hash_flags, const char *cname)
5985 TRACEME(("get_lhash (#%d)", (int)cxt->tagnum));
5987 #ifdef HAS_RESTRICTED_HASHES
5988 PERL_UNUSED_ARG(hash_flags);
5990 if (hash_flags & SHV_RESTRICTED) {
5991 if (cxt->derestrict < 0)
5992 cxt->derestrict = (SvTRUE
5993 (get_sv("Storable::downgrade_restricted", GV_ADD))
5995 if (cxt->derestrict == 0)
5996 RESTRICTED_HASH_CROAK();
6000 TRACEME(("size = %lu", (unsigned long)len));
6002 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
6003 SEEN_NN(hv, stash, 0); /* Will return if table not allocated properly */
6005 return (SV *) hv; /* No data follow if table empty */
6006 TRACEME(("split %lu", (unsigned long)len+1));
6007 hv_ksplit(hv, len+1); /* pre-extend hash to save multiple splits */
6010 * Now get each key/value pair in turn...
6013 for (i = 0; i < len; i++) {
6018 TRACEME(("(#%d) value", (int)i));
6019 sv = retrieve(aTHX_ cxt, 0);
6025 * Since we're reading into kbuf, we must ensure we're not
6026 * recursing between the read and the hv_store() where it's used.
6027 * Hence the key comes after the value.
6030 RLEN(size); /* Get key size */
6031 KBUFCHK((STRLEN)size); /* Grow hash key read pool if needed */
6034 kbuf[size] = '\0'; /* Mark string end, just in case */
6035 TRACEME(("(#%d) key '%s'", (int)i, kbuf));
6038 * Enter key/value pair into hash table.
6041 if (hv_store(hv, kbuf, (U32) size, sv, 0) == 0)
6045 TRACEME(("ok (get_lhash at 0x%" UVxf ")", PTR2UV(hv)));
6053 * Retrieve a whole hash table.
6054 * Layout is SX_HASH <size> followed by each key/value pair, in random order.
6055 * Keys are stored as <length> <data>, the <data> section being omitted
6057 * Values are stored as <object>.
6059 * When we come here, SX_HASH has been read already.
6061 static SV *retrieve_hash(pTHX_ stcxt_t *cxt, const char *cname)
6070 TRACEME(("retrieve_hash (#%d)", (int)cxt->tagnum));
6073 * Read length, allocate table.
6077 TRACEME(("size = %d", (int)len));
6079 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
6080 SEEN_NN(hv, stash, 0); /* Will return if table not allocated properly */
6082 return (SV *) hv; /* No data follow if table empty */
6083 TRACEME(("split %d", (int)len+1));
6084 hv_ksplit(hv, len+1); /* pre-extend hash to save multiple splits */
6087 * Now get each key/value pair in turn...
6090 for (i = 0; i < len; i++) {
6095 TRACEME(("(#%d) value", (int)i));
6096 sv = retrieve(aTHX_ cxt, 0);
6102 * Since we're reading into kbuf, we must ensure we're not
6103 * recursing between the read and the hv_store() where it's used.
6104 * Hence the key comes after the value.
6107 RLEN(size); /* Get key size */
6108 KBUFCHK((STRLEN)size); /* Grow hash key read pool if needed */
6111 kbuf[size] = '\0'; /* Mark string end, just in case */
6112 TRACEME(("(#%d) key '%s'", (int)i, kbuf));
6115 * Enter key/value pair into hash table.
6118 if (hv_store(hv, kbuf, (U32) size, sv, 0) == 0)
6122 TRACEME(("ok (retrieve_hash at 0x%" UVxf ")", PTR2UV(hv)));
6130 * Retrieve a whole hash table.
6131 * Layout is SX_HASH <size> followed by each key/value pair, in random order.
6132 * Keys are stored as <length> <data>, the <data> section being omitted
6134 * Values are stored as <object>.
6136 * When we come here, SX_HASH has been read already.
6138 static SV *retrieve_flag_hash(pTHX_ stcxt_t *cxt, const char *cname)
6149 GETMARK(hash_flags);
6150 TRACEME(("retrieve_flag_hash (#%d)", (int)cxt->tagnum));
6152 * Read length, allocate table.
6155 #ifndef HAS_RESTRICTED_HASHES
6156 if (hash_flags & SHV_RESTRICTED) {
6157 if (cxt->derestrict < 0)
6158 cxt->derestrict = (SvTRUE
6159 (get_sv("Storable::downgrade_restricted", GV_ADD))
6161 if (cxt->derestrict == 0)
6162 RESTRICTED_HASH_CROAK();
6167 TRACEME(("size = %d, flags = %d", (int)len, hash_flags));
6169 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
6170 SEEN_NN(hv, stash, 0); /* Will return if table not allocated properly */
6172 return (SV *) hv; /* No data follow if table empty */
6173 TRACEME(("split %d", (int)len+1));
6174 hv_ksplit(hv, len+1); /* pre-extend hash to save multiple splits */
6177 * Now get each key/value pair in turn...
6180 for (i = 0; i < len; i++) {
6182 int store_flags = 0;
6187 TRACEME(("(#%d) value", (int)i));
6188 sv = retrieve(aTHX_ cxt, 0);
6193 #ifdef HAS_RESTRICTED_HASHES
6194 if ((hash_flags & SHV_RESTRICTED) && (flags & SHV_K_LOCKED))
6198 if (flags & SHV_K_ISSV) {
6199 /* XXX you can't set a placeholder with an SV key.
6200 Then again, you can't get an SV key.
6201 Without messing around beyond what the API is supposed to do.
6204 TRACEME(("(#%d) keysv, flags=%d", (int)i, flags));
6205 keysv = retrieve(aTHX_ cxt, 0);
6209 if (!hv_store_ent(hv, keysv, sv, 0))
6214 * Since we're reading into kbuf, we must ensure we're not
6215 * recursing between the read and the hv_store() where it's used.
6216 * Hence the key comes after the value.
6219 if (flags & SHV_K_PLACEHOLDER) {
6221 sv = &PL_sv_placeholder;
6222 store_flags |= HVhek_PLACEHOLD;
6224 if (flags & SHV_K_UTF8) {
6225 #ifdef HAS_UTF8_HASHES
6226 store_flags |= HVhek_UTF8;
6228 if (cxt->use_bytes < 0)
6230 = (SvTRUE(get_sv("Storable::drop_utf8", GV_ADD))
6232 if (cxt->use_bytes == 0)
6236 #ifdef HAS_UTF8_HASHES
6237 if (flags & SHV_K_WASUTF8)
6238 store_flags |= HVhek_WASUTF8;
6241 RLEN(size); /* Get key size */
6242 KBUFCHK((STRLEN)size);/* Grow hash key read pool if needed */
6245 kbuf[size] = '\0'; /* Mark string end, just in case */
6246 TRACEME(("(#%d) key '%s' flags %X store_flags %X", (int)i, kbuf,
6247 flags, store_flags));
6250 * Enter key/value pair into hash table.
6253 #ifdef HAS_RESTRICTED_HASHES
6254 if (hv_store_flags(hv, kbuf, size, sv, 0, store_flags) == 0)
6257 if (!(store_flags & HVhek_PLACEHOLD))
6258 if (hv_store(hv, kbuf, size, sv, 0) == 0)
6263 #ifdef HAS_RESTRICTED_HASHES
6264 if (hash_flags & SHV_RESTRICTED)
6268 TRACEME(("ok (retrieve_hash at 0x%" UVxf ")", PTR2UV(hv)));
6276 * Return a code reference.
6278 static SV *retrieve_code(pTHX_ stcxt_t *cxt, const char *cname)
6280 #if PERL_VERSION < 6
6281 CROAK(("retrieve_code does not work with perl 5.005 or less\n"));
6287 SV *sv, *text, *sub, *errsv;
6290 TRACEME(("retrieve_code (#%d)", (int)cxt->tagnum));
6293 * Insert dummy SV in the aseen array so that we don't screw
6294 * up the tag numbers. We would just make the internal
6295 * scalar an untagged item in the stream, but
6296 * retrieve_scalar() calls SEEN(). So we just increase the
6299 tagnum = cxt->tagnum;
6301 stash = cname ? gv_stashpv(cname, GV_ADD) : 0;
6302 SEEN_NN(sv, stash, 0);
6305 * Retrieve the source of the code reference
6306 * as a small or large scalar
6312 text = retrieve_scalar(aTHX_ cxt, cname);
6315 text = retrieve_lscalar(aTHX_ cxt, cname);
6318 text = retrieve_utf8str(aTHX_ cxt, cname);
6321 text = retrieve_lutf8str(aTHX_ cxt, cname);
6324 CROAK(("Unexpected type %d in retrieve_code\n", (int)type));
6328 CROAK(("Unable to retrieve code\n"));
6332 * prepend "sub " to the source
6335 sub = newSVpvs("sub ");
6338 sv_catpv(sub, SvPV_nolen(text)); /* XXX no sv_catsv! */
6342 * evaluate the source to a code reference and use the CV value
6345 if (cxt->eval == NULL) {
6346 cxt->eval = get_sv("Storable::Eval", GV_ADD);
6347 SvREFCNT_inc(cxt->eval);
6349 if (!SvTRUE(cxt->eval)) {
6350 if (cxt->forgive_me == 0 ||
6351 (cxt->forgive_me < 0 &&
6352 !(cxt->forgive_me = SvTRUE
6353 (get_sv("Storable::forgive_me", GV_ADD)) ? 1 : 0))
6355 CROAK(("Can't eval, please set $Storable::Eval to a true value"));
6358 /* fix up the dummy entry... */
6359 av_store(cxt->aseen, tagnum, SvREFCNT_inc(sv));
6367 errsv = get_sv("@", GV_ADD);
6368 SvPVCLEAR(errsv); /* clear $@ */
6369 if (SvROK(cxt->eval) && SvTYPE(SvRV(cxt->eval)) == SVt_PVCV) {
6371 XPUSHs(sv_2mortal(newSVsv(sub)));
6373 count = call_sv(cxt->eval, G_SCALAR);
6375 CROAK(("Unexpected return value from $Storable::Eval callback\n"));
6377 eval_sv(sub, G_SCALAR);
6383 if (SvTRUE(errsv)) {
6384 CROAK(("code %s caused an error: %s",
6385 SvPV_nolen(sub), SvPV_nolen(errsv)));
6388 if (cv && SvROK(cv) && SvTYPE(SvRV(cv)) == SVt_PVCV) {
6391 CROAK(("code %s did not evaluate to a subroutine reference\n",
6395 SvREFCNT_inc(sv); /* XXX seems to be necessary */
6400 /* fix up the dummy entry... */
6401 av_store(cxt->aseen, tagnum, SvREFCNT_inc(sv));
6408 * old_retrieve_array
6410 * Retrieve a whole array in pre-0.6 binary format.
6412 * Layout is SX_ARRAY <size> followed by each item, in increasing index order.
6413 * Each item is stored as SX_ITEM <object> or SX_IT_UNDEF for "holes".
6415 * When we come here, SX_ARRAY has been read already.
6417 static SV *old_retrieve_array(pTHX_ stcxt_t *cxt, const char *cname)
6425 PERL_UNUSED_ARG(cname);
6426 TRACEME(("old_retrieve_array (#%d)", (int)cxt->tagnum));
6429 * Read length, and allocate array, then pre-extend it.
6433 TRACEME(("size = %d", (int)len));
6435 SEEN0_NN(av, 0); /* Will return if array not allocated nicely */
6439 return (SV *) av; /* No data follow if array is empty */
6442 * Now get each item in turn...
6445 for (i = 0; i < len; i++) {
6447 if (c == SX_IT_UNDEF) {
6448 TRACEME(("(#%d) undef item", (int)i));
6449 continue; /* av_extend() already filled us with undef */
6452 (void) retrieve_other(aTHX_ cxt, 0);/* Will croak out */
6453 TRACEME(("(#%d) item", (int)i));
6454 sv = retrieve(aTHX_ cxt, 0); /* Retrieve item */
6457 if (av_store(av, i, sv) == 0)
6461 TRACEME(("ok (old_retrieve_array at 0x%" UVxf ")", PTR2UV(av)));
6469 * Retrieve a whole hash table in pre-0.6 binary format.
6471 * Layout is SX_HASH <size> followed by each key/value pair, in random order.
6472 * Keys are stored as SX_KEY <length> <data>, the <data> section being omitted
6474 * Values are stored as SX_VALUE <object> or SX_VL_UNDEF for "holes".
6476 * When we come here, SX_HASH has been read already.
6478 static SV *old_retrieve_hash(pTHX_ stcxt_t *cxt, const char *cname)
6486 SV *sv_h_undef = (SV *) 0; /* hv_store() bug */
6488 PERL_UNUSED_ARG(cname);
6489 TRACEME(("old_retrieve_hash (#%d)", (int)cxt->tagnum));
6492 * Read length, allocate table.
6496 TRACEME(("size = %d", (int)len));
6498 SEEN0_NN(hv, 0); /* Will return if table not allocated properly */
6500 return (SV *) hv; /* No data follow if table empty */
6501 TRACEME(("split %d", (int)len+1));
6502 hv_ksplit(hv, len+1); /* pre-extend hash to save multiple splits */
6505 * Now get each key/value pair in turn...
6508 for (i = 0; i < len; i++) {
6514 if (c == SX_VL_UNDEF) {
6515 TRACEME(("(#%d) undef value", (int)i));
6517 * Due to a bug in hv_store(), it's not possible to pass
6518 * &PL_sv_undef to hv_store() as a value, otherwise the
6519 * associated key will not be creatable any more. -- RAM, 14/01/97
6522 sv_h_undef = newSVsv(&PL_sv_undef);
6523 sv = SvREFCNT_inc(sv_h_undef);
6524 } else if (c == SX_VALUE) {
6525 TRACEME(("(#%d) value", (int)i));
6526 sv = retrieve(aTHX_ cxt, 0);
6530 (void) retrieve_other(aTHX_ cxt, 0); /* Will croak out */
6534 * Since we're reading into kbuf, we must ensure we're not
6535 * recursing between the read and the hv_store() where it's used.
6536 * Hence the key comes after the value.
6541 (void) retrieve_other(aTHX_ cxt, 0); /* Will croak out */
6542 RLEN(size); /* Get key size */
6543 KBUFCHK((STRLEN)size); /* Grow hash key read pool if needed */
6546 kbuf[size] = '\0'; /* Mark string end, just in case */
6547 TRACEME(("(#%d) key '%s'", (int)i, kbuf));
6550 * Enter key/value pair into hash table.
6553 if (hv_store(hv, kbuf, (U32) size, sv, 0) == 0)
6557 TRACEME(("ok (retrieve_hash at 0x%" UVxf ")", PTR2UV(hv)));
6563 *** Retrieval engine.
6569 * Make sure the stored data we're trying to retrieve has been produced
6570 * on an ILP compatible system with the same byteorder. It croaks out in
6571 * case an error is detected. [ILP = integer-long-pointer sizes]
6572 * Returns null if error is detected, &PL_sv_undef otherwise.
6574 * Note that there's no byte ordering info emitted when network order was
6575 * used at store time.
6577 static SV *magic_check(pTHX_ stcxt_t *cxt)
6579 /* The worst case for a malicious header would be old magic (which is
6580 longer), major, minor, byteorder length byte of 255, 255 bytes of
6581 garbage, sizeof int, long, pointer, NV.
6582 So the worse of that we can read is 255 bytes of garbage plus 4.
6583 Err, I am assuming 8 bit bytes here. Please file a bug report if you're
6584 compiling perl on a system with chars that are larger than 8 bits.
6585 (Even Crays aren't *that* perverse).
6587 unsigned char buf[4 + 255];
6588 unsigned char *current;
6591 int use_network_order;
6595 int version_minor = 0;
6597 TRACEME(("magic_check"));
6600 * The "magic number" is only for files, not when freezing in memory.
6604 /* This includes the '\0' at the end. I want to read the extra byte,
6605 which is usually going to be the major version number. */
6606 STRLEN len = sizeof(magicstr);
6609 READ(buf, (SSize_t)(len)); /* Not null-terminated */
6611 /* Point at the byte after the byte we read. */
6612 current = buf + --len; /* Do the -- outside of macros. */
6614 if (memNE(buf, magicstr, len)) {
6616 * Try to read more bytes to check for the old magic number, which
6620 TRACEME(("trying for old magic number"));
6622 old_len = sizeof(old_magicstr) - 1;
6623 READ(current + 1, (SSize_t)(old_len - len));
6625 if (memNE(buf, old_magicstr, old_len))
6626 CROAK(("File is not a perl storable"));
6628 current = buf + old_len;
6630 use_network_order = *current;
6632 GETMARK(use_network_order);
6636 * Starting with 0.6, the "use_network_order" byte flag is also used to
6637 * indicate the version number of the binary, and therefore governs the
6638 * setting of sv_retrieve_vtbl. See magic_write().
6640 if (old_magic && use_network_order > 1) {
6641 /* 0.1 dump - use_network_order is really byte order length */
6645 version_major = use_network_order >> 1;
6647 cxt->retrieve_vtbl = (SV*(**)(pTHX_ stcxt_t *cxt, const char *cname)) (version_major > 0 ? sv_retrieve : sv_old_retrieve);
6649 TRACEME(("magic_check: netorder = 0x%x", use_network_order));
6653 * Starting with 0.7 (binary major 2), a full byte is dedicated to the
6654 * minor version of the protocol. See magic_write().
6657 if (version_major > 1)
6658 GETMARK(version_minor);
6660 cxt->ver_major = version_major;
6661 cxt->ver_minor = version_minor;
6663 TRACEME(("binary image version is %d.%d", version_major, version_minor));
6666 * Inter-operability sanity check: we can't retrieve something stored
6667 * using a format more recent than ours, because we have no way to
6668 * know what has changed, and letting retrieval go would mean a probable
6669 * failure reporting a "corrupted" storable file.
6673 version_major > STORABLE_BIN_MAJOR ||
6674 (version_major == STORABLE_BIN_MAJOR &&
6675 version_minor > STORABLE_BIN_MINOR)
6678 TRACEME(("but I am version is %d.%d", STORABLE_BIN_MAJOR,
6679 STORABLE_BIN_MINOR));
6681 if (version_major == STORABLE_BIN_MAJOR) {
6682 TRACEME(("cxt->accept_future_minor is %d",
6683 cxt->accept_future_minor));
6684 if (cxt->accept_future_minor < 0)
6685 cxt->accept_future_minor
6686 = (SvTRUE(get_sv("Storable::accept_future_minor",
6689 if (cxt->accept_future_minor == 1)
6690 croak_now = 0; /* Don't croak yet. */
6693 CROAK(("Storable binary image v%d.%d more recent than I am (v%d.%d)",
6694 version_major, version_minor,
6695 STORABLE_BIN_MAJOR, STORABLE_BIN_MINOR));
6700 * If they stored using network order, there's no byte ordering
6701 * information to check.
6704 if ((cxt->netorder = (use_network_order & 0x1))) /* Extra () for -Wall */
6705 return &PL_sv_undef; /* No byte ordering info */
6707 /* In C truth is 1, falsehood is 0. Very convenient. */
6708 use_NV_size = version_major >= 2 && version_minor >= 2;
6710 if (version_major >= 0) {
6714 c = use_network_order;
6716 length = c + 3 + use_NV_size;
6717 READ(buf, length); /* Not null-terminated */
6719 TRACEME(("byte order '%.*s' %d", c, buf, c));
6721 #ifdef USE_56_INTERWORK_KLUDGE
6722 /* No point in caching this in the context as we only need it once per
6723 retrieve, and we need to recheck it each read. */
6724 if (SvTRUE(get_sv("Storable::interwork_56_64bit", GV_ADD))) {
6725 if ((c != (sizeof (byteorderstr_56) - 1))
6726 || memNE(buf, byteorderstr_56, c))
6727 CROAK(("Byte order is not compatible"));
6731 if ((c != (sizeof (byteorderstr) - 1))
6732 || memNE(buf, byteorderstr, c))
6733 CROAK(("Byte order is not compatible"));
6739 if ((int) *current++ != sizeof(int))
6740 CROAK(("Integer size is not compatible"));
6743 if ((int) *current++ != sizeof(long))
6744 CROAK(("Long integer size is not compatible"));
6746 /* sizeof(char *) */
6747 if ((int) *current != sizeof(char *))
6748 CROAK(("Pointer size is not compatible"));
6752 if ((int) *++current != sizeof(NV))
6753 CROAK(("Double size is not compatible"));
6756 return &PL_sv_undef; /* OK */
6762 * Recursively retrieve objects from the specified file and return their
6763 * root SV (which may be an AV or an HV for what we care).
6764 * Returns null if there is a problem.
6766 static SV *retrieve(pTHX_ stcxt_t *cxt, const char *cname)
6772 TRACEME(("retrieve"));
6775 * Grab address tag which identifies the object if we are retrieving
6776 * an older format. Since the new binary format counts objects and no
6777 * longer explicitly tags them, we must keep track of the correspondence
6780 * The following section will disappear one day when the old format is
6781 * no longer supported, hence the final "goto" in the "if" block.
6784 if (cxt->hseen) { /* Retrieving old binary */
6786 if (cxt->netorder) {
6788 READ(&nettag, sizeof(I32)); /* Ordered sequence of I32 */
6789 tag = (stag_t) nettag;
6791 READ(&tag, sizeof(stag_t)); /* Original address of the SV */
6794 if (type == SX_OBJECT) {
6796 svh = hv_fetch(cxt->hseen, (char *) &tag, sizeof(tag), FALSE);
6798 CROAK(("Old tag 0x%" UVxf " should have been mapped already",
6800 tagn = SvIV(*svh); /* Mapped tag number computed earlier below */
6803 * The following code is common with the SX_OBJECT case below.
6806 svh = av_fetch(cxt->aseen, tagn, FALSE);
6808 CROAK(("Object #%" IVdf " should have been retrieved already",
6811 TRACEME(("has retrieved #%d at 0x%" UVxf, (int)tagn, PTR2UV(sv)));
6812 SvREFCNT_inc(sv); /* One more reference to this same sv */
6813 return sv; /* The SV pointer where object was retrieved */
6817 * Map new object, but don't increase tagnum. This will be done
6818 * by each of the retrieve_* functions when they call SEEN().
6820 * The mapping associates the "tag" initially present with a unique
6821 * tag number. See test for SX_OBJECT above to see how this is perused.
6824 if (!hv_store(cxt->hseen, (char *) &tag, sizeof(tag),
6825 newSViv(cxt->tagnum), 0))
6832 * Regular post-0.6 binary format.
6837 TRACEME(("retrieve type = %d", type));
6840 * Are we dealing with an object we should have already retrieved?
6843 if (type == SX_OBJECT) {
6847 svh = av_fetch(cxt->aseen, tag, FALSE);
6849 CROAK(("Object #%" IVdf " should have been retrieved already",
6852 TRACEME(("had retrieved #%d at 0x%" UVxf, (int)tag, PTR2UV(sv)));
6853 SvREFCNT_inc(sv); /* One more reference to this same sv */
6854 return sv; /* The SV pointer where object was retrieved */
6855 } else if (type >= SX_ERROR && cxt->ver_minor > STORABLE_BIN_MINOR) {
6856 if (cxt->accept_future_minor < 0)
6857 cxt->accept_future_minor
6858 = (SvTRUE(get_sv("Storable::accept_future_minor",
6861 if (cxt->accept_future_minor == 1) {
6862 CROAK(("Storable binary image v%d.%d contains data of type %d. "
6863 "This Storable is v%d.%d and can only handle data types up to %d",
6864 cxt->ver_major, cxt->ver_minor, type,
6865 STORABLE_BIN_MAJOR, STORABLE_BIN_MINOR, SX_ERROR - 1));
6869 first_time: /* Will disappear when support for old format is dropped */
6872 * Okay, first time through for this one.
6875 sv = RETRIEVE(cxt, type)(aTHX_ cxt, cname);
6877 return (SV *) 0; /* Failed */
6880 * Old binary formats (pre-0.7).
6882 * Final notifications, ended by SX_STORED may now follow.
6883 * Currently, the only pertinent notification to apply on the
6884 * freshly retrieved object is either:
6885 * SX_CLASS <char-len> <classname> for short classnames.
6886 * SX_LG_CLASS <int-len> <classname> for larger one (rare!).
6887 * Class name is then read into the key buffer pool used by
6888 * hash table key retrieval.
6891 if (cxt->ver_major < 2) {
6892 while ((type = GETCHAR()) != SX_STORED) {
6897 GETMARK(len); /* Length coded on a single char */
6899 case SX_LG_CLASS: /* Length coded on a regular integer */
6904 return (SV *) 0; /* Failed */
6906 KBUFCHK((STRLEN)len); /* Grow buffer as necessary */
6909 kbuf[len] = '\0'; /* Mark string end */
6910 stash = gv_stashpvn(kbuf, len, GV_ADD);
6915 TRACEME(("ok (retrieved 0x%" UVxf ", refcnt=%d, %s)", PTR2UV(sv),
6916 (int)SvREFCNT(sv) - 1, sv_reftype(sv, FALSE)));
6924 * Retrieve data held in file and return the root object.
6925 * Common routine for pretrieve and mretrieve.
6927 static SV *do_retrieve(
6936 int is_tainted; /* Is input source tainted? */
6937 int pre_06_fmt = 0; /* True with pre Storable 0.6 formats */
6939 TRACEME(("do_retrieve (optype = 0x%x)", optype));
6940 TRACEME(("do_retrieve (flags = 0x%x)", flags));
6942 optype |= ST_RETRIEVE;
6946 * Sanity assertions for retrieve dispatch tables.
6949 ASSERT(sizeof(sv_old_retrieve) == sizeof(sv_retrieve),
6950 ("old and new retrieve dispatch table have same size"));
6951 ASSERT(sv_old_retrieve[(int)SX_ERROR] == retrieve_other,
6952 ("SX_ERROR entry correctly initialized in old dispatch table"));
6953 ASSERT(sv_retrieve[(int)SX_ERROR] == retrieve_other,
6954 ("SX_ERROR entry correctly initialized in new dispatch table"));
6957 * Workaround for CROAK leak: if they enter with a "dirty" context,
6958 * free up memory for them now.
6963 clean_context(aTHX_ cxt);
6966 * Now that STORABLE_xxx hooks exist, it is possible that they try to
6967 * re-enter retrieve() via the hooks.
6971 cxt = allocate_context(aTHX_ cxt);
6977 ASSERT(cxt->entry == 1, ("starting new recursion"));
6978 ASSERT(!cxt->s_dirty, ("clean context"));
6983 * Data is loaded into the memory buffer when f is NULL, unless 'in' is
6984 * also NULL, in which case we're expecting the data to already lie
6985 * in the buffer (dclone case).
6988 KBUFINIT(); /* Allocate hash key reading pool once */
6994 const char *orig = SvPV(in, length);
6996 /* This is quite deliberate. I want the UTF8 routines
6997 to encounter the '\0' which perl adds at the end
6998 of all scalars, so that any new string also has
7001 STRLEN klen_tmp = length + 1;
7002 bool is_utf8 = TRUE;
7004 /* Just casting the &klen to (STRLEN) won't work
7005 well if STRLEN and I32 are of different widths.
7007 asbytes = (char*)bytes_from_utf8((U8*)orig,
7011 CROAK(("Frozen string corrupt - contains characters outside 0-255"));
7013 if (asbytes != orig) {
7014 /* String has been converted.
7015 There is no need to keep any reference to
7017 in = sv_newmortal();
7018 /* We donate the SV the malloc()ed string
7019 bytes_from_utf8 returned us. */
7020 SvUPGRADE(in, SVt_PV);
7022 SvPV_set(in, asbytes);
7023 SvLEN_set(in, klen_tmp);
7024 SvCUR_set(in, klen_tmp - 1);
7028 MBUF_SAVE_AND_LOAD(in);
7032 * Magic number verifications.
7034 * This needs to be done before calling init_retrieve_context()
7035 * since the format indication in the file are necessary to conduct
7036 * some of the initializations.
7039 cxt->fio = f; /* Where I/O are performed */
7041 if (!magic_check(aTHX_ cxt))
7042 CROAK(("Magic number checking on storable %s failed",
7043 cxt->fio ? "file" : "string"));
7045 TRACEME(("data stored in %s format",
7046 cxt->netorder ? "net order" : "native"));
7049 * Check whether input source is tainted, so that we don't wrongly
7050 * taint perfectly good values...
7052 * We assume file input is always tainted. If both 'f' and 'in' are
7053 * NULL, then we come from dclone, and tainted is already filled in
7054 * the context. That's a kludge, but the whole dclone() thing is
7055 * already quite a kludge anyway! -- RAM, 15/09/2000.
7058 is_tainted = f ? 1 : (in ? SvTAINTED(in) : cxt->s_tainted);
7059 TRACEME(("input source is %s", is_tainted ? "tainted" : "trusted"));
7060 init_retrieve_context(aTHX_ cxt, optype, is_tainted);
7062 ASSERT(is_retrieving(aTHX), ("within retrieve operation"));
7064 sv = retrieve(aTHX_ cxt, 0); /* Recursively retrieve object, get root SV */
7073 pre_06_fmt = cxt->hseen != NULL; /* Before we clean context */
7076 * The "root" context is never freed.
7079 clean_retrieve_context(aTHX_ cxt);
7080 if (cxt->prev) /* This context was stacked */
7081 free_context(aTHX_ cxt); /* It was not the "root" context */
7084 * Prepare returned value.
7088 TRACEME(("retrieve ERROR"));
7089 #if (PATCHLEVEL <= 4)
7090 /* perl 5.00405 seems to screw up at this point with an
7091 'attempt to modify a read only value' error reported in the
7092 eval { $self = pretrieve(*FILE) } in _retrieve.
7093 I can't see what the cause of this error is, but I suspect a
7094 bug in 5.004, as it seems to be capable of issuing spurious
7095 errors or core dumping with matches on $@. I'm not going to
7096 spend time on what could be a fruitless search for the cause,
7097 so here's a bodge. If you're running 5.004 and don't like
7098 this inefficiency, either upgrade to a newer perl, or you are
7099 welcome to find the problem and send in a patch.
7103 return &PL_sv_undef; /* Something went wrong, return undef */
7107 TRACEME(("retrieve got %s(0x%" UVxf ")",
7108 sv_reftype(sv, FALSE), PTR2UV(sv)));
7111 * Backward compatibility with Storable-0.5@9 (which we know we
7112 * are retrieving if hseen is non-null): don't create an extra RV
7113 * for objects since we special-cased it at store time.
7115 * Build a reference to the SV returned by pretrieve even if it is
7116 * already one and not a scalar, for consistency reasons.
7119 if (pre_06_fmt) { /* Was not handling overloading by then */
7121 TRACEME(("fixing for old formats -- pre 0.6"));
7122 if (sv_type(aTHX_ sv) == svis_REF && (rv = SvRV(sv)) && SvOBJECT(rv)) {
7123 TRACEME(("ended do_retrieve() with an object -- pre 0.6"));
7129 * If reference is overloaded, restore behaviour.
7131 * NB: minor glitch here: normally, overloaded refs are stored specially
7132 * so that we can croak when behaviour cannot be re-installed, and also
7133 * avoid testing for overloading magic at each reference retrieval.
7135 * Unfortunately, the root reference is implicitly stored, so we must
7136 * check for possible overloading now. Furthermore, if we don't restore
7137 * overloading, we cannot croak as if the original ref was, because we
7138 * have no way to determine whether it was an overloaded ref or not in
7141 * It's a pity that overloading magic is attached to the rv, and not to
7142 * the underlying sv as blessing is.
7146 HV *stash = (HV *) SvSTASH(sv);
7147 SV *rv = newRV_noinc(sv);
7148 if (stash && Gv_AMG(stash)) {
7150 TRACEME(("restored overloading on root reference"));
7152 TRACEME(("ended do_retrieve() with an object"));
7156 TRACEME(("regular do_retrieve() end"));
7158 return newRV_noinc(sv);
7164 * Retrieve data held in file and return the root object, undef on error.
7166 static SV *pretrieve(pTHX_ PerlIO *f, IV flag)
7168 TRACEME(("pretrieve"));
7169 return do_retrieve(aTHX_ f, Nullsv, 0, (int)flag);
7175 * Retrieve data held in scalar and return the root object, undef on error.
7177 static SV *mretrieve(pTHX_ SV *sv, IV flag)
7179 TRACEME(("mretrieve"));
7180 return do_retrieve(aTHX_ (PerlIO*) 0, sv, 0, (int)flag);
7190 * Deep clone: returns a fresh copy of the original referenced SV tree.
7192 * This is achieved by storing the object in memory and restoring from
7193 * there. Not that efficient, but it should be faster than doing it from
7196 static SV *dclone(pTHX_ SV *sv)
7200 stcxt_t *real_context;
7203 TRACEME(("dclone"));
7206 * Workaround for CROAK leak: if they enter with a "dirty" context,
7207 * free up memory for them now.
7212 clean_context(aTHX_ cxt);
7215 * Tied elements seem to need special handling.
7218 if ((SvTYPE(sv) == SVt_PVLV
7219 #if PERL_VERSION < 8
7220 || SvTYPE(sv) == SVt_PVMG
7222 ) && (SvFLAGS(sv) & (SVs_GMG|SVs_SMG|SVs_RMG)) ==
7223 (SVs_GMG|SVs_SMG|SVs_RMG) &&
7229 * do_store() optimizes for dclone by not freeing its context, should
7230 * we need to allocate one because we're deep cloning from a hook.
7233 if (!do_store(aTHX_ (PerlIO*) 0, sv, ST_CLONE, FALSE, (SV**) 0))
7234 return &PL_sv_undef; /* Error during store */
7237 * Because of the above optimization, we have to refresh the context,
7238 * since a new one could have been allocated and stacked by do_store().
7241 { dSTCXT; real_context = cxt; } /* Sub-block needed for macro */
7242 cxt = real_context; /* And we need this temporary... */
7245 * Now, 'cxt' may refer to a new context.
7249 ASSERT(!cxt->s_dirty, ("clean context"));
7250 ASSERT(!cxt->entry, ("entry will not cause new context allocation"));
7253 TRACEME(("dclone stored %ld bytes", (long)size));
7257 * Since we're passing do_retrieve() both a NULL file and sv, we need
7258 * to pre-compute the taintedness of the input by setting cxt->tainted
7259 * to whatever state our own input string was. -- RAM, 15/09/2000
7261 * do_retrieve() will free non-root context.
7264 cxt->s_tainted = SvTAINTED(sv);
7265 out = do_retrieve(aTHX_ (PerlIO*) 0, Nullsv, ST_CLONE, FLAG_BLESS_OK | FLAG_TIE_OK);
7267 TRACEME(("dclone returns 0x%" UVxf, PTR2UV(out)));
7277 * The Perl IO GV object distinguishes between input and output for sockets
7278 * but not for plain files. To allow Storable to transparently work on
7279 * plain files and sockets transparently, we have to ask xsubpp to fetch the
7280 * right object for us. Hence the OutputStream and InputStream declarations.
7282 * Before perl 5.004_05, those entries in the standard typemap are not
7283 * defined in perl include files, so we do that here.
7286 #ifndef OutputStream
7287 #define OutputStream PerlIO *
7288 #define InputStream PerlIO *
7289 #endif /* !OutputStream */
7292 storable_free(pTHX_ SV *sv, MAGIC* mg) {
7293 stcxt_t *cxt = (stcxt_t *)SvPVX(sv);
7295 PERL_UNUSED_ARG(mg);
7298 if (!cxt->membuf_ro && mbase)
7300 if (cxt->membuf_ro && (cxt->msaved).arena)
7301 Safefree((cxt->msaved).arena);
7305 MODULE = Storable PACKAGE = Storable
7311 HV *stash = gv_stashpvn("Storable", 8, GV_ADD);
7312 newCONSTSUB(stash, "BIN_MAJOR", newSViv(STORABLE_BIN_MAJOR));
7313 newCONSTSUB(stash, "BIN_MINOR", newSViv(STORABLE_BIN_MINOR));
7314 newCONSTSUB(stash, "BIN_WRITE_MINOR", newSViv(STORABLE_BIN_WRITE_MINOR));
7316 init_perinterp(aTHX);
7317 gv_fetchpv("Storable::drop_utf8", GV_ADDMULTI, SVt_PV);
7319 /* Only disable the used only once warning if we are in debugging mode. */
7320 gv_fetchpv("Storable::DEBUGME", GV_ADDMULTI, SVt_PV);
7322 #ifdef USE_56_INTERWORK_KLUDGE
7323 gv_fetchpv("Storable::interwork_56_64bit", GV_ADDMULTI, SVt_PV);
7330 init_perinterp(aTHX);
7334 # Store the transitive data closure of given object to disk.
7335 # Returns undef on error, a true value otherwise.
7339 # Same as pstore(), but network order is used for integers and doubles are
7340 # emitted as strings.
7349 RETVAL = do_store(aTHX_ f, obj, 0, ix, (SV **)0) ? &PL_sv_yes : &PL_sv_undef;
7350 /* do_store() can reallocate the stack, so need a sequence point to ensure
7351 that ST(0) knows about it. Hence using two statements. */
7357 # Store the transitive data closure of given object to memory.
7358 # Returns undef on error, a scalar value containing the data otherwise.
7362 # Same as mstore(), but network order is used for integers and doubles are
7363 # emitted as strings.
7371 RETVAL = &PL_sv_undef;
7372 if (!do_store(aTHX_ (PerlIO*) 0, obj, 0, ix, &RETVAL))
7373 RETVAL = &PL_sv_undef;
7378 pretrieve(f, flag = 6)
7382 RETVAL = pretrieve(aTHX_ f, flag);
7387 mretrieve(sv, flag = 6)
7391 RETVAL = mretrieve(aTHX_ sv, flag);
7399 RETVAL = dclone(aTHX_ sv);
7404 last_op_in_netorder()
7406 is_storing = ST_STORE
7407 is_retrieving = ST_RETRIEVE
7414 result = cxt->entry && (cxt->optype & ix) ? TRUE : FALSE;
7416 result = !!last_op_in_netorder(aTHX);
7418 ST(0) = boolSV(result);
7420 # so far readonly. we rather probe at install to be safe.
7432 RETVAL = MAX_DEPTH_HASH;