2 * Store and retrieve mechanism.
4 * Copyright (c) 1995-2000, Raphael Manfredi
6 * You may redistribute only under the same terms as Perl 5, as specified
7 * in the README file that comes with the distribution.
11 #define PERL_NO_GET_CONTEXT /* we want efficiency */
17 #include <patchlevel.h> /* Perl's one, needed since 5.6 */
20 #if !defined(PERL_VERSION) || PERL_VERSION < 8
21 #include "ppport.h" /* handle old perls */
25 #define DEBUGME /* Debug mode, turns assertions on as well */
26 #define DASSERT /* Assertion mode */
30 * Pre PerlIO time when none of USE_PERLIO and PERLIO_IS_STDIO is defined
31 * Provide them with the necessary defines so they can build with pre-5.004.
34 #ifndef PERLIO_IS_STDIO
36 #define PerlIO_getc(x) getc(x)
37 #define PerlIO_putc(f,x) putc(x,f)
38 #define PerlIO_read(x,y,z) fread(y,1,z,x)
39 #define PerlIO_write(x,y,z) fwrite(y,1,z,x)
40 #define PerlIO_stdoutf printf
41 #endif /* PERLIO_IS_STDIO */
42 #endif /* USE_PERLIO */
45 * Earlier versions of perl might be used, we can't assume they have the latest!
48 #ifndef PERL_VERSION /* For perls < 5.6 */
49 #define PERL_VERSION PATCHLEVEL
51 #define newRV_noinc(sv) ((Sv = newRV(sv)), --SvREFCNT(SvRV(Sv)), Sv)
53 #if (PATCHLEVEL <= 4) /* Older perls (<= 5.004) lack PL_ namespace */
54 #define PL_sv_yes sv_yes
55 #define PL_sv_no sv_no
56 #define PL_sv_undef sv_undef
57 #if (SUBVERSION <= 4) /* 5.004_04 has been reported to lack newSVpvn */
58 #define newSVpvn newSVpv
60 #endif /* PATCHLEVEL <= 4 */
61 #ifndef HvSHAREKEYS_off
62 #define HvSHAREKEYS_off(hv) /* Ignore */
64 #ifndef AvFILLp /* Older perls (<=5.003) lack AvFILLp */
65 #define AvFILLp AvFILL
67 typedef double NV; /* Older perls lack the NV type */
68 #define IVdf "ld" /* Various printf formats for Perl types */
72 #define INT2PTR(t,v) (t)(IV)(v)
73 #define PTR2UV(v) (unsigned long)(v)
74 #endif /* PERL_VERSION -- perls < 5.6 */
76 #ifndef NVef /* The following were not part of perl 5.6 */
77 #if defined(USE_LONG_DOUBLE) && \
78 defined(HAS_LONG_DOUBLE) && defined(PERL_PRIfldbl)
79 #define NVef PERL_PRIeldbl
80 #define NVff PERL_PRIfldbl
81 #define NVgf PERL_PRIgldbl
90 #ifndef PERL_UNUSED_DECL
92 # if (defined(__GNUC__) && defined(__cplusplus)) || defined(__INTEL_COMPILER)
93 # define PERL_UNUSED_DECL
95 # define PERL_UNUSED_DECL __attribute__((unused))
98 # define PERL_UNUSED_DECL
103 #define dNOOP extern int Perl___notused PERL_UNUSED_DECL
111 # define HvRITER_set(hv,r) (*HvRITER(hv) = r)
114 # define HvEITER_set(hv,r) (*HvEITER(hv) = r)
118 # define HvRITER_get HvRITER
121 # define HvEITER_get HvEITER
125 #define HvNAME_get HvNAME
128 #ifndef HvPLACEHOLDERS_get
129 # define HvPLACEHOLDERS_get HvPLACEHOLDERS
139 * TRACEME() will only output things when the $Storable::DEBUGME is true.
144 if (SvTRUE(perl_get_sv("Storable::DEBUGME", TRUE))) \
145 { PerlIO_stdoutf x; PerlIO_stdoutf("\n"); } \
152 #define ASSERT(x,y) \
155 PerlIO_stdoutf("ASSERT FAILED (\"%s\", line %d): ", \
156 __FILE__, __LINE__); \
157 PerlIO_stdoutf y; PerlIO_stdoutf("\n"); \
168 #define C(x) ((char) (x)) /* For markers with dynamic retrieval handling */
170 #define SX_OBJECT C(0) /* Already stored object */
171 #define SX_LSCALAR C(1) /* Scalar (large binary) follows (length, data) */
172 #define SX_ARRAY C(2) /* Array forthcominng (size, item list) */
173 #define SX_HASH C(3) /* Hash forthcoming (size, key/value pair list) */
174 #define SX_REF C(4) /* Reference to object forthcoming */
175 #define SX_UNDEF C(5) /* Undefined scalar */
176 #define SX_INTEGER C(6) /* Integer forthcoming */
177 #define SX_DOUBLE C(7) /* Double forthcoming */
178 #define SX_BYTE C(8) /* (signed) byte forthcoming */
179 #define SX_NETINT C(9) /* Integer in network order forthcoming */
180 #define SX_SCALAR C(10) /* Scalar (binary, small) follows (length, data) */
181 #define SX_TIED_ARRAY C(11) /* Tied array forthcoming */
182 #define SX_TIED_HASH C(12) /* Tied hash forthcoming */
183 #define SX_TIED_SCALAR C(13) /* Tied scalar forthcoming */
184 #define SX_SV_UNDEF C(14) /* Perl's immortal PL_sv_undef */
185 #define SX_SV_YES C(15) /* Perl's immortal PL_sv_yes */
186 #define SX_SV_NO C(16) /* Perl's immortal PL_sv_no */
187 #define SX_BLESS C(17) /* Object is blessed */
188 #define SX_IX_BLESS C(18) /* Object is blessed, classname given by index */
189 #define SX_HOOK C(19) /* Stored via hook, user-defined */
190 #define SX_OVERLOAD C(20) /* Overloaded reference */
191 #define SX_TIED_KEY C(21) /* Tied magic key forthcoming */
192 #define SX_TIED_IDX C(22) /* Tied magic index forthcoming */
193 #define SX_UTF8STR C(23) /* UTF-8 string forthcoming (small) */
194 #define SX_LUTF8STR C(24) /* UTF-8 string forthcoming (large) */
195 #define SX_FLAG_HASH C(25) /* Hash with flags forthcoming (size, flags, key/flags/value triplet list) */
196 #define SX_CODE C(26) /* Code references as perl source code */
197 #define SX_WEAKREF C(27) /* Weak reference to object forthcoming */
198 #define SX_WEAKOVERLOAD C(28) /* Overloaded weak reference */
199 #define SX_ERROR C(29) /* Error */
202 * Those are only used to retrieve "old" pre-0.6 binary images.
204 #define SX_ITEM 'i' /* An array item introducer */
205 #define SX_IT_UNDEF 'I' /* Undefined array item */
206 #define SX_KEY 'k' /* A hash key introducer */
207 #define SX_VALUE 'v' /* A hash value introducer */
208 #define SX_VL_UNDEF 'V' /* Undefined hash value */
211 * Those are only used to retrieve "old" pre-0.7 binary images
214 #define SX_CLASS 'b' /* Object is blessed, class name length <255 */
215 #define SX_LG_CLASS 'B' /* Object is blessed, class name length >255 */
216 #define SX_STORED 'X' /* End of object */
219 * Limits between short/long length representation.
222 #define LG_SCALAR 255 /* Large scalar length limit */
223 #define LG_BLESS 127 /* Large classname bless limit */
229 #define ST_STORE 0x1 /* Store operation */
230 #define ST_RETRIEVE 0x2 /* Retrieval operation */
231 #define ST_CLONE 0x4 /* Deep cloning operation */
234 * The following structure is used for hash table key retrieval. Since, when
235 * retrieving objects, we'll be facing blessed hash references, it's best
236 * to pre-allocate that buffer once and resize it as the need arises, never
237 * freeing it (keys will be saved away someplace else anyway, so even large
238 * keys are not enough a motivation to reclaim that space).
240 * This structure is also used for memory store/retrieve operations which
241 * happen in a fixed place before being malloc'ed elsewhere if persistency
242 * is required. Hence the aptr pointer.
245 char *arena; /* Will hold hash key strings, resized as needed */
246 STRLEN asiz; /* Size of aforementionned buffer */
247 char *aptr; /* Arena pointer, for in-place read/write ops */
248 char *aend; /* First invalid address */
253 * A hash table records the objects which have already been stored.
254 * Those are referred to as SX_OBJECT in the file, and their "tag" (i.e.
255 * an arbitrary sequence number) is used to identify them.
258 * An array table records the objects which have already been retrieved,
259 * as seen by the tag determind by counting the objects themselves. The
260 * reference to that retrieved object is kept in the table, and is returned
261 * when an SX_OBJECT is found bearing that same tag.
263 * The same processing is used to record "classname" for blessed objects:
264 * indexing by a hash at store time, and via an array at retrieve time.
267 typedef unsigned long stag_t; /* Used by pre-0.6 binary format */
270 * The following "thread-safe" related defines were contributed by
271 * Murray Nesbitt <murray@activestate.com> and integrated by RAM, who
272 * only renamed things a little bit to ensure consistency with surrounding
273 * code. -- RAM, 14/09/1999
275 * The original patch suffered from the fact that the stcxt_t structure
276 * was global. Murray tried to minimize the impact on the code as much as
279 * Starting with 0.7, Storable can be re-entrant, via the STORABLE_xxx hooks
280 * on objects. Therefore, the notion of context needs to be generalized,
284 #define MY_VERSION "Storable(" XS_VERSION ")"
288 * Conditional UTF8 support.
292 #define STORE_UTF8STR(pv, len) STORE_PV_LEN(pv, len, SX_UTF8STR, SX_LUTF8STR)
293 #define HAS_UTF8_SCALARS
295 #define HAS_UTF8_HASHES
298 /* 5.6 perl has utf8 scalars but not hashes */
302 #define STORE_UTF8STR(pv, len) CROAK(("panic: storing UTF8 in non-UTF8 perl"))
305 #define UTF8_CROAK() CROAK(("Cannot retrieve UTF8 data in non-UTF8 perl"))
308 #define WEAKREF_CROAK() CROAK(("Cannot retrieve weak references in this perl"))
311 #ifdef HvPLACEHOLDERS
312 #define HAS_RESTRICTED_HASHES
314 #define HVhek_PLACEHOLD 0x200
315 #define RESTRICTED_HASH_CROAK() CROAK(("Cannot retrieve restricted hash"))
319 #define HAS_HASH_KEY_FLAGS
323 #define USE_PTR_TABLE
327 * Fields s_tainted and s_dirty are prefixed with s_ because Perl's include
328 * files remap tainted and dirty when threading is enabled. That's bad for
329 * perl to remap such common words. -- RAM, 29/09/00
333 typedef struct stcxt {
334 int entry; /* flags recursion */
335 int optype; /* type of traversal operation */
336 /* which objects have been seen, store time.
337 tags are numbers, which are cast to (SV *) and stored directly */
339 /* use pseen if we have ptr_tables. We have to store tag+1, because
340 tag numbers start at 0, and we can't store (SV *) 0 in a ptr_table
341 without it being confused for a fetch lookup failure. */
342 struct ptr_tbl *pseen;
343 /* Still need hseen for the 0.6 file format code. */
346 AV *hook_seen; /* which SVs were returned by STORABLE_freeze() */
347 AV *aseen; /* which objects have been seen, retrieve time */
348 IV where_is_undef; /* index in aseen of PL_sv_undef */
349 HV *hclass; /* which classnames have been seen, store time */
350 AV *aclass; /* which classnames have been seen, retrieve time */
351 HV *hook; /* cache for hook methods per class name */
352 IV tagnum; /* incremented at store time for each seen object */
353 IV classnum; /* incremented at store time for each seen classname */
354 int netorder; /* true if network order used */
355 int s_tainted; /* true if input source is tainted, at retrieve time */
356 int forgive_me; /* whether to be forgiving... */
357 int deparse; /* whether to deparse code refs */
358 SV *eval; /* whether to eval source code */
359 int canonical; /* whether to store hashes sorted by key */
360 #ifndef HAS_RESTRICTED_HASHES
361 int derestrict; /* whether to downgrade restrcted hashes */
364 int use_bytes; /* whether to bytes-ify utf8 */
366 int accept_future_minor; /* croak immediately on future minor versions? */
367 int s_dirty; /* context is dirty due to CROAK() -- can be cleaned */
368 int membuf_ro; /* true means membuf is read-only and msaved is rw */
369 struct extendable keybuf; /* for hash key retrieval */
370 struct extendable membuf; /* for memory store/retrieve operations */
371 struct extendable msaved; /* where potentially valid mbuf is saved */
372 PerlIO *fio; /* where I/O are performed, NULL for memory */
373 int ver_major; /* major of version for retrieved object */
374 int ver_minor; /* minor of version for retrieved object */
375 SV *(**retrieve_vtbl)(pTHX_ struct stcxt *, char *); /* retrieve dispatch table */
376 SV *prev; /* contexts chained backwards in real recursion */
377 SV *my_sv; /* the blessed scalar who's SvPVX() I am */
380 #define NEW_STORABLE_CXT_OBJ(cxt) \
382 SV *self = newSV(sizeof(stcxt_t) - 1); \
383 SV *my_sv = newRV_noinc(self); \
384 sv_bless(my_sv, gv_stashpv("Storable::Cxt", TRUE)); \
385 cxt = (stcxt_t *)SvPVX(self); \
386 Zero(cxt, 1, stcxt_t); \
387 cxt->my_sv = my_sv; \
390 #if defined(MULTIPLICITY) || defined(PERL_OBJECT) || defined(PERL_CAPI)
392 #if (PATCHLEVEL <= 4) && (SUBVERSION < 68)
394 SV *perinterp_sv = perl_get_sv(MY_VERSION, FALSE)
395 #else /* >= perl5.004_68 */
397 SV *perinterp_sv = *hv_fetch(PL_modglobal, \
398 MY_VERSION, sizeof(MY_VERSION)-1, TRUE)
399 #endif /* < perl5.004_68 */
401 #define dSTCXT_PTR(T,name) \
402 T name = ((perinterp_sv && SvIOK(perinterp_sv) && SvIVX(perinterp_sv) \
403 ? (T)SvPVX(SvRV(INT2PTR(SV*,SvIVX(perinterp_sv)))) : (T) 0))
406 dSTCXT_PTR(stcxt_t *, cxt)
410 NEW_STORABLE_CXT_OBJ(cxt); \
411 sv_setiv(perinterp_sv, PTR2IV(cxt->my_sv))
413 #define SET_STCXT(x) \
416 sv_setiv(perinterp_sv, PTR2IV(x->my_sv)); \
419 #else /* !MULTIPLICITY && !PERL_OBJECT && !PERL_CAPI */
421 static stcxt_t *Context_ptr = NULL;
422 #define dSTCXT stcxt_t *cxt = Context_ptr
423 #define SET_STCXT(x) Context_ptr = x
426 NEW_STORABLE_CXT_OBJ(cxt); \
430 #endif /* MULTIPLICITY || PERL_OBJECT || PERL_CAPI */
434 * Croaking implies a memory leak, since we don't use setjmp/longjmp
435 * to catch the exit and free memory used during store or retrieve
436 * operations. This is not too difficult to fix, but I need to understand
437 * how Perl does it, and croaking is exceptional anyway, so I lack the
438 * motivation to do it.
440 * The current workaround is to mark the context as dirty when croaking,
441 * so that data structures can be freed whenever we renter Storable code
442 * (but only *then*: it's a workaround, not a fix).
444 * This is also imperfect, because we don't really know how far they trapped
445 * the croak(), and when we were recursing, we won't be able to clean anything
446 * but the topmost context stacked.
449 #define CROAK(x) STMT_START { cxt->s_dirty = 1; croak x; } STMT_END
452 * End of "thread-safe" related definitions.
458 * Keep only the low 32 bits of a pointer (used for tags, which are not
463 #define LOW_32BITS(x) ((I32) (x))
465 #define LOW_32BITS(x) ((I32) ((unsigned long) (x) & 0xffffffffUL))
471 * Hack for Crays, where sizeof(I32) == 8, and which are big-endians.
472 * Used in the WLEN and RLEN macros.
476 #define oI(x) ((I32 *) ((char *) (x) + 4))
477 #define oS(x) ((x) - 4)
478 #define oC(x) (x = 0)
487 * key buffer handling
489 #define kbuf (cxt->keybuf).arena
490 #define ksiz (cxt->keybuf).asiz
494 TRACEME(("** allocating kbuf of 128 bytes")); \
495 New(10003, kbuf, 128, char); \
502 TRACEME(("** extending kbuf to %d bytes (had %d)", x+1, ksiz)); \
503 Renew(kbuf, x+1, char); \
509 * memory buffer handling
511 #define mbase (cxt->membuf).arena
512 #define msiz (cxt->membuf).asiz
513 #define mptr (cxt->membuf).aptr
514 #define mend (cxt->membuf).aend
516 #define MGROW (1 << 13)
517 #define MMASK (MGROW - 1)
519 #define round_mgrow(x) \
520 ((unsigned long) (((unsigned long) (x) + MMASK) & ~MMASK))
521 #define trunc_int(x) \
522 ((unsigned long) ((unsigned long) (x) & ~(sizeof(int)-1)))
523 #define int_aligned(x) \
524 ((unsigned long) (x) == trunc_int(x))
526 #define MBUF_INIT(x) \
529 TRACEME(("** allocating mbase of %d bytes", MGROW)); \
530 New(10003, mbase, MGROW, char); \
531 msiz = (STRLEN)MGROW; \
537 mend = mbase + msiz; \
540 #define MBUF_TRUNC(x) mptr = mbase + x
541 #define MBUF_SIZE() (mptr - mbase)
547 * Those macros are used in do_retrieve() to save the current memory
548 * buffer into cxt->msaved, before MBUF_LOAD() can be used to retrieve
549 * data from a string.
551 #define MBUF_SAVE_AND_LOAD(in) \
553 ASSERT(!cxt->membuf_ro, ("mbase not already saved")); \
554 cxt->membuf_ro = 1; \
555 TRACEME(("saving mbuf")); \
556 StructCopy(&cxt->membuf, &cxt->msaved, struct extendable); \
560 #define MBUF_RESTORE() \
562 ASSERT(cxt->membuf_ro, ("mbase is read-only")); \
563 cxt->membuf_ro = 0; \
564 TRACEME(("restoring mbuf")); \
565 StructCopy(&cxt->msaved, &cxt->membuf, struct extendable); \
569 * Use SvPOKp(), because SvPOK() fails on tainted scalars.
570 * See store_scalar() for other usage of this workaround.
572 #define MBUF_LOAD(v) \
574 ASSERT(cxt->membuf_ro, ("mbase is read-only")); \
576 CROAK(("Not a scalar string")); \
577 mptr = mbase = SvPV(v, msiz); \
578 mend = mbase + msiz; \
581 #define MBUF_XTEND(x) \
583 int nsz = (int) round_mgrow((x)+msiz); \
584 int offset = mptr - mbase; \
585 ASSERT(!cxt->membuf_ro, ("mbase is not read-only")); \
586 TRACEME(("** extending mbase from %d to %d bytes (wants %d new)", \
588 Renew(mbase, nsz, char); \
590 mptr = mbase + offset; \
591 mend = mbase + nsz; \
594 #define MBUF_CHK(x) \
596 if ((mptr + (x)) > mend) \
600 #define MBUF_GETC(x) \
603 x = (int) (unsigned char) *mptr++; \
609 #define MBUF_GETINT(x) \
612 if ((mptr + 4) <= mend) { \
613 memcpy(oI(&x), mptr, 4); \
619 #define MBUF_GETINT(x) \
621 if ((mptr + sizeof(int)) <= mend) { \
622 if (int_aligned(mptr)) \
625 memcpy(&x, mptr, sizeof(int)); \
626 mptr += sizeof(int); \
632 #define MBUF_READ(x,s) \
634 if ((mptr + (s)) <= mend) { \
635 memcpy(x, mptr, s); \
641 #define MBUF_SAFEREAD(x,s,z) \
643 if ((mptr + (s)) <= mend) { \
644 memcpy(x, mptr, s); \
652 #define MBUF_PUTC(c) \
655 *mptr++ = (char) c; \
658 *mptr++ = (char) c; \
663 #define MBUF_PUTINT(i) \
666 memcpy(mptr, oI(&i), 4); \
670 #define MBUF_PUTINT(i) \
672 MBUF_CHK(sizeof(int)); \
673 if (int_aligned(mptr)) \
676 memcpy(mptr, &i, sizeof(int)); \
677 mptr += sizeof(int); \
681 #define MBUF_WRITE(x,s) \
684 memcpy(mptr, x, s); \
689 * Possible return values for sv_type().
693 #define svis_SCALAR 1
697 #define svis_TIED_ITEM 5
705 #define SHF_TYPE_MASK 0x03
706 #define SHF_LARGE_CLASSLEN 0x04
707 #define SHF_LARGE_STRLEN 0x08
708 #define SHF_LARGE_LISTLEN 0x10
709 #define SHF_IDX_CLASSNAME 0x20
710 #define SHF_NEED_RECURSE 0x40
711 #define SHF_HAS_LIST 0x80
714 * Types for SX_HOOK (last 2 bits in flags).
720 #define SHT_EXTRA 3 /* Read extra byte for type */
723 * The following are held in the "extra byte"...
726 #define SHT_TSCALAR 4 /* 4 + 0 -- tied scalar */
727 #define SHT_TARRAY 5 /* 4 + 1 -- tied array */
728 #define SHT_THASH 6 /* 4 + 2 -- tied hash */
731 * per hash flags for flagged hashes
734 #define SHV_RESTRICTED 0x01
737 * per key flags for flagged hashes
740 #define SHV_K_UTF8 0x01
741 #define SHV_K_WASUTF8 0x02
742 #define SHV_K_LOCKED 0x04
743 #define SHV_K_ISSV 0x08
744 #define SHV_K_PLACEHOLDER 0x10
747 * Before 0.6, the magic string was "perl-store" (binary version number 0).
749 * Since 0.6 introduced many binary incompatibilities, the magic string has
750 * been changed to "pst0" to allow an old image to be properly retrieved by
751 * a newer Storable, but ensure a newer image cannot be retrieved with an
754 * At 0.7, objects are given the ability to serialize themselves, and the
755 * set of markers is extended, backward compatibility is not jeopardized,
756 * so the binary version number could have remained unchanged. To correctly
757 * spot errors if a file making use of 0.7-specific extensions is given to
758 * 0.6 for retrieval, the binary version was moved to "2". And I'm introducing
759 * a "minor" version, to better track this kind of evolution from now on.
762 static const char old_magicstr[] = "perl-store"; /* Magic number before 0.6 */
763 static const char magicstr[] = "pst0"; /* Used as a magic number */
765 #define MAGICSTR_BYTES 'p','s','t','0'
766 #define OLDMAGICSTR_BYTES 'p','e','r','l','-','s','t','o','r','e'
768 /* 5.6.x introduced the ability to have IVs as long long.
769 However, Configure still defined BYTEORDER based on the size of a long.
770 Storable uses the BYTEORDER value as part of the header, but doesn't
771 explicity store sizeof(IV) anywhere in the header. Hence on 5.6.x built
772 with IV as long long on a platform that uses Configure (ie most things
773 except VMS and Windows) headers are identical for the different IV sizes,
774 despite the files containing some fields based on sizeof(IV)
776 5.8 is consistent - the following redifinition kludge is only needed on
777 5.6.x, but the interwork is needed on 5.8 while data survives in files
782 #if defined (IVSIZE) && (IVSIZE == 8) && (LONGSIZE == 4)
783 #ifndef NO_56_INTERWORK_KLUDGE
784 #define USE_56_INTERWORK_KLUDGE
786 #if BYTEORDER == 0x1234
788 #define BYTEORDER 0x12345678
790 #if BYTEORDER == 0x4321
792 #define BYTEORDER 0x87654321
797 #if BYTEORDER == 0x1234
798 #define BYTEORDER_BYTES '1','2','3','4'
800 #if BYTEORDER == 0x12345678
801 #define BYTEORDER_BYTES '1','2','3','4','5','6','7','8'
802 #ifdef USE_56_INTERWORK_KLUDGE
803 #define BYTEORDER_BYTES_56 '1','2','3','4'
806 #if BYTEORDER == 0x87654321
807 #define BYTEORDER_BYTES '8','7','6','5','4','3','2','1'
808 #ifdef USE_56_INTERWORK_KLUDGE
809 #define BYTEORDER_BYTES_56 '4','3','2','1'
812 #if BYTEORDER == 0x4321
813 #define BYTEORDER_BYTES '4','3','2','1'
815 #error Unknown byteorder. Please append your byteorder to Storable.xs
821 static const char byteorderstr[] = {BYTEORDER_BYTES, 0};
822 #ifdef USE_56_INTERWORK_KLUDGE
823 static const char byteorderstr_56[] = {BYTEORDER_BYTES_56, 0};
826 #define STORABLE_BIN_MAJOR 2 /* Binary major "version" */
827 #define STORABLE_BIN_MINOR 7 /* Binary minor "version" */
829 #if (PATCHLEVEL <= 5)
830 #define STORABLE_BIN_WRITE_MINOR 4
833 * Perl 5.6.0 onwards can do weak references.
835 #define STORABLE_BIN_WRITE_MINOR 7
836 #endif /* (PATCHLEVEL <= 5) */
838 #if (PATCHLEVEL < 8 || (PATCHLEVEL == 8 && SUBVERSION < 1))
839 #define PL_sv_placeholder PL_sv_undef
843 * Useful store shortcuts...
847 * Note that if you put more than one mark for storing a particular
848 * type of thing, *and* in the retrieve_foo() function you mark both
849 * the thingy's you get off with SEEN(), you *must* increase the
850 * tagnum with cxt->tagnum++ along with this macro!
857 else if (PerlIO_putc(cxt->fio, x) == EOF) \
861 #define WRITE_I32(x) \
863 ASSERT(sizeof(x) == sizeof(I32), ("writing an I32")); \
866 else if (PerlIO_write(cxt->fio, oI(&x), oS(sizeof(x))) != oS(sizeof(x))) \
873 if (cxt->netorder) { \
874 int y = (int) htonl(x); \
877 else if (PerlIO_write(cxt->fio,oI(&y),oS(sizeof(y))) != oS(sizeof(y))) \
882 else if (PerlIO_write(cxt->fio,oI(&x),oS(sizeof(x))) != oS(sizeof(x))) \
887 #define WLEN(x) WRITE_I32(x)
894 else if (PerlIO_write(cxt->fio, x, y) != y) \
898 #define STORE_PV_LEN(pv, len, small, large) \
900 if (len <= LG_SCALAR) { \
901 unsigned char clen = (unsigned char) len; \
913 #define STORE_SCALAR(pv, len) STORE_PV_LEN(pv, len, SX_SCALAR, SX_LSCALAR)
916 * Store &PL_sv_undef in arrays without recursing through store().
918 #define STORE_SV_UNDEF() \
921 PUTMARK(SX_SV_UNDEF); \
925 * Useful retrieve shortcuts...
929 (cxt->fio ? PerlIO_getc(cxt->fio) : (mptr >= mend ? EOF : (int) *mptr++))
935 else if ((int) (x = PerlIO_getc(cxt->fio)) == EOF) \
939 #define READ_I32(x) \
941 ASSERT(sizeof(x) == sizeof(I32), ("reading an I32")); \
945 else if (PerlIO_read(cxt->fio, oI(&x), oS(sizeof(x))) != oS(sizeof(x))) \
955 else if (PerlIO_read(cxt->fio, oI(&x), oS(sizeof(x))) != oS(sizeof(x))) \
958 x = (int) ntohl(x); \
961 #define RLEN(x) READ_I32(x)
968 else if (PerlIO_read(cxt->fio, x, y) != y) \
972 #define SAFEREAD(x,y,z) \
975 MBUF_SAFEREAD(x,y,z); \
976 else if (PerlIO_read(cxt->fio, x, y) != y) { \
983 * This macro is used at retrieve time, to remember where object 'y', bearing a
984 * given tag 'tagnum', has been retrieved. Next time we see an SX_OBJECT marker,
985 * we'll therefore know where it has been retrieved and will be able to
986 * share the same reference, as in the original stored memory image.
988 * We also need to bless objects ASAP for hooks (which may compute "ref $x"
989 * on the objects given to STORABLE_thaw and expect that to be defined), and
990 * also for overloaded objects (for which we might not find the stash if the
991 * object is not blessed yet--this might occur for overloaded objects that
992 * refer to themselves indirectly: if we blessed upon return from a sub
993 * retrieve(), the SX_OBJECT marker we'd found could not have overloading
994 * restored on it because the underlying object would not be blessed yet!).
996 * To achieve that, the class name of the last retrieved object is passed down
997 * recursively, and the first SEEN() call for which the class name is not NULL
998 * will bless the object.
1000 * i should be true iff sv is immortal (ie PL_sv_yes, PL_sv_no or PL_sv_undef)
1002 #define SEEN(y,c,i) \
1006 if (av_store(cxt->aseen, cxt->tagnum++, i ? (SV*)(y) : SvREFCNT_inc(y)) == 0) \
1008 TRACEME(("aseen(#%d) = 0x%"UVxf" (refcnt=%d)", cxt->tagnum-1, \
1009 PTR2UV(y), SvREFCNT(y)-1)); \
1011 BLESS((SV *) (y), c); \
1015 * Bless `s' in `p', via a temporary reference, required by sv_bless().
1017 #define BLESS(s,p) \
1021 TRACEME(("blessing 0x%"UVxf" in %s", PTR2UV(s), (p))); \
1022 stash = gv_stashpv((p), TRUE); \
1023 ref = newRV_noinc(s); \
1024 (void) sv_bless(ref, stash); \
1025 SvRV_set(ref, NULL); \
1026 SvREFCNT_dec(ref); \
1029 * sort (used in store_hash) - conditionally use qsort when
1030 * sortsv is not available ( <= 5.6.1 ).
1033 #if (PATCHLEVEL <= 6)
1035 #if defined(USE_ITHREADS)
1037 #define STORE_HASH_SORT \
1039 PerlInterpreter *orig_perl = PERL_GET_CONTEXT; \
1040 SAVESPTR(orig_perl); \
1041 PERL_SET_CONTEXT(aTHX); \
1042 qsort((char *) AvARRAY(av), len, sizeof(SV *), sortcmp); \
1045 #else /* ! USE_ITHREADS */
1047 #define STORE_HASH_SORT \
1048 qsort((char *) AvARRAY(av), len, sizeof(SV *), sortcmp);
1050 #endif /* USE_ITHREADS */
1052 #else /* PATCHLEVEL > 6 */
1054 #define STORE_HASH_SORT \
1055 sortsv(AvARRAY(av), len, Perl_sv_cmp);
1057 #endif /* PATCHLEVEL <= 6 */
1059 static int store(pTHX_ stcxt_t *cxt, SV *sv);
1060 static SV *retrieve(pTHX_ stcxt_t *cxt, char *cname);
1063 * Dynamic dispatching table for SV store.
1066 static int store_ref(pTHX_ stcxt_t *cxt, SV *sv);
1067 static int store_scalar(pTHX_ stcxt_t *cxt, SV *sv);
1068 static int store_array(pTHX_ stcxt_t *cxt, AV *av);
1069 static int store_hash(pTHX_ stcxt_t *cxt, HV *hv);
1070 static int store_tied(pTHX_ stcxt_t *cxt, SV *sv);
1071 static int store_tied_item(pTHX_ stcxt_t *cxt, SV *sv);
1072 static int store_code(pTHX_ stcxt_t *cxt, CV *cv);
1073 static int store_other(pTHX_ stcxt_t *cxt, SV *sv);
1074 static int store_blessed(pTHX_ stcxt_t *cxt, SV *sv, int type, HV *pkg);
1076 typedef int (*sv_store_t)(pTHX_ stcxt_t *cxt, SV *sv);
1078 static const sv_store_t sv_store[] = {
1079 (sv_store_t)store_ref, /* svis_REF */
1080 (sv_store_t)store_scalar, /* svis_SCALAR */
1081 (sv_store_t)store_array, /* svis_ARRAY */
1082 (sv_store_t)store_hash, /* svis_HASH */
1083 (sv_store_t)store_tied, /* svis_TIED */
1084 (sv_store_t)store_tied_item, /* svis_TIED_ITEM */
1085 (sv_store_t)store_code, /* svis_CODE */
1086 (sv_store_t)store_other, /* svis_OTHER */
1089 #define SV_STORE(x) (*sv_store[x])
1092 * Dynamic dispatching tables for SV retrieval.
1095 static SV *retrieve_lscalar(pTHX_ stcxt_t *cxt, char *cname);
1096 static SV *retrieve_lutf8str(pTHX_ stcxt_t *cxt, char *cname);
1097 static SV *old_retrieve_array(pTHX_ stcxt_t *cxt, char *cname);
1098 static SV *old_retrieve_hash(pTHX_ stcxt_t *cxt, char *cname);
1099 static SV *retrieve_ref(pTHX_ stcxt_t *cxt, char *cname);
1100 static SV *retrieve_undef(pTHX_ stcxt_t *cxt, char *cname);
1101 static SV *retrieve_integer(pTHX_ stcxt_t *cxt, char *cname);
1102 static SV *retrieve_double(pTHX_ stcxt_t *cxt, char *cname);
1103 static SV *retrieve_byte(pTHX_ stcxt_t *cxt, char *cname);
1104 static SV *retrieve_netint(pTHX_ stcxt_t *cxt, char *cname);
1105 static SV *retrieve_scalar(pTHX_ stcxt_t *cxt, char *cname);
1106 static SV *retrieve_utf8str(pTHX_ stcxt_t *cxt, char *cname);
1107 static SV *retrieve_tied_array(pTHX_ stcxt_t *cxt, char *cname);
1108 static SV *retrieve_tied_hash(pTHX_ stcxt_t *cxt, char *cname);
1109 static SV *retrieve_tied_scalar(pTHX_ stcxt_t *cxt, char *cname);
1110 static SV *retrieve_other(pTHX_ stcxt_t *cxt, char *cname);
1112 typedef SV* (*sv_retrieve_t)(pTHX_ stcxt_t *cxt, char *name);
1114 static const sv_retrieve_t sv_old_retrieve[] = {
1115 0, /* SX_OBJECT -- entry unused dynamically */
1116 (sv_retrieve_t)retrieve_lscalar, /* SX_LSCALAR */
1117 (sv_retrieve_t)old_retrieve_array, /* SX_ARRAY -- for pre-0.6 binaries */
1118 (sv_retrieve_t)old_retrieve_hash, /* SX_HASH -- for pre-0.6 binaries */
1119 (sv_retrieve_t)retrieve_ref, /* SX_REF */
1120 (sv_retrieve_t)retrieve_undef, /* SX_UNDEF */
1121 (sv_retrieve_t)retrieve_integer, /* SX_INTEGER */
1122 (sv_retrieve_t)retrieve_double, /* SX_DOUBLE */
1123 (sv_retrieve_t)retrieve_byte, /* SX_BYTE */
1124 (sv_retrieve_t)retrieve_netint, /* SX_NETINT */
1125 (sv_retrieve_t)retrieve_scalar, /* SX_SCALAR */
1126 (sv_retrieve_t)retrieve_tied_array, /* SX_ARRAY */
1127 (sv_retrieve_t)retrieve_tied_hash, /* SX_HASH */
1128 (sv_retrieve_t)retrieve_tied_scalar, /* SX_SCALAR */
1129 (sv_retrieve_t)retrieve_other, /* SX_SV_UNDEF not supported */
1130 (sv_retrieve_t)retrieve_other, /* SX_SV_YES not supported */
1131 (sv_retrieve_t)retrieve_other, /* SX_SV_NO not supported */
1132 (sv_retrieve_t)retrieve_other, /* SX_BLESS not supported */
1133 (sv_retrieve_t)retrieve_other, /* SX_IX_BLESS not supported */
1134 (sv_retrieve_t)retrieve_other, /* SX_HOOK not supported */
1135 (sv_retrieve_t)retrieve_other, /* SX_OVERLOADED not supported */
1136 (sv_retrieve_t)retrieve_other, /* SX_TIED_KEY not supported */
1137 (sv_retrieve_t)retrieve_other, /* SX_TIED_IDX not supported */
1138 (sv_retrieve_t)retrieve_other, /* SX_UTF8STR not supported */
1139 (sv_retrieve_t)retrieve_other, /* SX_LUTF8STR not supported */
1140 (sv_retrieve_t)retrieve_other, /* SX_FLAG_HASH not supported */
1141 (sv_retrieve_t)retrieve_other, /* SX_CODE not supported */
1142 (sv_retrieve_t)retrieve_other, /* SX_WEAKREF not supported */
1143 (sv_retrieve_t)retrieve_other, /* SX_WEAKOVERLOAD not supported */
1144 (sv_retrieve_t)retrieve_other, /* SX_ERROR */
1147 static SV *retrieve_array(pTHX_ stcxt_t *cxt, char *cname);
1148 static SV *retrieve_hash(pTHX_ stcxt_t *cxt, char *cname);
1149 static SV *retrieve_sv_undef(pTHX_ stcxt_t *cxt, char *cname);
1150 static SV *retrieve_sv_yes(pTHX_ stcxt_t *cxt, char *cname);
1151 static SV *retrieve_sv_no(pTHX_ stcxt_t *cxt, char *cname);
1152 static SV *retrieve_blessed(pTHX_ stcxt_t *cxt, char *cname);
1153 static SV *retrieve_idx_blessed(pTHX_ stcxt_t *cxt, char *cname);
1154 static SV *retrieve_hook(pTHX_ stcxt_t *cxt, char *cname);
1155 static SV *retrieve_overloaded(pTHX_ stcxt_t *cxt, char *cname);
1156 static SV *retrieve_tied_key(pTHX_ stcxt_t *cxt, char *cname);
1157 static SV *retrieve_tied_idx(pTHX_ stcxt_t *cxt, char *cname);
1158 static SV *retrieve_flag_hash(pTHX_ stcxt_t *cxt, char *cname);
1159 static SV *retrieve_code(pTHX_ stcxt_t *cxt, char *cname);
1160 static SV *retrieve_weakref(pTHX_ stcxt_t *cxt, char *cname);
1161 static SV *retrieve_weakoverloaded(pTHX_ stcxt_t *cxt, char *cname);
1163 static const sv_retrieve_t sv_retrieve[] = {
1164 0, /* SX_OBJECT -- entry unused dynamically */
1165 (sv_retrieve_t)retrieve_lscalar, /* SX_LSCALAR */
1166 (sv_retrieve_t)retrieve_array, /* SX_ARRAY */
1167 (sv_retrieve_t)retrieve_hash, /* SX_HASH */
1168 (sv_retrieve_t)retrieve_ref, /* SX_REF */
1169 (sv_retrieve_t)retrieve_undef, /* SX_UNDEF */
1170 (sv_retrieve_t)retrieve_integer, /* SX_INTEGER */
1171 (sv_retrieve_t)retrieve_double, /* SX_DOUBLE */
1172 (sv_retrieve_t)retrieve_byte, /* SX_BYTE */
1173 (sv_retrieve_t)retrieve_netint, /* SX_NETINT */
1174 (sv_retrieve_t)retrieve_scalar, /* SX_SCALAR */
1175 (sv_retrieve_t)retrieve_tied_array, /* SX_ARRAY */
1176 (sv_retrieve_t)retrieve_tied_hash, /* SX_HASH */
1177 (sv_retrieve_t)retrieve_tied_scalar, /* SX_SCALAR */
1178 (sv_retrieve_t)retrieve_sv_undef, /* SX_SV_UNDEF */
1179 (sv_retrieve_t)retrieve_sv_yes, /* SX_SV_YES */
1180 (sv_retrieve_t)retrieve_sv_no, /* SX_SV_NO */
1181 (sv_retrieve_t)retrieve_blessed, /* SX_BLESS */
1182 (sv_retrieve_t)retrieve_idx_blessed, /* SX_IX_BLESS */
1183 (sv_retrieve_t)retrieve_hook, /* SX_HOOK */
1184 (sv_retrieve_t)retrieve_overloaded, /* SX_OVERLOAD */
1185 (sv_retrieve_t)retrieve_tied_key, /* SX_TIED_KEY */
1186 (sv_retrieve_t)retrieve_tied_idx, /* SX_TIED_IDX */
1187 (sv_retrieve_t)retrieve_utf8str, /* SX_UTF8STR */
1188 (sv_retrieve_t)retrieve_lutf8str, /* SX_LUTF8STR */
1189 (sv_retrieve_t)retrieve_flag_hash, /* SX_HASH */
1190 (sv_retrieve_t)retrieve_code, /* SX_CODE */
1191 (sv_retrieve_t)retrieve_weakref, /* SX_WEAKREF */
1192 (sv_retrieve_t)retrieve_weakoverloaded, /* SX_WEAKOVERLOAD */
1193 (sv_retrieve_t)retrieve_other, /* SX_ERROR */
1196 #define RETRIEVE(c,x) (*(c)->retrieve_vtbl[(x) >= SX_ERROR ? SX_ERROR : (x)])
1198 static SV *mbuf2sv(pTHX);
1201 *** Context management.
1207 * Called once per "thread" (interpreter) to initialize some global context.
1209 static void init_perinterp(pTHX)
1213 cxt->netorder = 0; /* true if network order used */
1214 cxt->forgive_me = -1; /* whether to be forgiving... */
1215 cxt->accept_future_minor = -1; /* would otherwise occur too late */
1221 * Called at the end of every context cleaning, to perform common reset
1224 static void reset_context(stcxt_t *cxt)
1228 cxt->optype &= ~(ST_STORE|ST_RETRIEVE); /* Leave ST_CLONE alone */
1232 * init_store_context
1234 * Initialize a new store context for real recursion.
1236 static void init_store_context(
1243 TRACEME(("init_store_context"));
1245 cxt->netorder = network_order;
1246 cxt->forgive_me = -1; /* Fetched from perl if needed */
1247 cxt->deparse = -1; /* Idem */
1248 cxt->eval = NULL; /* Idem */
1249 cxt->canonical = -1; /* Idem */
1250 cxt->tagnum = -1; /* Reset tag numbers */
1251 cxt->classnum = -1; /* Reset class numbers */
1252 cxt->fio = f; /* Where I/O are performed */
1253 cxt->optype = optype; /* A store, or a deep clone */
1254 cxt->entry = 1; /* No recursion yet */
1257 * The `hseen' table is used to keep track of each SV stored and their
1258 * associated tag numbers is special. It is "abused" because the
1259 * values stored are not real SV, just integers cast to (SV *),
1260 * which explains the freeing below.
1262 * It is also one possible bottlneck to achieve good storing speed,
1263 * so the "shared keys" optimization is turned off (unlikely to be
1264 * of any use here), and the hash table is "pre-extended". Together,
1265 * those optimizations increase the throughput by 12%.
1268 #ifdef USE_PTR_TABLE
1269 cxt->pseen = ptr_table_new();
1272 cxt->hseen = newHV(); /* Table where seen objects are stored */
1273 HvSHAREKEYS_off(cxt->hseen);
1276 * The following does not work well with perl5.004_04, and causes
1277 * a core dump later on, in a completely unrelated spot, which
1278 * makes me think there is a memory corruption going on.
1280 * Calling hv_ksplit(hseen, HBUCKETS) instead of manually hacking
1281 * it below does not make any difference. It seems to work fine
1282 * with perl5.004_68 but given the probable nature of the bug,
1283 * that does not prove anything.
1285 * It's a shame because increasing the amount of buckets raises
1286 * store() throughput by 5%, but until I figure this out, I can't
1287 * allow for this to go into production.
1289 * It is reported fixed in 5.005, hence the #if.
1291 #if PERL_VERSION >= 5
1292 #define HBUCKETS 4096 /* Buckets for %hseen */
1293 #ifndef USE_PTR_TABLE
1294 HvMAX(cxt->hseen) = HBUCKETS - 1; /* keys %hseen = $HBUCKETS; */
1299 * The `hclass' hash uses the same settings as `hseen' above, but it is
1300 * used to assign sequential tags (numbers) to class names for blessed
1303 * We turn the shared key optimization on.
1306 cxt->hclass = newHV(); /* Where seen classnames are stored */
1308 #if PERL_VERSION >= 5
1309 HvMAX(cxt->hclass) = HBUCKETS - 1; /* keys %hclass = $HBUCKETS; */
1313 * The `hook' hash table is used to keep track of the references on
1314 * the STORABLE_freeze hook routines, when found in some class name.
1316 * It is assumed that the inheritance tree will not be changed during
1317 * storing, and that no new method will be dynamically created by the
1321 cxt->hook = newHV(); /* Table where hooks are cached */
1324 * The `hook_seen' array keeps track of all the SVs returned by
1325 * STORABLE_freeze hooks for us to serialize, so that they are not
1326 * reclaimed until the end of the serialization process. Each SV is
1327 * only stored once, the first time it is seen.
1330 cxt->hook_seen = newAV(); /* Lists SVs returned by STORABLE_freeze */
1334 * clean_store_context
1336 * Clean store context by
1338 static void clean_store_context(pTHX_ stcxt_t *cxt)
1342 TRACEME(("clean_store_context"));
1344 ASSERT(cxt->optype & ST_STORE, ("was performing a store()"));
1347 * Insert real values into hashes where we stored faked pointers.
1350 #ifndef USE_PTR_TABLE
1352 hv_iterinit(cxt->hseen);
1353 while ((he = hv_iternext(cxt->hseen))) /* Extra () for -Wall, grr.. */
1354 HeVAL(he) = &PL_sv_undef;
1359 hv_iterinit(cxt->hclass);
1360 while ((he = hv_iternext(cxt->hclass))) /* Extra () for -Wall, grr.. */
1361 HeVAL(he) = &PL_sv_undef;
1365 * And now dispose of them...
1367 * The surrounding if() protection has been added because there might be
1368 * some cases where this routine is called more than once, during
1369 * exceptionnal events. This was reported by Marc Lehmann when Storable
1370 * is executed from mod_perl, and the fix was suggested by him.
1371 * -- RAM, 20/12/2000
1374 #ifdef USE_PTR_TABLE
1376 struct ptr_tbl *pseen = cxt->pseen;
1378 ptr_table_free(pseen);
1380 assert(!cxt->hseen);
1383 HV *hseen = cxt->hseen;
1386 sv_free((SV *) hseen);
1391 HV *hclass = cxt->hclass;
1394 sv_free((SV *) hclass);
1398 HV *hook = cxt->hook;
1401 sv_free((SV *) hook);
1404 if (cxt->hook_seen) {
1405 AV *hook_seen = cxt->hook_seen;
1407 av_undef(hook_seen);
1408 sv_free((SV *) hook_seen);
1411 cxt->forgive_me = -1; /* Fetched from perl if needed */
1412 cxt->deparse = -1; /* Idem */
1414 SvREFCNT_dec(cxt->eval);
1416 cxt->eval = NULL; /* Idem */
1417 cxt->canonical = -1; /* Idem */
1423 * init_retrieve_context
1425 * Initialize a new retrieve context for real recursion.
1427 static void init_retrieve_context(pTHX_ stcxt_t *cxt, int optype, int is_tainted)
1429 TRACEME(("init_retrieve_context"));
1432 * The hook hash table is used to keep track of the references on
1433 * the STORABLE_thaw hook routines, when found in some class name.
1435 * It is assumed that the inheritance tree will not be changed during
1436 * storing, and that no new method will be dynamically created by the
1440 cxt->hook = newHV(); /* Caches STORABLE_thaw */
1442 #ifdef USE_PTR_TABLE
1447 * If retrieving an old binary version, the cxt->retrieve_vtbl variable
1448 * was set to sv_old_retrieve. We'll need a hash table to keep track of
1449 * the correspondance between the tags and the tag number used by the
1450 * new retrieve routines.
1453 cxt->hseen = (((void*)cxt->retrieve_vtbl == (void*)sv_old_retrieve)
1456 cxt->aseen = newAV(); /* Where retrieved objects are kept */
1457 cxt->where_is_undef = -1; /* Special case for PL_sv_undef */
1458 cxt->aclass = newAV(); /* Where seen classnames are kept */
1459 cxt->tagnum = 0; /* Have to count objects... */
1460 cxt->classnum = 0; /* ...and class names as well */
1461 cxt->optype = optype;
1462 cxt->s_tainted = is_tainted;
1463 cxt->entry = 1; /* No recursion yet */
1464 #ifndef HAS_RESTRICTED_HASHES
1465 cxt->derestrict = -1; /* Fetched from perl if needed */
1467 #ifndef HAS_UTF8_ALL
1468 cxt->use_bytes = -1; /* Fetched from perl if needed */
1470 cxt->accept_future_minor = -1; /* Fetched from perl if needed */
1474 * clean_retrieve_context
1476 * Clean retrieve context by
1478 static void clean_retrieve_context(pTHX_ stcxt_t *cxt)
1480 TRACEME(("clean_retrieve_context"));
1482 ASSERT(cxt->optype & ST_RETRIEVE, ("was performing a retrieve()"));
1485 AV *aseen = cxt->aseen;
1488 sv_free((SV *) aseen);
1490 cxt->where_is_undef = -1;
1493 AV *aclass = cxt->aclass;
1496 sv_free((SV *) aclass);
1500 HV *hook = cxt->hook;
1503 sv_free((SV *) hook);
1507 HV *hseen = cxt->hseen;
1510 sv_free((SV *) hseen); /* optional HV, for backward compat. */
1513 #ifndef HAS_RESTRICTED_HASHES
1514 cxt->derestrict = -1; /* Fetched from perl if needed */
1516 #ifndef HAS_UTF8_ALL
1517 cxt->use_bytes = -1; /* Fetched from perl if needed */
1519 cxt->accept_future_minor = -1; /* Fetched from perl if needed */
1527 * A workaround for the CROAK bug: cleanup the last context.
1529 static void clean_context(pTHX_ stcxt_t *cxt)
1531 TRACEME(("clean_context"));
1533 ASSERT(cxt->s_dirty, ("dirty context"));
1538 ASSERT(!cxt->membuf_ro, ("mbase is not read-only"));
1540 if (cxt->optype & ST_RETRIEVE)
1541 clean_retrieve_context(aTHX_ cxt);
1542 else if (cxt->optype & ST_STORE)
1543 clean_store_context(aTHX_ cxt);
1547 ASSERT(!cxt->s_dirty, ("context is clean"));
1548 ASSERT(cxt->entry == 0, ("context is reset"));
1554 * Allocate a new context and push it on top of the parent one.
1555 * This new context is made globally visible via SET_STCXT().
1557 static stcxt_t *allocate_context(pTHX_ stcxt_t *parent_cxt)
1561 TRACEME(("allocate_context"));
1563 ASSERT(!parent_cxt->s_dirty, ("parent context clean"));
1565 NEW_STORABLE_CXT_OBJ(cxt);
1566 cxt->prev = parent_cxt->my_sv;
1569 ASSERT(!cxt->s_dirty, ("clean context"));
1577 * Free current context, which cannot be the "root" one.
1578 * Make the context underneath globally visible via SET_STCXT().
1580 static void free_context(pTHX_ stcxt_t *cxt)
1582 stcxt_t *prev = (stcxt_t *)(cxt->prev ? SvPVX(SvRV(cxt->prev)) : 0);
1584 TRACEME(("free_context"));
1586 ASSERT(!cxt->s_dirty, ("clean context"));
1587 ASSERT(prev, ("not freeing root context"));
1589 SvREFCNT_dec(cxt->my_sv);
1592 ASSERT(cxt, ("context not void"));
1602 * Tells whether we're in the middle of a store operation.
1604 int is_storing(pTHX)
1608 return cxt->entry && (cxt->optype & ST_STORE);
1614 * Tells whether we're in the middle of a retrieve operation.
1616 int is_retrieving(pTHX)
1620 return cxt->entry && (cxt->optype & ST_RETRIEVE);
1624 * last_op_in_netorder
1626 * Returns whether last operation was made using network order.
1628 * This is typically out-of-band information that might prove useful
1629 * to people wishing to convert native to network order data when used.
1631 int last_op_in_netorder(pTHX)
1635 return cxt->netorder;
1639 *** Hook lookup and calling routines.
1645 * A wrapper on gv_fetchmethod_autoload() which caches results.
1647 * Returns the routine reference as an SV*, or null if neither the package
1648 * nor its ancestors know about the method.
1650 static SV *pkg_fetchmeth(
1658 const char *hvname = HvNAME_get(pkg);
1662 * The following code is the same as the one performed by UNIVERSAL::can
1666 gv = gv_fetchmethod_autoload(pkg, method, FALSE);
1667 if (gv && isGV(gv)) {
1668 sv = newRV((SV*) GvCV(gv));
1669 TRACEME(("%s->%s: 0x%"UVxf, hvname, method, PTR2UV(sv)));
1671 sv = newSVsv(&PL_sv_undef);
1672 TRACEME(("%s->%s: not found", hvname, method));
1676 * Cache the result, ignoring failure: if we can't store the value,
1677 * it just won't be cached.
1680 (void) hv_store(cache, hvname, strlen(hvname), sv, 0);
1682 return SvOK(sv) ? sv : (SV *) 0;
1688 * Force cached value to be undef: hook ignored even if present.
1690 static void pkg_hide(
1696 const char *hvname = HvNAME_get(pkg);
1697 (void) hv_store(cache,
1698 hvname, strlen(hvname), newSVsv(&PL_sv_undef), 0);
1704 * Discard cached value: a whole fetch loop will be retried at next lookup.
1706 static void pkg_uncache(
1712 const char *hvname = HvNAME_get(pkg);
1713 (void) hv_delete(cache, hvname, strlen(hvname), G_DISCARD);
1719 * Our own "UNIVERSAL::can", which caches results.
1721 * Returns the routine reference as an SV*, or null if the object does not
1722 * know about the method.
1732 const char *hvname = HvNAME_get(pkg);
1734 TRACEME(("pkg_can for %s->%s", hvname, method));
1737 * Look into the cache to see whether we already have determined
1738 * where the routine was, if any.
1740 * NOTA BENE: we don't use `method' at all in our lookup, since we know
1741 * that only one hook (i.e. always the same) is cached in a given cache.
1744 svh = hv_fetch(cache, hvname, strlen(hvname), FALSE);
1748 TRACEME(("cached %s->%s: not found", hvname, method));
1751 TRACEME(("cached %s->%s: 0x%"UVxf,
1752 hvname, method, PTR2UV(sv)));
1757 TRACEME(("not cached yet"));
1758 return pkg_fetchmeth(aTHX_ cache, pkg, method); /* Fetch and cache */
1764 * Call routine as obj->hook(av) in scalar context.
1765 * Propagates the single returned value if not called in void context.
1767 static SV *scalar_call(
1779 TRACEME(("scalar_call (cloning=%d)", cloning));
1786 XPUSHs(sv_2mortal(newSViv(cloning))); /* Cloning flag */
1788 SV **ary = AvARRAY(av);
1789 int cnt = AvFILLp(av) + 1;
1791 XPUSHs(ary[0]); /* Frozen string */
1792 for (i = 1; i < cnt; i++) {
1793 TRACEME(("pushing arg #%d (0x%"UVxf")...",
1794 i, PTR2UV(ary[i])));
1795 XPUSHs(sv_2mortal(newRV(ary[i])));
1800 TRACEME(("calling..."));
1801 count = perl_call_sv(hook, flags); /* Go back to Perl code */
1802 TRACEME(("count = %d", count));
1808 SvREFCNT_inc(sv); /* We're returning it, must stay alive! */
1821 * Call routine obj->hook(cloning) in list context.
1822 * Returns the list of returned values in an array.
1824 static AV *array_call(
1835 TRACEME(("array_call (cloning=%d)", cloning));
1841 XPUSHs(obj); /* Target object */
1842 XPUSHs(sv_2mortal(newSViv(cloning))); /* Cloning flag */
1845 count = perl_call_sv(hook, G_ARRAY); /* Go back to Perl code */
1850 for (i = count - 1; i >= 0; i--) {
1852 av_store(av, i, SvREFCNT_inc(sv));
1865 * Lookup the class name in the `hclass' table and either assign it a new ID
1866 * or return the existing one, by filling in `classnum'.
1868 * Return true if the class was known, false if the ID was just generated.
1870 static int known_class(
1873 char *name, /* Class name */
1874 int len, /* Name length */
1878 HV *hclass = cxt->hclass;
1880 TRACEME(("known_class (%s)", name));
1883 * Recall that we don't store pointers in this hash table, but tags.
1884 * Therefore, we need LOW_32BITS() to extract the relevant parts.
1887 svh = hv_fetch(hclass, name, len, FALSE);
1889 *classnum = LOW_32BITS(*svh);
1894 * Unknown classname, we need to record it.
1898 if (!hv_store(hclass, name, len, INT2PTR(SV*, cxt->classnum), 0))
1899 CROAK(("Unable to record new classname"));
1901 *classnum = cxt->classnum;
1906 *** Sepcific store routines.
1912 * Store a reference.
1913 * Layout is SX_REF <object> or SX_OVERLOAD <object>.
1915 static int store_ref(pTHX_ stcxt_t *cxt, SV *sv)
1918 TRACEME(("store_ref (0x%"UVxf")", PTR2UV(sv)));
1921 * Follow reference, and check if target is overloaded.
1927 TRACEME(("ref (0x%"UVxf") is%s weak", PTR2UV(sv), is_weak ? "" : "n't"));
1932 HV *stash = (HV *) SvSTASH(sv);
1933 if (stash && Gv_AMG(stash)) {
1934 TRACEME(("ref (0x%"UVxf") is overloaded", PTR2UV(sv)));
1935 PUTMARK(is_weak ? SX_WEAKOVERLOAD : SX_OVERLOAD);
1937 PUTMARK(is_weak ? SX_WEAKREF : SX_REF);
1939 PUTMARK(is_weak ? SX_WEAKREF : SX_REF);
1941 return store(aTHX_ cxt, sv);
1949 * Layout is SX_LSCALAR <length> <data>, SX_SCALAR <length> <data> or SX_UNDEF.
1950 * The <data> section is omitted if <length> is 0.
1952 * If integer or double, the layout is SX_INTEGER <data> or SX_DOUBLE <data>.
1953 * Small integers (within [-127, +127]) are stored as SX_BYTE <byte>.
1955 static int store_scalar(pTHX_ stcxt_t *cxt, SV *sv)
1960 U32 flags = SvFLAGS(sv); /* "cc -O" may put it in register */
1962 TRACEME(("store_scalar (0x%"UVxf")", PTR2UV(sv)));
1965 * For efficiency, break the SV encapsulation by peaking at the flags
1966 * directly without using the Perl macros to avoid dereferencing
1967 * sv->sv_flags each time we wish to check the flags.
1970 if (!(flags & SVf_OK)) { /* !SvOK(sv) */
1971 if (sv == &PL_sv_undef) {
1972 TRACEME(("immortal undef"));
1973 PUTMARK(SX_SV_UNDEF);
1975 TRACEME(("undef at 0x%"UVxf, PTR2UV(sv)));
1982 * Always store the string representation of a scalar if it exists.
1983 * Gisle Aas provided me with this test case, better than a long speach:
1985 * perl -MDevel::Peek -le '$a="abc"; $a+0; Dump($a)'
1986 * SV = PVNV(0x80c8520)
1988 * FLAGS = (NOK,POK,pNOK,pPOK)
1991 * PV = 0x80c83d0 "abc"\0
1995 * Write SX_SCALAR, length, followed by the actual data.
1997 * Otherwise, write an SX_BYTE, SX_INTEGER or an SX_DOUBLE as
1998 * appropriate, followed by the actual (binary) data. A double
1999 * is written as a string if network order, for portability.
2001 * NOTE: instead of using SvNOK(sv), we test for SvNOKp(sv).
2002 * The reason is that when the scalar value is tainted, the SvNOK(sv)
2005 * The test for a read-only scalar with both POK and NOK set is meant
2006 * to quickly detect &PL_sv_yes and &PL_sv_no without having to pay the
2007 * address comparison for each scalar we store.
2010 #define SV_MAYBE_IMMORTAL (SVf_READONLY|SVf_POK|SVf_NOK)
2012 if ((flags & SV_MAYBE_IMMORTAL) == SV_MAYBE_IMMORTAL) {
2013 if (sv == &PL_sv_yes) {
2014 TRACEME(("immortal yes"));
2016 } else if (sv == &PL_sv_no) {
2017 TRACEME(("immortal no"));
2020 pv = SvPV(sv, len); /* We know it's SvPOK */
2021 goto string; /* Share code below */
2023 } else if (flags & SVf_POK) {
2024 /* public string - go direct to string read. */
2025 goto string_readlen;
2027 #if (PATCHLEVEL <= 6)
2028 /* For 5.6 and earlier NV flag trumps IV flag, so only use integer
2029 direct if NV flag is off. */
2030 (flags & (SVf_NOK | SVf_IOK)) == SVf_IOK
2032 /* 5.7 rules are that if IV public flag is set, IV value is as
2033 good, if not better, than NV value. */
2039 * Will come here from below with iv set if double is an integer.
2043 /* Sorry. This isn't in 5.005_56 (IIRC) or earlier. */
2045 /* Need to do this out here, else 0xFFFFFFFF becomes iv of -1
2046 * (for example) and that ends up in the optimised small integer
2049 if ((flags & SVf_IVisUV) && SvUV(sv) > IV_MAX) {
2050 TRACEME(("large unsigned integer as string, value = %"UVuf, SvUV(sv)));
2051 goto string_readlen;
2055 * Optimize small integers into a single byte, otherwise store as
2056 * a real integer (converted into network order if they asked).
2059 if (iv >= -128 && iv <= 127) {
2060 unsigned char siv = (unsigned char) (iv + 128); /* [0,255] */
2063 TRACEME(("small integer stored as %d", siv));
2064 } else if (cxt->netorder) {
2066 TRACEME(("no htonl, fall back to string for integer"));
2067 goto string_readlen;
2075 /* Sorry. This isn't in 5.005_56 (IIRC) or earlier. */
2076 ((flags & SVf_IVisUV) && SvUV(sv) > 0x7FFFFFFF) ||
2078 (iv > 0x7FFFFFFF) || (iv < -0x80000000)) {
2079 /* Bigger than 32 bits. */
2080 TRACEME(("large network order integer as string, value = %"IVdf, iv));
2081 goto string_readlen;
2085 niv = (I32) htonl((I32) iv);
2086 TRACEME(("using network order"));
2091 PUTMARK(SX_INTEGER);
2092 WRITE(&iv, sizeof(iv));
2095 TRACEME(("ok (integer 0x%"UVxf", value = %"IVdf")", PTR2UV(sv), iv));
2096 } else if (flags & SVf_NOK) {
2098 #if (PATCHLEVEL <= 6)
2101 * Watch for number being an integer in disguise.
2103 if (nv == (NV) (iv = I_V(nv))) {
2104 TRACEME(("double %"NVff" is actually integer %"IVdf, nv, iv));
2105 goto integer; /* Share code above */
2110 if (SvIOK_notUV(sv)) {
2112 goto integer; /* Share code above */
2117 if (cxt->netorder) {
2118 TRACEME(("double %"NVff" stored as string", nv));
2119 goto string_readlen; /* Share code below */
2123 WRITE(&nv, sizeof(nv));
2125 TRACEME(("ok (double 0x%"UVxf", value = %"NVff")", PTR2UV(sv), nv));
2127 } else if (flags & (SVp_POK | SVp_NOK | SVp_IOK)) {
2128 I32 wlen; /* For 64-bit machines */
2134 * Will come here from above if it was readonly, POK and NOK but
2135 * neither &PL_sv_yes nor &PL_sv_no.
2139 wlen = (I32) len; /* WLEN via STORE_SCALAR expects I32 */
2141 STORE_UTF8STR(pv, wlen);
2143 STORE_SCALAR(pv, wlen);
2144 TRACEME(("ok (scalar 0x%"UVxf" '%s', length = %"IVdf")",
2145 PTR2UV(sv), SvPVX(sv), (IV)len));
2147 CROAK(("Can't determine type of %s(0x%"UVxf")",
2148 sv_reftype(sv, FALSE),
2150 return 0; /* Ok, no recursion on scalars */
2158 * Layout is SX_ARRAY <size> followed by each item, in increading index order.
2159 * Each item is stored as <object>.
2161 static int store_array(pTHX_ stcxt_t *cxt, AV *av)
2164 I32 len = av_len(av) + 1;
2168 TRACEME(("store_array (0x%"UVxf")", PTR2UV(av)));
2171 * Signal array by emitting SX_ARRAY, followed by the array length.
2176 TRACEME(("size = %d", len));
2179 * Now store each item recursively.
2182 for (i = 0; i < len; i++) {
2183 sav = av_fetch(av, i, 0);
2185 TRACEME(("(#%d) undef item", i));
2189 TRACEME(("(#%d) item", i));
2190 if ((ret = store(aTHX_ cxt, *sav))) /* Extra () for -Wall, grr... */
2194 TRACEME(("ok (array)"));
2200 #if (PATCHLEVEL <= 6)
2206 * Borrowed from perl source file pp_ctl.c, where it is used by pp_sort.
2209 sortcmp(const void *a, const void *b)
2211 #if defined(USE_ITHREADS)
2213 #endif /* USE_ITHREADS */
2214 return sv_cmp(*(SV * const *) a, *(SV * const *) b);
2217 #endif /* PATCHLEVEL <= 6 */
2222 * Store a hash table.
2224 * For a "normal" hash (not restricted, no utf8 keys):
2226 * Layout is SX_HASH <size> followed by each key/value pair, in random order.
2227 * Values are stored as <object>.
2228 * Keys are stored as <length> <data>, the <data> section being omitted
2231 * For a "fancy" hash (restricted or utf8 keys):
2233 * Layout is SX_FLAG_HASH <size> <hash flags> followed by each key/value pair,
2235 * Values are stored as <object>.
2236 * Keys are stored as <flags> <length> <data>, the <data> section being omitted
2238 * Currently the only hash flag is "restriced"
2239 * Key flags are as for hv.h
2241 static int store_hash(pTHX_ stcxt_t *cxt, HV *hv)
2245 #ifdef HAS_RESTRICTED_HASHES
2254 int flagged_hash = ((SvREADONLY(hv)
2255 #ifdef HAS_HASH_KEY_FLAGS
2259 unsigned char hash_flags = (SvREADONLY(hv) ? SHV_RESTRICTED : 0);
2262 /* needs int cast for C++ compilers, doesn't it? */
2263 TRACEME(("store_hash (0x%"UVxf") (flags %x)", PTR2UV(hv),
2266 TRACEME(("store_hash (0x%"UVxf")", PTR2UV(hv)));
2270 * Signal hash by emitting SX_HASH, followed by the table length.
2274 PUTMARK(SX_FLAG_HASH);
2275 PUTMARK(hash_flags);
2280 TRACEME(("size = %d", len));
2283 * Save possible iteration state via each() on that table.
2286 riter = HvRITER_get(hv);
2287 eiter = HvEITER_get(hv);
2291 * Now store each item recursively.
2293 * If canonical is defined to some true value then store each
2294 * key/value pair in sorted order otherwise the order is random.
2295 * Canonical order is irrelevant when a deep clone operation is performed.
2297 * Fetch the value from perl only once per store() operation, and only
2302 !(cxt->optype & ST_CLONE) && (cxt->canonical == 1 ||
2303 (cxt->canonical < 0 && (cxt->canonical =
2304 (SvTRUE(perl_get_sv("Storable::canonical", TRUE)) ? 1 : 0))))
2307 * Storing in order, sorted by key.
2308 * Run through the hash, building up an array of keys in a
2309 * mortal array, sort the array and then run through the
2315 /*av_extend (av, len);*/
2317 TRACEME(("using canonical order"));
2319 for (i = 0; i < len; i++) {
2320 #ifdef HAS_RESTRICTED_HASHES
2321 HE *he = hv_iternext_flags(hv, HV_ITERNEXT_WANTPLACEHOLDERS);
2323 HE *he = hv_iternext(hv);
2325 SV *key = hv_iterkeysv(he);
2326 av_store(av, AvFILLp(av)+1, key); /* av_push(), really */
2331 for (i = 0; i < len; i++) {
2332 #ifdef HAS_RESTRICTED_HASHES
2333 int placeholders = (int)HvPLACEHOLDERS_get(hv);
2335 unsigned char flags = 0;
2339 SV *key = av_shift(av);
2340 /* This will fail if key is a placeholder.
2341 Track how many placeholders we have, and error if we
2343 HE *he = hv_fetch_ent(hv, key, 0, 0);
2347 if (!(val = HeVAL(he))) {
2348 /* Internal error, not I/O error */
2352 #ifdef HAS_RESTRICTED_HASHES
2353 /* Should be a placeholder. */
2354 if (placeholders-- < 0) {
2355 /* This should not happen - number of
2356 retrieves should be identical to
2357 number of placeholders. */
2360 /* Value is never needed, and PL_sv_undef is
2361 more space efficient to store. */
2364 ("Flags not 0 but %d", flags));
2365 flags = SHV_K_PLACEHOLDER;
2372 * Store value first.
2375 TRACEME(("(#%d) value 0x%"UVxf, i, PTR2UV(val)));
2377 if ((ret = store(aTHX_ cxt, val))) /* Extra () for -Wall, grr... */
2382 * Keys are written after values to make sure retrieval
2383 * can be optimal in terms of memory usage, where keys are
2384 * read into a fixed unique buffer called kbuf.
2385 * See retrieve_hash() for details.
2388 /* Implementation of restricted hashes isn't nicely
2390 if ((hash_flags & SHV_RESTRICTED) && SvREADONLY(val)) {
2391 flags |= SHV_K_LOCKED;
2394 keyval = SvPV(key, keylen_tmp);
2395 keylen = keylen_tmp;
2396 #ifdef HAS_UTF8_HASHES
2397 /* If you build without optimisation on pre 5.6
2398 then nothing spots that SvUTF8(key) is always 0,
2399 so the block isn't optimised away, at which point
2400 the linker dislikes the reference to
2403 const char *keysave = keyval;
2404 bool is_utf8 = TRUE;
2406 /* Just casting the &klen to (STRLEN) won't work
2407 well if STRLEN and I32 are of different widths.
2409 keyval = (char*)bytes_from_utf8((U8*)keyval,
2413 /* If we were able to downgrade here, then than
2414 means that we have a key which only had chars
2415 0-255, but was utf8 encoded. */
2417 if (keyval != keysave) {
2418 keylen = keylen_tmp;
2419 flags |= SHV_K_WASUTF8;
2421 /* keylen_tmp can't have changed, so no need
2422 to assign back to keylen. */
2423 flags |= SHV_K_UTF8;
2430 TRACEME(("(#%d) key '%s' flags %x %u", i, keyval, flags, *keyval));
2432 /* This is a workaround for a bug in 5.8.0
2433 that causes the HEK_WASUTF8 flag to be
2434 set on an HEK without the hash being
2435 marked as having key flags. We just
2436 cross our fingers and drop the flag.
2438 assert (flags == 0 || flags == SHV_K_WASUTF8);
2439 TRACEME(("(#%d) key '%s'", i, keyval));
2443 WRITE(keyval, keylen);
2444 if (flags & SHV_K_WASUTF8)
2449 * Free up the temporary array
2458 * Storing in "random" order (in the order the keys are stored
2459 * within the hash). This is the default and will be faster!
2462 for (i = 0; i < len; i++) {
2465 unsigned char flags;
2466 #ifdef HV_ITERNEXT_WANTPLACEHOLDERS
2467 HE *he = hv_iternext_flags(hv, HV_ITERNEXT_WANTPLACEHOLDERS);
2469 HE *he = hv_iternext(hv);
2471 SV *val = (he ? hv_iterval(hv, he) : 0);
2476 return 1; /* Internal error, not I/O error */
2478 /* Implementation of restricted hashes isn't nicely
2481 = (((hash_flags & SHV_RESTRICTED)
2483 ? SHV_K_LOCKED : 0);
2485 if (val == &PL_sv_placeholder) {
2486 flags |= SHV_K_PLACEHOLDER;
2491 * Store value first.
2494 TRACEME(("(#%d) value 0x%"UVxf, i, PTR2UV(val)));
2496 if ((ret = store(aTHX_ cxt, val))) /* Extra () for -Wall, grr... */
2500 hek = HeKEY_hek(he);
2502 if (len == HEf_SVKEY) {
2503 /* This is somewhat sick, but the internal APIs are
2504 * such that XS code could put one of these in in
2506 * Maybe we should be capable of storing one if
2509 key_sv = HeKEY_sv(he);
2510 flags |= SHV_K_ISSV;
2512 /* Regular string key. */
2513 #ifdef HAS_HASH_KEY_FLAGS
2515 flags |= SHV_K_UTF8;
2516 if (HEK_WASUTF8(hek))
2517 flags |= SHV_K_WASUTF8;
2523 * Keys are written after values to make sure retrieval
2524 * can be optimal in terms of memory usage, where keys are
2525 * read into a fixed unique buffer called kbuf.
2526 * See retrieve_hash() for details.
2531 TRACEME(("(#%d) key '%s' flags %x", i, key, flags));
2533 /* This is a workaround for a bug in 5.8.0
2534 that causes the HEK_WASUTF8 flag to be
2535 set on an HEK without the hash being
2536 marked as having key flags. We just
2537 cross our fingers and drop the flag.
2539 assert (flags == 0 || flags == SHV_K_WASUTF8);
2540 TRACEME(("(#%d) key '%s'", i, key));
2542 if (flags & SHV_K_ISSV) {
2543 store(aTHX_ cxt, key_sv);
2552 TRACEME(("ok (hash 0x%"UVxf")", PTR2UV(hv)));
2555 HvRITER_set(hv, riter); /* Restore hash iterator state */
2556 HvEITER_set(hv, eiter);
2564 * Store a code reference.
2566 * Layout is SX_CODE <length> followed by a scalar containing the perl
2567 * source code of the code reference.
2569 static int store_code(pTHX_ stcxt_t *cxt, CV *cv)
2571 #if PERL_VERSION < 6
2573 * retrieve_code does not work with perl 5.005 or less
2575 return store_other(aTHX_ cxt, (SV*)cv);
2580 SV *text, *bdeparse;
2582 TRACEME(("store_code (0x%"UVxf")", PTR2UV(cv)));
2585 cxt->deparse == 0 ||
2586 (cxt->deparse < 0 && !(cxt->deparse =
2587 SvTRUE(perl_get_sv("Storable::Deparse", TRUE)) ? 1 : 0))
2589 return store_other(aTHX_ cxt, (SV*)cv);
2593 * Require B::Deparse. At least B::Deparse 0.61 is needed for
2594 * blessed code references.
2596 /* Ownership of both SVs is passed to load_module, which frees them. */
2597 load_module(PERL_LOADMOD_NOIMPORT, newSVpvn("B::Deparse",10), newSVnv(0.61));
2603 * create the B::Deparse object
2607 XPUSHs(sv_2mortal(newSVpvn("B::Deparse",10)));
2609 count = call_method("new", G_SCALAR);
2612 CROAK(("Unexpected return value from B::Deparse::new\n"));
2616 * call the coderef2text method
2620 XPUSHs(bdeparse); /* XXX is this already mortal? */
2621 XPUSHs(sv_2mortal(newRV_inc((SV*)cv)));
2623 count = call_method("coderef2text", G_SCALAR);
2626 CROAK(("Unexpected return value from B::Deparse::coderef2text\n"));
2630 reallen = strlen(SvPV_nolen(text));
2633 * Empty code references or XS functions are deparsed as
2634 * "(prototype) ;" or ";".
2637 if (len == 0 || *(SvPV_nolen(text)+reallen-1) == ';') {
2638 CROAK(("The result of B::Deparse::coderef2text was empty - maybe you're trying to serialize an XS function?\n"));
2642 * Signal code by emitting SX_CODE.
2646 cxt->tagnum++; /* necessary, as SX_CODE is a SEEN() candidate */
2647 TRACEME(("size = %d", len));
2648 TRACEME(("code = %s", SvPV_nolen(text)));
2651 * Now store the source code.
2654 STORE_SCALAR(SvPV_nolen(text), len);
2659 TRACEME(("ok (code)"));
2668 * When storing a tied object (be it a tied scalar, array or hash), we lay out
2669 * a special mark, followed by the underlying tied object. For instance, when
2670 * dealing with a tied hash, we store SX_TIED_HASH <hash object>, where
2671 * <hash object> stands for the serialization of the tied hash.
2673 static int store_tied(pTHX_ stcxt_t *cxt, SV *sv)
2678 int svt = SvTYPE(sv);
2681 TRACEME(("store_tied (0x%"UVxf")", PTR2UV(sv)));
2684 * We have a small run-time penalty here because we chose to factorise
2685 * all tieds objects into the same routine, and not have a store_tied_hash,
2686 * a store_tied_array, etc...
2688 * Don't use a switch() statement, as most compilers don't optimize that
2689 * well for 2/3 values. An if() else if() cascade is just fine. We put
2690 * tied hashes first, as they are the most likely beasts.
2693 if (svt == SVt_PVHV) {
2694 TRACEME(("tied hash"));
2695 PUTMARK(SX_TIED_HASH); /* Introduces tied hash */
2696 } else if (svt == SVt_PVAV) {
2697 TRACEME(("tied array"));
2698 PUTMARK(SX_TIED_ARRAY); /* Introduces tied array */
2700 TRACEME(("tied scalar"));
2701 PUTMARK(SX_TIED_SCALAR); /* Introduces tied scalar */
2705 if (!(mg = mg_find(sv, mtype)))
2706 CROAK(("No magic '%c' found while storing tied %s", mtype,
2707 (svt == SVt_PVHV) ? "hash" :
2708 (svt == SVt_PVAV) ? "array" : "scalar"));
2711 * The mg->mg_obj found by mg_find() above actually points to the
2712 * underlying tied Perl object implementation. For instance, if the
2713 * original SV was that of a tied array, then mg->mg_obj is an AV.
2715 * Note that we store the Perl object as-is. We don't call its FETCH
2716 * method along the way. At retrieval time, we won't call its STORE
2717 * method either, but the tieing magic will be re-installed. In itself,
2718 * that ensures that the tieing semantics are preserved since futher
2719 * accesses on the retrieved object will indeed call the magic methods...
2722 /* [#17040] mg_obj is NULL for scalar self-ties. AMS 20030416 */
2723 obj = mg->mg_obj ? mg->mg_obj : newSV(0);
2724 if ((ret = store(aTHX_ cxt, obj)))
2727 TRACEME(("ok (tied)"));
2735 * Stores a reference to an item within a tied structure:
2737 * . \$h{key}, stores both the (tied %h) object and 'key'.
2738 * . \$a[idx], stores both the (tied @a) object and 'idx'.
2740 * Layout is therefore either:
2741 * SX_TIED_KEY <object> <key>
2742 * SX_TIED_IDX <object> <index>
2744 static int store_tied_item(pTHX_ stcxt_t *cxt, SV *sv)
2749 TRACEME(("store_tied_item (0x%"UVxf")", PTR2UV(sv)));
2751 if (!(mg = mg_find(sv, 'p')))
2752 CROAK(("No magic 'p' found while storing reference to tied item"));
2755 * We discriminate between \$h{key} and \$a[idx] via mg_ptr.
2759 TRACEME(("store_tied_item: storing a ref to a tied hash item"));
2760 PUTMARK(SX_TIED_KEY);
2761 TRACEME(("store_tied_item: storing OBJ 0x%"UVxf, PTR2UV(mg->mg_obj)));
2763 if ((ret = store(aTHX_ cxt, mg->mg_obj))) /* Extra () for -Wall, grr... */
2766 TRACEME(("store_tied_item: storing PTR 0x%"UVxf, PTR2UV(mg->mg_ptr)));
2768 if ((ret = store(aTHX_ cxt, (SV *) mg->mg_ptr))) /* Idem, for -Wall */
2771 I32 idx = mg->mg_len;
2773 TRACEME(("store_tied_item: storing a ref to a tied array item "));
2774 PUTMARK(SX_TIED_IDX);
2775 TRACEME(("store_tied_item: storing OBJ 0x%"UVxf, PTR2UV(mg->mg_obj)));
2777 if ((ret = store(aTHX_ cxt, mg->mg_obj))) /* Idem, for -Wall */
2780 TRACEME(("store_tied_item: storing IDX %d", idx));
2785 TRACEME(("ok (tied item)"));
2791 * store_hook -- dispatched manually, not via sv_store[]
2793 * The blessed SV is serialized by a hook.
2797 * SX_HOOK <flags> <len> <classname> <len2> <str> [<len3> <object-IDs>]
2799 * where <flags> indicates how long <len>, <len2> and <len3> are, whether
2800 * the trailing part [] is present, the type of object (scalar, array or hash).
2801 * There is also a bit which says how the classname is stored between:
2806 * and when the <index> form is used (classname already seen), the "large
2807 * classname" bit in <flags> indicates how large the <index> is.
2809 * The serialized string returned by the hook is of length <len2> and comes
2810 * next. It is an opaque string for us.
2812 * Those <len3> object IDs which are listed last represent the extra references
2813 * not directly serialized by the hook, but which are linked to the object.
2815 * When recursion is mandated to resolve object-IDs not yet seen, we have
2816 * instead, with <header> being flags with bits set to indicate the object type
2817 * and that recursion was indeed needed:
2819 * SX_HOOK <header> <object> <header> <object> <flags>
2821 * that same header being repeated between serialized objects obtained through
2822 * recursion, until we reach flags indicating no recursion, at which point
2823 * we know we've resynchronized with a single layout, after <flags>.
2825 * When storing a blessed ref to a tied variable, the following format is
2828 * SX_HOOK <flags> <extra> ... [<len3> <object-IDs>] <magic object>
2830 * The first <flags> indication carries an object of type SHT_EXTRA, and the
2831 * real object type is held in the <extra> flag. At the very end of the
2832 * serialization stream, the underlying magic object is serialized, just like
2833 * any other tied variable.
2835 static int store_hook(
2849 int count; /* really len3 + 1 */
2850 unsigned char flags;
2853 int recursed = 0; /* counts recursion */
2854 int obj_type; /* object type, on 2 bits */
2857 int clone = cxt->optype & ST_CLONE;
2858 char mtype = '\0'; /* for blessed ref to tied structures */
2859 unsigned char eflags = '\0'; /* used when object type is SHT_EXTRA */
2861 TRACEME(("store_hook, classname \"%s\", tagged #%d", HvNAME_get(pkg), cxt->tagnum));
2864 * Determine object type on 2 bits.
2869 obj_type = SHT_SCALAR;
2872 obj_type = SHT_ARRAY;
2875 obj_type = SHT_HASH;
2879 * Produced by a blessed ref to a tied data structure, $o in the
2880 * following Perl code.
2884 * my $o = bless \%h, 'BAR';
2886 * Signal the tie-ing magic by setting the object type as SHT_EXTRA
2887 * (since we have only 2 bits in <flags> to store the type), and an
2888 * <extra> byte flag will be emitted after the FIRST <flags> in the
2889 * stream, carrying what we put in `eflags'.
2891 obj_type = SHT_EXTRA;
2892 switch (SvTYPE(sv)) {
2894 eflags = (unsigned char) SHT_THASH;
2898 eflags = (unsigned char) SHT_TARRAY;
2902 eflags = (unsigned char) SHT_TSCALAR;
2908 CROAK(("Unexpected object type (%d) in store_hook()", type));
2910 flags = SHF_NEED_RECURSE | obj_type;
2912 classname = HvNAME_get(pkg);
2913 len = strlen(classname);
2916 * To call the hook, we need to fake a call like:
2918 * $object->STORABLE_freeze($cloning);
2920 * but we don't have the $object here. For instance, if $object is
2921 * a blessed array, what we have in `sv' is the array, and we can't
2922 * call a method on those.
2924 * Therefore, we need to create a temporary reference to the object and
2925 * make the call on that reference.
2928 TRACEME(("about to call STORABLE_freeze on class %s", classname));
2930 ref = newRV_noinc(sv); /* Temporary reference */
2931 av = array_call(aTHX_ ref, hook, clone); /* @a = $object->STORABLE_freeze($c) */
2932 SvRV_set(ref, NULL);
2933 SvREFCNT_dec(ref); /* Reclaim temporary reference */
2935 count = AvFILLp(av) + 1;
2936 TRACEME(("store_hook, array holds %d items", count));
2939 * If they return an empty list, it means they wish to ignore the
2940 * hook for this class (and not just this instance -- that's for them
2941 * to handle if they so wish).
2943 * Simply disable the cached entry for the hook (it won't be recomputed
2944 * since it's present in the cache) and recurse to store_blessed().
2949 * They must not change their mind in the middle of a serialization.
2952 if (hv_fetch(cxt->hclass, classname, len, FALSE))
2953 CROAK(("Too late to ignore hooks for %s class \"%s\"",
2954 (cxt->optype & ST_CLONE) ? "cloning" : "storing", classname));
2956 pkg_hide(aTHX_ cxt->hook, pkg, "STORABLE_freeze");
2958 ASSERT(!pkg_can(aTHX_ cxt->hook, pkg, "STORABLE_freeze"), ("hook invisible"));
2959 TRACEME(("ignoring STORABLE_freeze in class \"%s\"", classname));
2961 return store_blessed(aTHX_ cxt, sv, type, pkg);
2965 * Get frozen string.
2969 pv = SvPV(ary[0], len2);
2970 /* We can't use pkg_can here because it only caches one method per
2973 GV* gv = gv_fetchmethod_autoload(pkg, "STORABLE_attach", FALSE);
2974 if (gv && isGV(gv)) {
2976 CROAK(("Freeze cannot return references if %s class is using STORABLE_attach", classname));
2982 * If they returned more than one item, we need to serialize some
2983 * extra references if not already done.
2985 * Loop over the array, starting at position #1, and for each item,
2986 * ensure it is a reference, serialize it if not already done, and
2987 * replace the entry with the tag ID of the corresponding serialized
2990 * We CHEAT by not calling av_fetch() and read directly within the
2994 for (i = 1; i < count; i++) {
2995 #ifdef USE_PTR_TABLE
3003 AV *av_hook = cxt->hook_seen;
3006 CROAK(("Item #%d returned by STORABLE_freeze "
3007 "for %s is not a reference", i, classname));
3008 xsv = SvRV(rsv); /* Follow ref to know what to look for */
3011 * Look in hseen and see if we have a tag already.
3012 * Serialize entry if not done already, and get its tag.
3015 #ifdef USE_PTR_TABLE
3016 /* Fakery needed because ptr_table_fetch returns zero for a
3017 failure, whereas the existing code assumes that it can
3018 safely store a tag zero. So for ptr_tables we store tag+1
3020 if (fake_tag = ptr_table_fetch(cxt->pseen, xsv))
3021 goto sv_seen; /* Avoid moving code too far to the right */
3023 if ((svh = hv_fetch(cxt->hseen, (char *) &xsv, sizeof(xsv), FALSE)))
3024 goto sv_seen; /* Avoid moving code too far to the right */
3027 TRACEME(("listed object %d at 0x%"UVxf" is unknown", i-1, PTR2UV(xsv)));
3030 * We need to recurse to store that object and get it to be known
3031 * so that we can resolve the list of object-IDs at retrieve time.
3033 * The first time we do this, we need to emit the proper header
3034 * indicating that we recursed, and what the type of object is (the
3035 * object we're storing via a user-hook). Indeed, during retrieval,
3036 * we'll have to create the object before recursing to retrieve the
3037 * others, in case those would point back at that object.
3040 /* [SX_HOOK] <flags> [<extra>] <object>*/
3044 if (obj_type == SHT_EXTRA)
3049 if ((ret = store(aTHX_ cxt, xsv))) /* Given by hook for us to store */
3052 #ifdef USE_PTR_TABLE
3053 fake_tag = ptr_table_fetch(cxt->pseen, xsv);
3055 CROAK(("Could not serialize item #%d from hook in %s", i, classname));
3057 svh = hv_fetch(cxt->hseen, (char *) &xsv, sizeof(xsv), FALSE);
3059 CROAK(("Could not serialize item #%d from hook in %s", i, classname));
3062 * It was the first time we serialized `xsv'.
3064 * Keep this SV alive until the end of the serialization: if we
3065 * disposed of it right now by decrementing its refcount, and it was
3066 * a temporary value, some next temporary value allocated during
3067 * another STORABLE_freeze might take its place, and we'd wrongly
3068 * assume that new SV was already serialized, based on its presence
3071 * Therefore, push it away in cxt->hook_seen.
3074 av_store(av_hook, AvFILLp(av_hook)+1, SvREFCNT_inc(xsv));
3078 * Dispose of the REF they returned. If we saved the `xsv' away
3079 * in the array of returned SVs, that will not cause the underlying
3080 * referenced SV to be reclaimed.
3083 ASSERT(SvREFCNT(xsv) > 1, ("SV will survive disposal of its REF"));
3084 SvREFCNT_dec(rsv); /* Dispose of reference */
3087 * Replace entry with its tag (not a real SV, so no refcnt increment)
3090 #ifdef USE_PTR_TABLE
3091 tag = (SV *)--fake_tag;
3096 TRACEME(("listed object %d at 0x%"UVxf" is tag #%"UVuf,
3097 i-1, PTR2UV(xsv), PTR2UV(tag)));
3101 * Allocate a class ID if not already done.
3103 * This needs to be done after the recursion above, since at retrieval
3104 * time, we'll see the inner objects first. Many thanks to
3105 * Salvador Ortiz Garcia <sog@msg.com.mx> who spot that bug and
3106 * proposed the right fix. -- RAM, 15/09/2000
3110 if (!known_class(aTHX_ cxt, classname, len, &classnum)) {
3111 TRACEME(("first time we see class %s, ID = %d", classname, classnum));
3112 classnum = -1; /* Mark: we must store classname */
3114 TRACEME(("already seen class %s, ID = %d", classname, classnum));
3118 * Compute leading flags.
3122 if (((classnum == -1) ? len : classnum) > LG_SCALAR)
3123 flags |= SHF_LARGE_CLASSLEN;
3125 flags |= SHF_IDX_CLASSNAME;
3126 if (len2 > LG_SCALAR)
3127 flags |= SHF_LARGE_STRLEN;
3129 flags |= SHF_HAS_LIST;
3130 if (count > (LG_SCALAR + 1))
3131 flags |= SHF_LARGE_LISTLEN;
3134 * We're ready to emit either serialized form:
3136 * SX_HOOK <flags> <len> <classname> <len2> <str> [<len3> <object-IDs>]
3137 * SX_HOOK <flags> <index> <len2> <str> [<len3> <object-IDs>]
3139 * If we recursed, the SX_HOOK has already been emitted.
3142 TRACEME(("SX_HOOK (recursed=%d) flags=0x%x "
3143 "class=%"IVdf" len=%"IVdf" len2=%"IVdf" len3=%d",
3144 recursed, flags, (IV)classnum, (IV)len, (IV)len2, count-1));
3146 /* SX_HOOK <flags> [<extra>] */
3150 if (obj_type == SHT_EXTRA)
3155 /* <len> <classname> or <index> */
3156 if (flags & SHF_IDX_CLASSNAME) {
3157 if (flags & SHF_LARGE_CLASSLEN)
3160 unsigned char cnum = (unsigned char) classnum;
3164 if (flags & SHF_LARGE_CLASSLEN)
3167 unsigned char clen = (unsigned char) len;
3170 WRITE(classname, len); /* Final \0 is omitted */
3173 /* <len2> <frozen-str> */
3174 if (flags & SHF_LARGE_STRLEN) {
3175 I32 wlen2 = len2; /* STRLEN might be 8 bytes */
3176 WLEN(wlen2); /* Must write an I32 for 64-bit machines */
3178 unsigned char clen = (unsigned char) len2;
3182 WRITE(pv, (SSize_t)len2); /* Final \0 is omitted */
3184 /* [<len3> <object-IDs>] */
3185 if (flags & SHF_HAS_LIST) {
3186 int len3 = count - 1;
3187 if (flags & SHF_LARGE_LISTLEN)
3190 unsigned char clen = (unsigned char) len3;
3195 * NOTA BENE, for 64-bit machines: the ary[i] below does not yield a
3196 * real pointer, rather a tag number, well under the 32-bit limit.
3199 for (i = 1; i < count; i++) {
3200 I32 tagval = htonl(LOW_32BITS(ary[i]));
3202 TRACEME(("object %d, tag #%d", i-1, ntohl(tagval)));
3207 * Free the array. We need extra care for indices after 0, since they
3208 * don't hold real SVs but integers cast.
3212 AvFILLp(av) = 0; /* Cheat, nothing after 0 interests us */
3217 * If object was tied, need to insert serialization of the magic object.
3220 if (obj_type == SHT_EXTRA) {
3223 if (!(mg = mg_find(sv, mtype))) {
3224 int svt = SvTYPE(sv);
3225 CROAK(("No magic '%c' found while storing ref to tied %s with hook",
3226 mtype, (svt == SVt_PVHV) ? "hash" :
3227 (svt == SVt_PVAV) ? "array" : "scalar"));
3230 TRACEME(("handling the magic object 0x%"UVxf" part of 0x%"UVxf,
3231 PTR2UV(mg->mg_obj), PTR2UV(sv)));
3237 if ((ret = store(aTHX_ cxt, mg->mg_obj))) /* Extra () for -Wall, grr... */
3245 * store_blessed -- dispatched manually, not via sv_store[]
3247 * Check whether there is a STORABLE_xxx hook defined in the class or in one
3248 * of its ancestors. If there is, then redispatch to store_hook();
3250 * Otherwise, the blessed SV is stored using the following layout:
3252 * SX_BLESS <flag> <len> <classname> <object>
3254 * where <flag> indicates whether <len> is stored on 0 or 4 bytes, depending
3255 * on the high-order bit in flag: if 1, then length follows on 4 bytes.
3256 * Otherwise, the low order bits give the length, thereby giving a compact
3257 * representation for class names less than 127 chars long.
3259 * Each <classname> seen is remembered and indexed, so that the next time
3260 * an object in the blessed in the same <classname> is stored, the following
3263 * SX_IX_BLESS <flag> <index> <object>
3265 * where <index> is the classname index, stored on 0 or 4 bytes depending
3266 * on the high-order bit in flag (same encoding as above for <len>).
3268 static int store_blessed(
3280 TRACEME(("store_blessed, type %d, class \"%s\"", type, HvNAME_get(pkg)));
3283 * Look for a hook for this blessed SV and redirect to store_hook()
3287 hook = pkg_can(aTHX_ cxt->hook, pkg, "STORABLE_freeze");
3289 return store_hook(aTHX_ cxt, sv, type, pkg, hook);
3292 * This is a blessed SV without any serialization hook.
3295 classname = HvNAME_get(pkg);
3296 len = strlen(classname);
3298 TRACEME(("blessed 0x%"UVxf" in %s, no hook: tagged #%d",
3299 PTR2UV(sv), classname, cxt->tagnum));
3302 * Determine whether it is the first time we see that class name (in which
3303 * case it will be stored in the SX_BLESS form), or whether we already
3304 * saw that class name before (in which case the SX_IX_BLESS form will be
3308 if (known_class(aTHX_ cxt, classname, len, &classnum)) {
3309 TRACEME(("already seen class %s, ID = %d", classname, classnum));
3310 PUTMARK(SX_IX_BLESS);
3311 if (classnum <= LG_BLESS) {
3312 unsigned char cnum = (unsigned char) classnum;
3315 unsigned char flag = (unsigned char) 0x80;
3320 TRACEME(("first time we see class %s, ID = %d", classname, classnum));
3322 if (len <= LG_BLESS) {
3323 unsigned char clen = (unsigned char) len;
3326 unsigned char flag = (unsigned char) 0x80;
3328 WLEN(len); /* Don't BER-encode, this should be rare */
3330 WRITE(classname, len); /* Final \0 is omitted */
3334 * Now emit the <object> part.
3337 return SV_STORE(type)(aTHX_ cxt, sv);
3343 * We don't know how to store the item we reached, so return an error condition.
3344 * (it's probably a GLOB, some CODE reference, etc...)
3346 * If they defined the `forgive_me' variable at the Perl level to some
3347 * true value, then don't croak, just warn, and store a placeholder string
3350 static int store_other(pTHX_ stcxt_t *cxt, SV *sv)
3355 TRACEME(("store_other"));
3358 * Fetch the value from perl only once per store() operation.
3362 cxt->forgive_me == 0 ||
3363 (cxt->forgive_me < 0 && !(cxt->forgive_me =
3364 SvTRUE(perl_get_sv("Storable::forgive_me", TRUE)) ? 1 : 0))
3366 CROAK(("Can't store %s items", sv_reftype(sv, FALSE)));
3368 warn("Can't store item %s(0x%"UVxf")",
3369 sv_reftype(sv, FALSE), PTR2UV(sv));
3372 * Store placeholder string as a scalar instead...
3375 (void) sprintf(buf, "You lost %s(0x%"UVxf")%c", sv_reftype(sv, FALSE),
3376 PTR2UV(sv), (char) 0);
3379 STORE_SCALAR(buf, len);
3380 TRACEME(("ok (dummy \"%s\", length = %"IVdf")", buf, (IV) len));
3386 *** Store driving routines
3392 * WARNING: partially duplicates Perl's sv_reftype for speed.
3394 * Returns the type of the SV, identified by an integer. That integer
3395 * may then be used to index the dynamic routine dispatch table.
3397 static int sv_type(pTHX_ SV *sv)
3399 switch (SvTYPE(sv)) {
3404 * No need to check for ROK, that can't be set here since there
3405 * is no field capable of hodling the xrv_rv reference.
3413 * Starting from SVt_PV, it is possible to have the ROK flag
3414 * set, the pointer to the other SV being either stored in
3415 * the xrv_rv (in the case of a pure SVt_RV), or as the
3416 * xpv_pv field of an SVt_PV and its heirs.
3418 * However, those SV cannot be magical or they would be an
3419 * SVt_PVMG at least.
3421 return SvROK(sv) ? svis_REF : svis_SCALAR;
3423 case SVt_PVLV: /* Workaround for perl5.004_04 "LVALUE" bug */
3424 if (SvRMAGICAL(sv) && (mg_find(sv, 'p')))
3425 return svis_TIED_ITEM;
3428 if (SvRMAGICAL(sv) && (mg_find(sv, 'q')))
3430 return SvROK(sv) ? svis_REF : svis_SCALAR;
3432 if (SvRMAGICAL(sv) && (mg_find(sv, 'P')))
3436 if (SvRMAGICAL(sv) && (mg_find(sv, 'P')))
3451 * Recursively store objects pointed to by the sv to the specified file.
3453 * Layout is <content> or SX_OBJECT <tagnum> if we reach an already stored
3454 * object (one for which storage has started -- it may not be over if we have
3455 * a self-referenced structure). This data set forms a stored <object>.
3457 static int store(pTHX_ stcxt_t *cxt, SV *sv)
3462 #ifdef USE_PTR_TABLE
3463 struct ptr_tbl *pseen = cxt->pseen;
3465 HV *hseen = cxt->hseen;
3468 TRACEME(("store (0x%"UVxf")", PTR2UV(sv)));
3471 * If object has already been stored, do not duplicate data.
3472 * Simply emit the SX_OBJECT marker followed by its tag data.
3473 * The tag is always written in network order.
3475 * NOTA BENE, for 64-bit machines: the "*svh" below does not yield a
3476 * real pointer, rather a tag number (watch the insertion code below).
3477 * That means it probably safe to assume it is well under the 32-bit limit,
3478 * and makes the truncation safe.
3479 * -- RAM, 14/09/1999
3482 #ifdef USE_PTR_TABLE
3483 svh = ptr_table_fetch(pseen, sv);
3485 svh = hv_fetch(hseen, (char *) &sv, sizeof(sv), FALSE);
3490 if (sv == &PL_sv_undef) {
3491 /* We have seen PL_sv_undef before, but fake it as
3494 Not the simplest solution to making restricted
3495 hashes work on 5.8.0, but it does mean that
3496 repeated references to the one true undef will
3497 take up less space in the output file.
3499 /* Need to jump past the next hv_store, because on the
3500 second store of undef the old hash value will be
3501 SvREFCNT_dec()ed, and as Storable cheats horribly
3502 by storing non-SVs in the hash a SEGV will ensure.
3503 Need to increase the tag number so that the
3504 receiver has no idea what games we're up to. This
3505 special casing doesn't affect hooks that store
3506 undef, as the hook routine does its own lookup into
3507 hseen. Also this means that any references back
3508 to PL_sv_undef (from the pathological case of hooks
3509 storing references to it) will find the seen hash
3510 entry for the first time, as if we didn't have this
3511 hackery here. (That hseen lookup works even on 5.8.0
3512 because it's a key of &PL_sv_undef and a value
3513 which is a tag number, not a value which is
3517 goto undef_special_case;
3520 #ifdef USE_PTR_TABLE
3521 tagval = htonl(LOW_32BITS(((char *)svh)-1));
3523 tagval = htonl(LOW_32BITS(*svh));
3526 TRACEME(("object 0x%"UVxf" seen as #%d", PTR2UV(sv), ntohl(tagval)));
3534 * Allocate a new tag and associate it with the address of the sv being
3535 * stored, before recursing...
3537 * In order to avoid creating new SvIVs to hold the tagnum we just
3538 * cast the tagnum to an SV pointer and store that in the hash. This
3539 * means that we must clean up the hash manually afterwards, but gives
3540 * us a 15% throughput increase.
3545 #ifdef USE_PTR_TABLE
3546 ptr_table_store(pseen, sv, INT2PTR(SV*, 1 + cxt->tagnum));
3548 if (!hv_store(hseen,
3549 (char *) &sv, sizeof(sv), INT2PTR(SV*, cxt->tagnum), 0))
3554 * Store `sv' and everything beneath it, using appropriate routine.
3555 * Abort immediately if we get a non-zero status back.
3558 type = sv_type(aTHX_ sv);
3561 TRACEME(("storing 0x%"UVxf" tag #%d, type %d...",
3562 PTR2UV(sv), cxt->tagnum, type));
3565 HV *pkg = SvSTASH(sv);
3566 ret = store_blessed(aTHX_ cxt, sv, type, pkg);
3568 ret = SV_STORE(type)(aTHX_ cxt, sv);
3570 TRACEME(("%s (stored 0x%"UVxf", refcnt=%d, %s)",
3571 ret ? "FAILED" : "ok", PTR2UV(sv),
3572 SvREFCNT(sv), sv_reftype(sv, FALSE)));
3580 * Write magic number and system information into the file.
3581 * Layout is <magic> <network> [<len> <byteorder> <sizeof int> <sizeof long>
3582 * <sizeof ptr>] where <len> is the length of the byteorder hexa string.
3583 * All size and lenghts are written as single characters here.
3585 * Note that no byte ordering info is emitted when <network> is true, since
3586 * integers will be emitted in network order in that case.
3588 static int magic_write(pTHX_ stcxt_t *cxt)
3591 * Starting with 0.6, the "use_network_order" byte flag is also used to
3592 * indicate the version number of the binary image, encoded in the upper
3593 * bits. The bit 0 is always used to indicate network order.
3596 * Starting with 0.7, a full byte is dedicated to the minor version of
3597 * the binary format, which is incremented only when new markers are
3598 * introduced, for instance, but when backward compatibility is preserved.
3601 /* Make these at compile time. The WRITE() macro is sufficiently complex
3602 that it saves about 200 bytes doing it this way and only using it
3604 static const unsigned char network_file_header[] = {
3606 (STORABLE_BIN_MAJOR << 1) | 1,
3607 STORABLE_BIN_WRITE_MINOR
3609 static const unsigned char file_header[] = {
3611 (STORABLE_BIN_MAJOR << 1) | 0,
3612 STORABLE_BIN_WRITE_MINOR,
3613 /* sizeof the array includes the 0 byte at the end: */
3614 (char) sizeof (byteorderstr) - 1,
3616 (unsigned char) sizeof(int),
3617 (unsigned char) sizeof(long),
3618 (unsigned char) sizeof(char *),
3619 (unsigned char) sizeof(NV)
3621 #ifdef USE_56_INTERWORK_KLUDGE
3622 static const unsigned char file_header_56[] = {
3624 (STORABLE_BIN_MAJOR << 1) | 0,
3625 STORABLE_BIN_WRITE_MINOR,
3626 /* sizeof the array includes the 0 byte at the end: */
3627 (char) sizeof (byteorderstr_56) - 1,
3629 (unsigned char) sizeof(int),
3630 (unsigned char) sizeof(long),
3631 (unsigned char) sizeof(char *),
3632 (unsigned char) sizeof(NV)
3635 const unsigned char *header;
3638 TRACEME(("magic_write on fd=%d", cxt->fio ? PerlIO_fileno(cxt->fio) : -1));
3640 if (cxt->netorder) {
3641 header = network_file_header;
3642 length = sizeof (network_file_header);
3644 #ifdef USE_56_INTERWORK_KLUDGE
3645 if (SvTRUE(perl_get_sv("Storable::interwork_56_64bit", TRUE))) {
3646 header = file_header_56;
3647 length = sizeof (file_header_56);
3651 header = file_header;
3652 length = sizeof (file_header);
3657 /* sizeof the array includes the 0 byte at the end. */
3658 header += sizeof (magicstr) - 1;
3659 length -= sizeof (magicstr) - 1;
3662 WRITE( (unsigned char*) header, length);
3664 if (!cxt->netorder) {
3665 TRACEME(("ok (magic_write byteorder = 0x%lx [%d], I%d L%d P%d D%d)",
3666 (unsigned long) BYTEORDER, (int) sizeof (byteorderstr) - 1,
3667 (int) sizeof(int), (int) sizeof(long),
3668 (int) sizeof(char *), (int) sizeof(NV)));
3676 * Common code for store operations.
3678 * When memory store is requested (f = NULL) and a non null SV* is given in
3679 * `res', it is filled with a new SV created out of the memory buffer.
3681 * It is required to provide a non-null `res' when the operation type is not
3682 * dclone() and store() is performed to memory.
3684 static int do_store(
3695 ASSERT(!(f == 0 && !(optype & ST_CLONE)) || res,
3696 ("must supply result SV pointer for real recursion to memory"));
3698 TRACEME(("do_store (optype=%d, netorder=%d)",
3699 optype, network_order));
3704 * Workaround for CROAK leak: if they enter with a "dirty" context,
3705 * free up memory for them now.
3709 clean_context(aTHX_ cxt);
3712 * Now that STORABLE_xxx hooks exist, it is possible that they try to
3713 * re-enter store() via the hooks. We need to stack contexts.
3717 cxt = allocate_context(aTHX_ cxt);
3721 ASSERT(cxt->entry == 1, ("starting new recursion"));
3722 ASSERT(!cxt->s_dirty, ("clean context"));
3725 * Ensure sv is actually a reference. From perl, we called something
3727 * pstore(aTHX_ FILE, \@array);
3728 * so we must get the scalar value behing that reference.
3732 CROAK(("Not a reference"));
3733 sv = SvRV(sv); /* So follow it to know what to store */
3736 * If we're going to store to memory, reset the buffer.
3743 * Prepare context and emit headers.
3746 init_store_context(aTHX_ cxt, f, optype, network_order);
3748 if (-1 == magic_write(aTHX_ cxt)) /* Emit magic and ILP info */
3749 return 0; /* Error */
3752 * Recursively store object...
3755 ASSERT(is_storing(aTHX), ("within store operation"));
3757 status = store(aTHX_ cxt, sv); /* Just do it! */
3760 * If they asked for a memory store and they provided an SV pointer,
3761 * make an SV string out of the buffer and fill their pointer.
3763 * When asking for ST_REAL, it's MANDATORY for the caller to provide
3764 * an SV, since context cleanup might free the buffer if we did recurse.
3765 * (unless caller is dclone(), which is aware of that).
3768 if (!cxt->fio && res)
3769 *res = mbuf2sv(aTHX);
3774 * The "root" context is never freed, since it is meant to be always
3775 * handy for the common case where no recursion occurs at all (i.e.
3776 * we enter store() outside of any Storable code and leave it, period).
3777 * We know it's the "root" context because there's nothing stacked
3782 * When deep cloning, we don't free the context: doing so would force
3783 * us to copy the data in the memory buffer. Sicne we know we're
3784 * about to enter do_retrieve...
3787 clean_store_context(aTHX_ cxt);
3788 if (cxt->prev && !(cxt->optype & ST_CLONE))
3789 free_context(aTHX_ cxt);
3791 TRACEME(("do_store returns %d", status));
3799 * Store the transitive data closure of given object to disk.
3800 * Returns 0 on error, a true value otherwise.
3802 int pstore(pTHX_ PerlIO *f, SV *sv)
3804 TRACEME(("pstore"));
3805 return do_store(aTHX_ f, sv, 0, FALSE, (SV**) 0);
3812 * Same as pstore(), but network order is used for integers and doubles are
3813 * emitted as strings.
3815 int net_pstore(pTHX_ PerlIO *f, SV *sv)
3817 TRACEME(("net_pstore"));
3818 return do_store(aTHX_ f, sv, 0, TRUE, (SV**) 0);
3828 * Build a new SV out of the content of the internal memory buffer.
3830 static SV *mbuf2sv(pTHX)
3834 return newSVpv(mbase, MBUF_SIZE());
3840 * Store the transitive data closure of given object to memory.
3841 * Returns undef on error, a scalar value containing the data otherwise.
3843 SV *mstore(pTHX_ SV *sv)
3847 TRACEME(("mstore"));
3849 if (!do_store(aTHX_ (PerlIO*) 0, sv, 0, FALSE, &out))
3850 return &PL_sv_undef;
3858 * Same as mstore(), but network order is used for integers and doubles are
3859 * emitted as strings.
3861 SV *net_mstore(pTHX_ SV *sv)
3865 TRACEME(("net_mstore"));
3867 if (!do_store(aTHX_ (PerlIO*) 0, sv, 0, TRUE, &out))
3868 return &PL_sv_undef;
3874 *** Specific retrieve callbacks.
3880 * Return an error via croak, since it is not possible that we get here
3881 * under normal conditions, when facing a file produced via pstore().
3883 static SV *retrieve_other(pTHX_ stcxt_t *cxt, char *cname)
3886 cxt->ver_major != STORABLE_BIN_MAJOR &&
3887 cxt->ver_minor != STORABLE_BIN_MINOR
3889 CROAK(("Corrupted storable %s (binary v%d.%d), current is v%d.%d",
3890 cxt->fio ? "file" : "string",
3891 cxt->ver_major, cxt->ver_minor,
3892 STORABLE_BIN_MAJOR, STORABLE_BIN_MINOR));
3894 CROAK(("Corrupted storable %s (binary v%d.%d)",
3895 cxt->fio ? "file" : "string",
3896 cxt->ver_major, cxt->ver_minor));
3899 return (SV *) 0; /* Just in case */
3903 * retrieve_idx_blessed
3905 * Layout is SX_IX_BLESS <index> <object> with SX_IX_BLESS already read.
3906 * <index> can be coded on either 1 or 5 bytes.
3908 static SV *retrieve_idx_blessed(pTHX_ stcxt_t *cxt, char *cname)
3915 TRACEME(("retrieve_idx_blessed (#%d)", cxt->tagnum));
3916 ASSERT(!cname, ("no bless-into class given here, got %s", cname));
3918 GETMARK(idx); /* Index coded on a single char? */
3923 * Fetch classname in `aclass'
3926 sva = av_fetch(cxt->aclass, idx, FALSE);
3928 CROAK(("Class name #%"IVdf" should have been seen already", (IV) idx));
3930 classname = SvPVX(*sva); /* We know it's a PV, by construction */
3932 TRACEME(("class ID %d => %s", idx, classname));
3935 * Retrieve object and bless it.
3938 sv = retrieve(aTHX_ cxt, classname); /* First SV which is SEEN will be blessed */
3946 * Layout is SX_BLESS <len> <classname> <object> with SX_BLESS already read.
3947 * <len> can be coded on either 1 or 5 bytes.
3949 static SV *retrieve_blessed(pTHX_ stcxt_t *cxt, char *cname)
3953 char buf[LG_BLESS + 1]; /* Avoid malloc() if possible */
3954 char *classname = buf;
3956 TRACEME(("retrieve_blessed (#%d)", cxt->tagnum));
3957 ASSERT(!cname, ("no bless-into class given here, got %s", cname));
3960 * Decode class name length and read that name.
3962 * Short classnames have two advantages: their length is stored on one
3963 * single byte, and the string can be read on the stack.
3966 GETMARK(len); /* Length coded on a single char? */
3969 TRACEME(("** allocating %d bytes for class name", len+1));
3970 New(10003, classname, len+1, char);
3972 READ(classname, len);
3973 classname[len] = '\0'; /* Mark string end */
3976 * It's a new classname, otherwise it would have been an SX_IX_BLESS.
3979 TRACEME(("new class name \"%s\" will bear ID = %d", classname, cxt->classnum));
3981 if (!av_store(cxt->aclass, cxt->classnum++, newSVpvn(classname, len)))
3985 * Retrieve object and bless it.
3988 sv = retrieve(aTHX_ cxt, classname); /* First SV which is SEEN will be blessed */
3989 if (classname != buf)
3990 Safefree(classname);
3998 * Layout: SX_HOOK <flags> <len> <classname> <len2> <str> [<len3> <object-IDs>]
3999 * with leading mark already read, as usual.
4001 * When recursion was involved during serialization of the object, there
4002 * is an unknown amount of serialized objects after the SX_HOOK mark. Until
4003 * we reach a <flags> marker with the recursion bit cleared.
4005 * If the first <flags> byte contains a type of SHT_EXTRA, then the real type
4006 * is held in the <extra> byte, and if the object is tied, the serialized
4007 * magic object comes at the very end:
4009 * SX_HOOK <flags> <extra> ... [<len3> <object-IDs>] <magic object>
4011 * This means the STORABLE_thaw hook will NOT get a tied variable during its
4012 * processing (since we won't have seen the magic object by the time the hook
4013 * is called). See comments below for why it was done that way.
4015 static SV *retrieve_hook(pTHX_ stcxt_t *cxt, char *cname)
4018 char buf[LG_BLESS + 1]; /* Avoid malloc() if possible */
4019 char *classname = buf;
4030 int clone = cxt->optype & ST_CLONE;
4032 unsigned int extra_type = 0;
4034 TRACEME(("retrieve_hook (#%d)", cxt->tagnum));
4035 ASSERT(!cname, ("no bless-into class given here, got %s", cname));
4038 * Read flags, which tell us about the type, and whether we need to recurse.
4044 * Create the (empty) object, and mark it as seen.
4046 * This must be done now, because tags are incremented, and during
4047 * serialization, the object tag was affected before recursion could
4051 obj_type = flags & SHF_TYPE_MASK;
4057 sv = (SV *) newAV();
4060 sv = (SV *) newHV();
4064 * Read <extra> flag to know the type of the object.
4065 * Record associated magic type for later.
4067 GETMARK(extra_type);
4068 switch (extra_type) {
4074 sv = (SV *) newAV();
4078 sv = (SV *) newHV();
4082 return retrieve_other(aTHX_ cxt, 0); /* Let it croak */
4086 return retrieve_other(aTHX_ cxt, 0); /* Let it croak */
4088 SEEN(sv, 0, 0); /* Don't bless yet */
4091 * Whilst flags tell us to recurse, do so.
4093 * We don't need to remember the addresses returned by retrieval, because
4094 * all the references will be obtained through indirection via the object
4095 * tags in the object-ID list.
4097 * We need to decrement the reference count for these objects
4098 * because, if the user doesn't save a reference to them in the hook,
4099 * they must be freed when this context is cleaned.
4102 while (flags & SHF_NEED_RECURSE) {
4103 TRACEME(("retrieve_hook recursing..."));
4104 rv = retrieve(aTHX_ cxt, 0);
4108 TRACEME(("retrieve_hook back with rv=0x%"UVxf,
4113 if (flags & SHF_IDX_CLASSNAME) {
4118 * Fetch index from `aclass'
4121 if (flags & SHF_LARGE_CLASSLEN)
4126 sva = av_fetch(cxt->aclass, idx, FALSE);
4128 CROAK(("Class name #%"IVdf" should have been seen already",
4131 classname = SvPVX(*sva); /* We know it's a PV, by construction */
4132 TRACEME(("class ID %d => %s", idx, classname));
4136 * Decode class name length and read that name.
4138 * NOTA BENE: even if the length is stored on one byte, we don't read
4139 * on the stack. Just like retrieve_blessed(), we limit the name to
4140 * LG_BLESS bytes. This is an arbitrary decision.
4143 if (flags & SHF_LARGE_CLASSLEN)
4148 if (len > LG_BLESS) {
4149 TRACEME(("** allocating %d bytes for class name", len+1));
4150 New(10003, classname, len+1, char);
4153 READ(classname, len);
4154 classname[len] = '\0'; /* Mark string end */
4157 * Record new classname.
4160 if (!av_store(cxt->aclass, cxt->classnum++, newSVpvn(classname, len)))
4164 TRACEME(("class name: %s", classname));
4167 * Decode user-frozen string length and read it in an SV.
4169 * For efficiency reasons, we read data directly into the SV buffer.
4170 * To understand that code, read retrieve_scalar()
4173 if (flags & SHF_LARGE_STRLEN)
4178 frozen = NEWSV(10002, len2);
4180 SAFEREAD(SvPVX(frozen), len2, frozen);
4181 SvCUR_set(frozen, len2);
4182 *SvEND(frozen) = '\0';
4184 (void) SvPOK_only(frozen); /* Validates string pointer */
4185 if (cxt->s_tainted) /* Is input source tainted? */
4188 TRACEME(("frozen string: %d bytes", len2));
4191 * Decode object-ID list length, if present.
4194 if (flags & SHF_HAS_LIST) {
4195 if (flags & SHF_LARGE_LISTLEN)
4201 av_extend(av, len3 + 1); /* Leave room for [0] */
4202 AvFILLp(av) = len3; /* About to be filled anyway */
4206 TRACEME(("has %d object IDs to link", len3));
4209 * Read object-ID list into array.
4210 * Because we pre-extended it, we can cheat and fill it manually.
4212 * We read object tags and we can convert them into SV* on the fly
4213 * because we know all the references listed in there (as tags)
4214 * have been already serialized, hence we have a valid correspondance
4215 * between each of those tags and the recreated SV.
4219 SV **ary = AvARRAY(av);
4221 for (i = 1; i <= len3; i++) { /* We leave [0] alone */
4228 svh = av_fetch(cxt->aseen, tag, FALSE);
4230 if (tag == cxt->where_is_undef) {
4231 /* av_fetch uses PL_sv_undef internally, hence this
4232 somewhat gruesome hack. */
4236 CROAK(("Object #%"IVdf" should have been retrieved already",
4241 ary[i] = SvREFCNT_inc(xsv);
4246 * Bless the object and look up the STORABLE_thaw hook.
4249 BLESS(sv, classname);
4251 /* Handle attach case; again can't use pkg_can because it only
4252 * caches one method */
4253 attach = gv_fetchmethod_autoload(SvSTASH(sv), "STORABLE_attach", FALSE);
4254 if (attach && isGV(attach)) {
4256 SV* attach_hook = newRV((SV*) GvCV(attach));
4259 CROAK(("STORABLE_attach called with unexpected references"));
4263 AvARRAY(av)[0] = SvREFCNT_inc(frozen);
4264 rv = newSVpv(classname, 0);
4265 attached = scalar_call(aTHX_ rv, attach_hook, clone, av, G_SCALAR);
4268 sv_derived_from(attached, classname))
4269 return SvRV(attached);
4270 CROAK(("STORABLE_attach did not return a %s object", classname));
4273 hook = pkg_can(aTHX_ cxt->hook, SvSTASH(sv), "STORABLE_thaw");
4276 * Hook not found. Maybe they did not require the module where this
4277 * hook is defined yet?
4279 * If the require below succeeds, we'll be able to find the hook.
4280 * Still, it only works reliably when each class is defined in a
4284 SV *psv = newSVpvn("require ", 8);
4285 sv_catpv(psv, classname);
4287 TRACEME(("No STORABLE_thaw defined for objects of class %s", classname));
4288 TRACEME(("Going to require module '%s' with '%s'", classname, SvPVX(psv)));
4290 perl_eval_sv(psv, G_DISCARD);
4294 * We cache results of pkg_can, so we need to uncache before attempting
4298 pkg_uncache(aTHX_ cxt->hook, SvSTASH(sv), "STORABLE_thaw");
4299 hook = pkg_can(aTHX_ cxt->hook, SvSTASH(sv), "STORABLE_thaw");
4302 CROAK(("No STORABLE_thaw defined for objects of class %s "
4303 "(even after a \"require %s;\")", classname, classname));
4307 * If we don't have an `av' yet, prepare one.
4308 * Then insert the frozen string as item [0].
4316 AvARRAY(av)[0] = SvREFCNT_inc(frozen);
4321 * $object->STORABLE_thaw($cloning, $frozen, @refs);
4323 * where $object is our blessed (empty) object, $cloning is a boolean
4324 * telling whether we're running a deep clone, $frozen is the frozen
4325 * string the user gave us in his serializing hook, and @refs, which may
4326 * be empty, is the list of extra references he returned along for us
4329 * In effect, the hook is an alternate creation routine for the class,
4330 * the object itself being already created by the runtime.
4333 TRACEME(("calling STORABLE_thaw on %s at 0x%"UVxf" (%"IVdf" args)",
4334 classname, PTR2UV(sv), (IV) AvFILLp(av) + 1));
4337 (void) scalar_call(aTHX_ rv, hook, clone, av, G_SCALAR|G_DISCARD);
4344 SvREFCNT_dec(frozen);
4347 if (!(flags & SHF_IDX_CLASSNAME) && classname != buf)
4348 Safefree(classname);
4351 * If we had an <extra> type, then the object was not as simple, and
4352 * we need to restore extra magic now.
4358 TRACEME(("retrieving magic object for 0x%"UVxf"...", PTR2UV(sv)));
4360 rv = retrieve(aTHX_ cxt, 0); /* Retrieve <magic object> */
4362 TRACEME(("restoring the magic object 0x%"UVxf" part of 0x%"UVxf,
4363 PTR2UV(rv), PTR2UV(sv)));
4365 switch (extra_type) {
4367 sv_upgrade(sv, SVt_PVMG);
4370 sv_upgrade(sv, SVt_PVAV);
4371 AvREAL_off((AV *)sv);
4374 sv_upgrade(sv, SVt_PVHV);
4377 CROAK(("Forgot to deal with extra type %d", extra_type));
4382 * Adding the magic only now, well after the STORABLE_thaw hook was called
4383 * means the hook cannot know it deals with an object whose variable is
4384 * tied. But this is happening when retrieving $o in the following case:
4388 * my $o = bless \%h, 'BAR';
4390 * The 'BAR' class is NOT the one where %h is tied into. Therefore, as
4391 * far as the 'BAR' class is concerned, the fact that %h is not a REAL
4392 * hash but a tied one should not matter at all, and remain transparent.
4393 * This means the magic must be restored by Storable AFTER the hook is
4396 * That looks very reasonable to me, but then I've come up with this
4397 * after a bug report from David Nesting, who was trying to store such
4398 * an object and caused Storable to fail. And unfortunately, it was
4399 * also the easiest way to retrofit support for blessed ref to tied objects
4400 * into the existing design. -- RAM, 17/02/2001
4403 sv_magic(sv, rv, mtype, Nullch, 0);
4404 SvREFCNT_dec(rv); /* Undo refcnt inc from sv_magic() */
4412 * Retrieve reference to some other scalar.
4413 * Layout is SX_REF <object>, with SX_REF already read.
4415 static SV *retrieve_ref(pTHX_ stcxt_t *cxt, char *cname)
4420 TRACEME(("retrieve_ref (#%d)", cxt->tagnum));
4423 * We need to create the SV that holds the reference to the yet-to-retrieve
4424 * object now, so that we may record the address in the seen table.
4425 * Otherwise, if the object to retrieve references us, we won't be able
4426 * to resolve the SX_OBJECT we'll see at that point! Hence we cannot
4427 * do the retrieve first and use rv = newRV(sv) since it will be too late
4428 * for SEEN() recording.
4431 rv = NEWSV(10002, 0);
4432 SEEN(rv, cname, 0); /* Will return if rv is null */
4433 sv = retrieve(aTHX_ cxt, 0); /* Retrieve <object> */
4435 return (SV *) 0; /* Failed */
4438 * WARNING: breaks RV encapsulation.
4440 * Now for the tricky part. We have to upgrade our existing SV, so that
4441 * it is now an RV on sv... Again, we cheat by duplicating the code
4442 * held in newSVrv(), since we already got our SV from retrieve().
4446 * SvRV(rv) = SvREFCNT_inc(sv);
4448 * here because the reference count we got from retrieve() above is
4449 * already correct: if the object was retrieved from the file, then
4450 * its reference count is one. Otherwise, if it was retrieved via
4451 * an SX_OBJECT indication, a ref count increment was done.
4455 /* No need to do anything, as rv will already be PVMG. */
4456 assert (SvTYPE(rv) >= SVt_RV);
4458 sv_upgrade(rv, SVt_RV);
4461 SvRV_set(rv, sv); /* $rv = \$sv */
4464 TRACEME(("ok (retrieve_ref at 0x%"UVxf")", PTR2UV(rv)));
4472 * Retrieve weak reference to some other scalar.
4473 * Layout is SX_WEAKREF <object>, with SX_WEAKREF already read.
4475 static SV *retrieve_weakref(pTHX_ stcxt_t *cxt, char *cname)
4479 TRACEME(("retrieve_weakref (#%d)", cxt->tagnum));
4481 sv = retrieve_ref(aTHX_ cxt, cname);
4493 * retrieve_overloaded
4495 * Retrieve reference to some other scalar with overloading.
4496 * Layout is SX_OVERLOAD <object>, with SX_OVERLOAD already read.
4498 static SV *retrieve_overloaded(pTHX_ stcxt_t *cxt, char *cname)
4504 TRACEME(("retrieve_overloaded (#%d)", cxt->tagnum));
4507 * Same code as retrieve_ref(), duplicated to avoid extra call.
4510 rv = NEWSV(10002, 0);
4511 SEEN(rv, cname, 0); /* Will return if rv is null */
4512 sv = retrieve(aTHX_ cxt, 0); /* Retrieve <object> */
4514 return (SV *) 0; /* Failed */
4517 * WARNING: breaks RV encapsulation.
4520 sv_upgrade(rv, SVt_RV);
4521 SvRV_set(rv, sv); /* $rv = \$sv */
4525 * Restore overloading magic.
4528 stash = SvTYPE(sv) ? (HV *) SvSTASH (sv) : 0;
4530 CROAK(("Cannot restore overloading on %s(0x%"UVxf
4531 ") (package <unknown>)",
4532 sv_reftype(sv, FALSE),
4535 if (!Gv_AMG(stash)) {
4536 SV *psv = newSVpvn("require ", 8);
4537 const char *package = HvNAME_get(stash);
4538 sv_catpv(psv, package);
4540 TRACEME(("No overloading defined for package %s", package));
4541 TRACEME(("Going to require module '%s' with '%s'", package, SvPVX(psv)));
4543 perl_eval_sv(psv, G_DISCARD);
4545 if (!Gv_AMG(stash)) {
4546 CROAK(("Cannot restore overloading on %s(0x%"UVxf
4547 ") (package %s) (even after a \"require %s;\")",
4548 sv_reftype(sv, FALSE),
4556 TRACEME(("ok (retrieve_overloaded at 0x%"UVxf")", PTR2UV(rv)));
4562 * retrieve_weakoverloaded
4564 * Retrieve weak overloaded reference to some other scalar.
4565 * Layout is SX_WEAKOVERLOADED <object>, with SX_WEAKOVERLOADED already read.
4567 static SV *retrieve_weakoverloaded(pTHX_ stcxt_t *cxt, char *cname)
4571 TRACEME(("retrieve_weakoverloaded (#%d)", cxt->tagnum));
4573 sv = retrieve_overloaded(aTHX_ cxt, cname);
4585 * retrieve_tied_array
4587 * Retrieve tied array
4588 * Layout is SX_TIED_ARRAY <object>, with SX_TIED_ARRAY already read.
4590 static SV *retrieve_tied_array(pTHX_ stcxt_t *cxt, char *cname)
4595 TRACEME(("retrieve_tied_array (#%d)", cxt->tagnum));
4597 tv = NEWSV(10002, 0);
4598 SEEN(tv, cname, 0); /* Will return if tv is null */
4599 sv = retrieve(aTHX_ cxt, 0); /* Retrieve <object> */
4601 return (SV *) 0; /* Failed */
4603 sv_upgrade(tv, SVt_PVAV);
4604 AvREAL_off((AV *)tv);
4605 sv_magic(tv, sv, 'P', Nullch, 0);
4606 SvREFCNT_dec(sv); /* Undo refcnt inc from sv_magic() */
4608 TRACEME(("ok (retrieve_tied_array at 0x%"UVxf")", PTR2UV(tv)));
4614 * retrieve_tied_hash
4616 * Retrieve tied hash
4617 * Layout is SX_TIED_HASH <object>, with SX_TIED_HASH already read.
4619 static SV *retrieve_tied_hash(pTHX_ stcxt_t *cxt, char *cname)
4624 TRACEME(("retrieve_tied_hash (#%d)", cxt->tagnum));
4626 tv = NEWSV(10002, 0);
4627 SEEN(tv, cname, 0); /* Will return if tv is null */
4628 sv = retrieve(aTHX_ cxt, 0); /* Retrieve <object> */
4630 return (SV *) 0; /* Failed */
4632 sv_upgrade(tv, SVt_PVHV);
4633 sv_magic(tv, sv, 'P', Nullch, 0);
4634 SvREFCNT_dec(sv); /* Undo refcnt inc from sv_magic() */
4636 TRACEME(("ok (retrieve_tied_hash at 0x%"UVxf")", PTR2UV(tv)));
4642 * retrieve_tied_scalar
4644 * Retrieve tied scalar
4645 * Layout is SX_TIED_SCALAR <object>, with SX_TIED_SCALAR already read.
4647 static SV *retrieve_tied_scalar(pTHX_ stcxt_t *cxt, char *cname)
4650 SV *sv, *obj = NULL;
4652 TRACEME(("retrieve_tied_scalar (#%d)", cxt->tagnum));
4654 tv = NEWSV(10002, 0);
4655 SEEN(tv, cname, 0); /* Will return if rv is null */
4656 sv = retrieve(aTHX_ cxt, 0); /* Retrieve <object> */
4658 return (SV *) 0; /* Failed */
4660 else if (SvTYPE(sv) != SVt_NULL) {
4664 sv_upgrade(tv, SVt_PVMG);
4665 sv_magic(tv, obj, 'q', Nullch, 0);
4668 /* Undo refcnt inc from sv_magic() */
4672 TRACEME(("ok (retrieve_tied_scalar at 0x%"UVxf")", PTR2UV(tv)));
4680 * Retrieve reference to value in a tied hash.
4681 * Layout is SX_TIED_KEY <object> <key>, with SX_TIED_KEY already read.
4683 static SV *retrieve_tied_key(pTHX_ stcxt_t *cxt, char *cname)
4689 TRACEME(("retrieve_tied_key (#%d)", cxt->tagnum));
4691 tv = NEWSV(10002, 0);
4692 SEEN(tv, cname, 0); /* Will return if tv is null */
4693 sv = retrieve(aTHX_ cxt, 0); /* Retrieve <object> */
4695 return (SV *) 0; /* Failed */
4697 key = retrieve(aTHX_ cxt, 0); /* Retrieve <key> */
4699 return (SV *) 0; /* Failed */
4701 sv_upgrade(tv, SVt_PVMG);
4702 sv_magic(tv, sv, 'p', (char *)key, HEf_SVKEY);
4703 SvREFCNT_dec(key); /* Undo refcnt inc from sv_magic() */
4704 SvREFCNT_dec(sv); /* Undo refcnt inc from sv_magic() */
4712 * Retrieve reference to value in a tied array.
4713 * Layout is SX_TIED_IDX <object> <idx>, with SX_TIED_IDX already read.
4715 static SV *retrieve_tied_idx(pTHX_ stcxt_t *cxt, char *cname)
4721 TRACEME(("retrieve_tied_idx (#%d)", cxt->tagnum));
4723 tv = NEWSV(10002, 0);
4724 SEEN(tv, cname, 0); /* Will return if tv is null */
4725 sv = retrieve(aTHX_ cxt, 0); /* Retrieve <object> */
4727 return (SV *) 0; /* Failed */
4729 RLEN(idx); /* Retrieve <idx> */
4731 sv_upgrade(tv, SVt_PVMG);
4732 sv_magic(tv, sv, 'p', Nullch, idx);
4733 SvREFCNT_dec(sv); /* Undo refcnt inc from sv_magic() */
4742 * Retrieve defined long (string) scalar.
4744 * Layout is SX_LSCALAR <length> <data>, with SX_LSCALAR already read.
4745 * The scalar is "long" in that <length> is larger than LG_SCALAR so it
4746 * was not stored on a single byte.
4748 static SV *retrieve_lscalar(pTHX_ stcxt_t *cxt, char *cname)
4754 TRACEME(("retrieve_lscalar (#%d), len = %"IVdf, cxt->tagnum, (IV) len));
4757 * Allocate an empty scalar of the suitable length.
4760 sv = NEWSV(10002, len);
4761 SEEN(sv, cname, 0); /* Associate this new scalar with tag "tagnum" */
4764 * WARNING: duplicates parts of sv_setpv and breaks SV data encapsulation.
4766 * Now, for efficiency reasons, read data directly inside the SV buffer,
4767 * and perform the SV final settings directly by duplicating the final
4768 * work done by sv_setpv. Since we're going to allocate lots of scalars
4769 * this way, it's worth the hassle and risk.
4772 SAFEREAD(SvPVX(sv), len, sv);
4773 SvCUR_set(sv, len); /* Record C string length */
4774 *SvEND(sv) = '\0'; /* Ensure it's null terminated anyway */
4775 (void) SvPOK_only(sv); /* Validate string pointer */
4776 if (cxt->s_tainted) /* Is input source tainted? */
4777 SvTAINT(sv); /* External data cannot be trusted */
4779 TRACEME(("large scalar len %"IVdf" '%s'", (IV) len, SvPVX(sv)));
4780 TRACEME(("ok (retrieve_lscalar at 0x%"UVxf")", PTR2UV(sv)));
4788 * Retrieve defined short (string) scalar.
4790 * Layout is SX_SCALAR <length> <data>, with SX_SCALAR already read.
4791 * The scalar is "short" so <length> is single byte. If it is 0, there
4792 * is no <data> section.
4794 static SV *retrieve_scalar(pTHX_ stcxt_t *cxt, char *cname)
4800 TRACEME(("retrieve_scalar (#%d), len = %d", cxt->tagnum, len));
4803 * Allocate an empty scalar of the suitable length.
4806 sv = NEWSV(10002, len);
4807 SEEN(sv, cname, 0); /* Associate this new scalar with tag "tagnum" */
4810 * WARNING: duplicates parts of sv_setpv and breaks SV data encapsulation.
4815 * newSV did not upgrade to SVt_PV so the scalar is undefined.
4816 * To make it defined with an empty length, upgrade it now...
4817 * Don't upgrade to a PV if the original type contains more
4818 * information than a scalar.
4820 if (SvTYPE(sv) <= SVt_PV) {
4821 sv_upgrade(sv, SVt_PV);
4824 *SvEND(sv) = '\0'; /* Ensure it's null terminated anyway */
4825 TRACEME(("ok (retrieve_scalar empty at 0x%"UVxf")", PTR2UV(sv)));
4828 * Now, for efficiency reasons, read data directly inside the SV buffer,
4829 * and perform the SV final settings directly by duplicating the final
4830 * work done by sv_setpv. Since we're going to allocate lots of scalars
4831 * this way, it's worth the hassle and risk.
4833 SAFEREAD(SvPVX(sv), len, sv);
4834 SvCUR_set(sv, len); /* Record C string length */
4835 *SvEND(sv) = '\0'; /* Ensure it's null terminated anyway */
4836 TRACEME(("small scalar len %d '%s'", len, SvPVX(sv)));
4839 (void) SvPOK_only(sv); /* Validate string pointer */
4840 if (cxt->s_tainted) /* Is input source tainted? */
4841 SvTAINT(sv); /* External data cannot be trusted */
4843 TRACEME(("ok (retrieve_scalar at 0x%"UVxf")", PTR2UV(sv)));
4850 * Like retrieve_scalar(), but tag result as utf8.
4851 * If we're retrieving UTF8 data in a non-UTF8 perl, croaks.
4853 static SV *retrieve_utf8str(pTHX_ stcxt_t *cxt, char *cname)
4857 TRACEME(("retrieve_utf8str"));
4859 sv = retrieve_scalar(aTHX_ cxt, cname);
4861 #ifdef HAS_UTF8_SCALARS
4864 if (cxt->use_bytes < 0)
4866 = (SvTRUE(perl_get_sv("Storable::drop_utf8", TRUE))
4868 if (cxt->use_bytes == 0)
4879 * Like retrieve_lscalar(), but tag result as utf8.
4880 * If we're retrieving UTF8 data in a non-UTF8 perl, croaks.
4882 static SV *retrieve_lutf8str(pTHX_ stcxt_t *cxt, char *cname)
4886 TRACEME(("retrieve_lutf8str"));
4888 sv = retrieve_lscalar(aTHX_ cxt, cname);
4890 #ifdef HAS_UTF8_SCALARS
4893 if (cxt->use_bytes < 0)
4895 = (SvTRUE(perl_get_sv("Storable::drop_utf8", TRUE))
4897 if (cxt->use_bytes == 0)
4907 * Retrieve defined integer.
4908 * Layout is SX_INTEGER <data>, whith SX_INTEGER already read.
4910 static SV *retrieve_integer(pTHX_ stcxt_t *cxt, char *cname)
4915 TRACEME(("retrieve_integer (#%d)", cxt->tagnum));
4917 READ(&iv, sizeof(iv));
4919 SEEN(sv, cname, 0); /* Associate this new scalar with tag "tagnum" */
4921 TRACEME(("integer %"IVdf, iv));
4922 TRACEME(("ok (retrieve_integer at 0x%"UVxf")", PTR2UV(sv)));
4930 * Retrieve defined integer in network order.
4931 * Layout is SX_NETINT <data>, whith SX_NETINT already read.
4933 static SV *retrieve_netint(pTHX_ stcxt_t *cxt, char *cname)
4938 TRACEME(("retrieve_netint (#%d)", cxt->tagnum));
4942 sv = newSViv((int) ntohl(iv));
4943 TRACEME(("network integer %d", (int) ntohl(iv)));
4946 TRACEME(("network integer (as-is) %d", iv));
4948 SEEN(sv, cname, 0); /* Associate this new scalar with tag "tagnum" */
4950 TRACEME(("ok (retrieve_netint at 0x%"UVxf")", PTR2UV(sv)));
4958 * Retrieve defined double.
4959 * Layout is SX_DOUBLE <data>, whith SX_DOUBLE already read.
4961 static SV *retrieve_double(pTHX_ stcxt_t *cxt, char *cname)
4966 TRACEME(("retrieve_double (#%d)", cxt->tagnum));
4968 READ(&nv, sizeof(nv));
4970 SEEN(sv, cname, 0); /* Associate this new scalar with tag "tagnum" */
4972 TRACEME(("double %"NVff, nv));
4973 TRACEME(("ok (retrieve_double at 0x%"UVxf")", PTR2UV(sv)));
4981 * Retrieve defined byte (small integer within the [-128, +127] range).
4982 * Layout is SX_BYTE <data>, whith SX_BYTE already read.
4984 static SV *retrieve_byte(pTHX_ stcxt_t *cxt, char *cname)
4988 signed char tmp; /* Workaround for AIX cc bug --H.Merijn Brand */
4990 TRACEME(("retrieve_byte (#%d)", cxt->tagnum));
4993 TRACEME(("small integer read as %d", (unsigned char) siv));
4994 tmp = (unsigned char) siv - 128;
4996 SEEN(sv, cname, 0); /* Associate this new scalar with tag "tagnum" */
4998 TRACEME(("byte %d", tmp));
4999 TRACEME(("ok (retrieve_byte at 0x%"UVxf")", PTR2UV(sv)));
5007 * Return the undefined value.
5009 static SV *retrieve_undef(pTHX_ stcxt_t *cxt, char *cname)
5013 TRACEME(("retrieve_undef"));
5024 * Return the immortal undefined value.
5026 static SV *retrieve_sv_undef(pTHX_ stcxt_t *cxt, char *cname)
5028 SV *sv = &PL_sv_undef;
5030 TRACEME(("retrieve_sv_undef"));
5032 /* Special case PL_sv_undef, as av_fetch uses it internally to mark
5033 deleted elements, and will return NULL (fetch failed) whenever it
5035 if (cxt->where_is_undef == -1) {
5036 cxt->where_is_undef = cxt->tagnum;
5045 * Return the immortal yes value.
5047 static SV *retrieve_sv_yes(pTHX_ stcxt_t *cxt, char *cname)
5049 SV *sv = &PL_sv_yes;
5051 TRACEME(("retrieve_sv_yes"));
5060 * Return the immortal no value.
5062 static SV *retrieve_sv_no(pTHX_ stcxt_t *cxt, char *cname)
5066 TRACEME(("retrieve_sv_no"));
5075 * Retrieve a whole array.
5076 * Layout is SX_ARRAY <size> followed by each item, in increading index order.
5077 * Each item is stored as <object>.
5079 * When we come here, SX_ARRAY has been read already.
5081 static SV *retrieve_array(pTHX_ stcxt_t *cxt, char *cname)
5088 TRACEME(("retrieve_array (#%d)", cxt->tagnum));
5091 * Read length, and allocate array, then pre-extend it.
5095 TRACEME(("size = %d", len));
5097 SEEN(av, cname, 0); /* Will return if array not allocated nicely */
5101 return (SV *) av; /* No data follow if array is empty */
5104 * Now get each item in turn...
5107 for (i = 0; i < len; i++) {
5108 TRACEME(("(#%d) item", i));
5109 sv = retrieve(aTHX_ cxt, 0); /* Retrieve item */
5112 if (av_store(av, i, sv) == 0)
5116 TRACEME(("ok (retrieve_array at 0x%"UVxf")", PTR2UV(av)));
5124 * Retrieve a whole hash table.
5125 * Layout is SX_HASH <size> followed by each key/value pair, in random order.
5126 * Keys are stored as <length> <data>, the <data> section being omitted
5128 * Values are stored as <object>.
5130 * When we come here, SX_HASH has been read already.
5132 static SV *retrieve_hash(pTHX_ stcxt_t *cxt, char *cname)
5140 TRACEME(("retrieve_hash (#%d)", cxt->tagnum));
5143 * Read length, allocate table.
5147 TRACEME(("size = %d", len));
5149 SEEN(hv, cname, 0); /* Will return if table not allocated properly */
5151 return (SV *) hv; /* No data follow if table empty */
5152 hv_ksplit(hv, len); /* pre-extend hash to save multiple splits */
5155 * Now get each key/value pair in turn...
5158 for (i = 0; i < len; i++) {
5163 TRACEME(("(#%d) value", i));
5164 sv = retrieve(aTHX_ cxt, 0);
5170 * Since we're reading into kbuf, we must ensure we're not
5171 * recursing between the read and the hv_store() where it's used.
5172 * Hence the key comes after the value.
5175 RLEN(size); /* Get key size */
5176 KBUFCHK((STRLEN)size); /* Grow hash key read pool if needed */
5179 kbuf[size] = '\0'; /* Mark string end, just in case */
5180 TRACEME(("(#%d) key '%s'", i, kbuf));
5183 * Enter key/value pair into hash table.
5186 if (hv_store(hv, kbuf, (U32) size, sv, 0) == 0)
5190 TRACEME(("ok (retrieve_hash at 0x%"UVxf")", PTR2UV(hv)));
5198 * Retrieve a whole hash table.
5199 * Layout is SX_HASH <size> followed by each key/value pair, in random order.
5200 * Keys are stored as <length> <data>, the <data> section being omitted
5202 * Values are stored as <object>.
5204 * When we come here, SX_HASH has been read already.
5206 static SV *retrieve_flag_hash(pTHX_ stcxt_t *cxt, char *cname)
5216 GETMARK(hash_flags);
5217 TRACEME(("retrieve_flag_hash (#%d)", cxt->tagnum));
5219 * Read length, allocate table.
5222 #ifndef HAS_RESTRICTED_HASHES
5223 if (hash_flags & SHV_RESTRICTED) {
5224 if (cxt->derestrict < 0)
5226 = (SvTRUE(perl_get_sv("Storable::downgrade_restricted", TRUE))
5228 if (cxt->derestrict == 0)
5229 RESTRICTED_HASH_CROAK();
5234 TRACEME(("size = %d, flags = %d", len, hash_flags));
5236 SEEN(hv, cname, 0); /* Will return if table not allocated properly */
5238 return (SV *) hv; /* No data follow if table empty */
5239 hv_ksplit(hv, len); /* pre-extend hash to save multiple splits */
5242 * Now get each key/value pair in turn...
5245 for (i = 0; i < len; i++) {
5247 int store_flags = 0;
5252 TRACEME(("(#%d) value", i));
5253 sv = retrieve(aTHX_ cxt, 0);
5258 #ifdef HAS_RESTRICTED_HASHES
5259 if ((hash_flags & SHV_RESTRICTED) && (flags & SHV_K_LOCKED))
5263 if (flags & SHV_K_ISSV) {
5264 /* XXX you can't set a placeholder with an SV key.
5265 Then again, you can't get an SV key.
5266 Without messing around beyond what the API is supposed to do.
5269 TRACEME(("(#%d) keysv, flags=%d", i, flags));
5270 keysv = retrieve(aTHX_ cxt, 0);
5274 if (!hv_store_ent(hv, keysv, sv, 0))
5279 * Since we're reading into kbuf, we must ensure we're not
5280 * recursing between the read and the hv_store() where it's used.
5281 * Hence the key comes after the value.
5284 if (flags & SHV_K_PLACEHOLDER) {
5286 sv = &PL_sv_placeholder;
5287 store_flags |= HVhek_PLACEHOLD;
5289 if (flags & SHV_K_UTF8) {
5290 #ifdef HAS_UTF8_HASHES
5291 store_flags |= HVhek_UTF8;
5293 if (cxt->use_bytes < 0)
5295 = (SvTRUE(perl_get_sv("Storable::drop_utf8", TRUE))
5297 if (cxt->use_bytes == 0)
5301 #ifdef HAS_UTF8_HASHES
5302 if (flags & SHV_K_WASUTF8)
5303 store_flags |= HVhek_WASUTF8;
5306 RLEN(size); /* Get key size */
5307 KBUFCHK((STRLEN)size); /* Grow hash key read pool if needed */
5310 kbuf[size] = '\0'; /* Mark string end, just in case */
5311 TRACEME(("(#%d) key '%s' flags %X store_flags %X", i, kbuf,
5312 flags, store_flags));
5315 * Enter key/value pair into hash table.
5318 #ifdef HAS_RESTRICTED_HASHES
5319 if (hv_store_flags(hv, kbuf, size, sv, 0, store_flags) == 0)
5322 if (!(store_flags & HVhek_PLACEHOLD))
5323 if (hv_store(hv, kbuf, size, sv, 0) == 0)
5328 #ifdef HAS_RESTRICTED_HASHES
5329 if (hash_flags & SHV_RESTRICTED)
5333 TRACEME(("ok (retrieve_hash at 0x%"UVxf")", PTR2UV(hv)));
5341 * Return a code reference.
5343 static SV *retrieve_code(pTHX_ stcxt_t *cxt, char *cname)
5345 #if PERL_VERSION < 6
5346 CROAK(("retrieve_code does not work with perl 5.005 or less\n"));
5349 int type, count, tagnum;
5351 SV *sv, *text, *sub;
5353 TRACEME(("retrieve_code (#%d)", cxt->tagnum));
5356 * Insert dummy SV in the aseen array so that we don't screw
5357 * up the tag numbers. We would just make the internal
5358 * scalar an untagged item in the stream, but
5359 * retrieve_scalar() calls SEEN(). So we just increase the
5362 tagnum = cxt->tagnum;
5367 * Retrieve the source of the code reference
5368 * as a small or large scalar
5374 text = retrieve_scalar(aTHX_ cxt, cname);
5377 text = retrieve_lscalar(aTHX_ cxt, cname);
5380 CROAK(("Unexpected type %d in retrieve_code\n", type));
5384 * prepend "sub " to the source
5387 sub = newSVpvn("sub ", 4);
5388 sv_catpv(sub, SvPV_nolen(text)); /* XXX no sv_catsv! */
5392 * evaluate the source to a code reference and use the CV value
5395 if (cxt->eval == NULL) {
5396 cxt->eval = perl_get_sv("Storable::Eval", TRUE);
5397 SvREFCNT_inc(cxt->eval);
5399 if (!SvTRUE(cxt->eval)) {
5401 cxt->forgive_me == 0 ||
5402 (cxt->forgive_me < 0 && !(cxt->forgive_me =
5403 SvTRUE(perl_get_sv("Storable::forgive_me", TRUE)) ? 1 : 0))
5405 CROAK(("Can't eval, please set $Storable::Eval to a true value"));
5408 /* fix up the dummy entry... */
5409 av_store(cxt->aseen, tagnum, SvREFCNT_inc(sv));
5417 if (SvROK(cxt->eval) && SvTYPE(SvRV(cxt->eval)) == SVt_PVCV) {
5418 SV* errsv = get_sv("@", TRUE);
5419 sv_setpvn(errsv, "", 0); /* clear $@ */
5421 XPUSHs(sv_2mortal(newSVsv(sub)));
5423 count = call_sv(cxt->eval, G_SCALAR);
5426 CROAK(("Unexpected return value from $Storable::Eval callback\n"));
5428 if (SvTRUE(errsv)) {
5429 CROAK(("code %s caused an error: %s",
5430 SvPV_nolen(sub), SvPV_nolen(errsv)));
5434 cv = eval_pv(SvPV_nolen(sub), TRUE);
5436 if (cv && SvROK(cv) && SvTYPE(SvRV(cv)) == SVt_PVCV) {
5439 CROAK(("code %s did not evaluate to a subroutine reference\n", SvPV_nolen(sub)));
5442 SvREFCNT_inc(sv); /* XXX seems to be necessary */
5447 /* fix up the dummy entry... */
5448 av_store(cxt->aseen, tagnum, SvREFCNT_inc(sv));
5455 * old_retrieve_array
5457 * Retrieve a whole array in pre-0.6 binary format.
5459 * Layout is SX_ARRAY <size> followed by each item, in increading index order.
5460 * Each item is stored as SX_ITEM <object> or SX_IT_UNDEF for "holes".
5462 * When we come here, SX_ARRAY has been read already.
5464 static SV *old_retrieve_array(pTHX_ stcxt_t *cxt, char *cname)
5472 TRACEME(("old_retrieve_array (#%d)", cxt->tagnum));
5475 * Read length, and allocate array, then pre-extend it.
5479 TRACEME(("size = %d", len));
5481 SEEN(av, 0, 0); /* Will return if array not allocated nicely */
5485 return (SV *) av; /* No data follow if array is empty */
5488 * Now get each item in turn...
5491 for (i = 0; i < len; i++) {
5493 if (c == SX_IT_UNDEF) {
5494 TRACEME(("(#%d) undef item", i));
5495 continue; /* av_extend() already filled us with undef */
5498 (void) retrieve_other(aTHX_ (stcxt_t *) 0, 0); /* Will croak out */
5499 TRACEME(("(#%d) item", i));
5500 sv = retrieve(aTHX_ cxt, 0); /* Retrieve item */
5503 if (av_store(av, i, sv) == 0)
5507 TRACEME(("ok (old_retrieve_array at 0x%"UVxf")", PTR2UV(av)));
5515 * Retrieve a whole hash table in pre-0.6 binary format.
5517 * Layout is SX_HASH <size> followed by each key/value pair, in random order.
5518 * Keys are stored as SX_KEY <length> <data>, the <data> section being omitted
5520 * Values are stored as SX_VALUE <object> or SX_VL_UNDEF for "holes".
5522 * When we come here, SX_HASH has been read already.
5524 static SV *old_retrieve_hash(pTHX_ stcxt_t *cxt, char *cname)
5532 SV *sv_h_undef = (SV *) 0; /* hv_store() bug */
5534 TRACEME(("old_retrieve_hash (#%d)", cxt->tagnum));
5537 * Read length, allocate table.
5541 TRACEME(("size = %d", len));
5543 SEEN(hv, 0, 0); /* Will return if table not allocated properly */
5545 return (SV *) hv; /* No data follow if table empty */
5546 hv_ksplit(hv, len); /* pre-extend hash to save multiple splits */
5549 * Now get each key/value pair in turn...
5552 for (i = 0; i < len; i++) {
5558 if (c == SX_VL_UNDEF) {
5559 TRACEME(("(#%d) undef value", i));
5561 * Due to a bug in hv_store(), it's not possible to pass
5562 * &PL_sv_undef to hv_store() as a value, otherwise the
5563 * associated key will not be creatable any more. -- RAM, 14/01/97
5566 sv_h_undef = newSVsv(&PL_sv_undef);
5567 sv = SvREFCNT_inc(sv_h_undef);
5568 } else if (c == SX_VALUE) {
5569 TRACEME(("(#%d) value", i));
5570 sv = retrieve(aTHX_ cxt, 0);
5574 (void) retrieve_other(aTHX_ (stcxt_t *) 0, 0); /* Will croak out */
5578 * Since we're reading into kbuf, we must ensure we're not
5579 * recursing between the read and the hv_store() where it's used.
5580 * Hence the key comes after the value.
5585 (void) retrieve_other(aTHX_ (stcxt_t *) 0, 0); /* Will croak out */
5586 RLEN(size); /* Get key size */
5587 KBUFCHK((STRLEN)size); /* Grow hash key read pool if needed */
5590 kbuf[size] = '\0'; /* Mark string end, just in case */
5591 TRACEME(("(#%d) key '%s'", i, kbuf));
5594 * Enter key/value pair into hash table.
5597 if (hv_store(hv, kbuf, (U32) size, sv, 0) == 0)
5601 TRACEME(("ok (retrieve_hash at 0x%"UVxf")", PTR2UV(hv)));
5607 *** Retrieval engine.
5613 * Make sure the stored data we're trying to retrieve has been produced
5614 * on an ILP compatible system with the same byteorder. It croaks out in
5615 * case an error is detected. [ILP = integer-long-pointer sizes]
5616 * Returns null if error is detected, &PL_sv_undef otherwise.
5618 * Note that there's no byte ordering info emitted when network order was
5619 * used at store time.
5621 static SV *magic_check(pTHX_ stcxt_t *cxt)
5623 /* The worst case for a malicious header would be old magic (which is
5624 longer), major, minor, byteorder length byte of 255, 255 bytes of
5625 garbage, sizeof int, long, pointer, NV.
5626 So the worse of that we can read is 255 bytes of garbage plus 4.
5627 Err, I am assuming 8 bit bytes here. Please file a bug report if you're
5628 compiling perl on a system with chars that are larger than 8 bits.
5629 (Even Crays aren't *that* perverse).
5631 unsigned char buf[4 + 255];
5632 unsigned char *current;
5635 int use_network_order;
5638 int version_minor = 0;
5640 TRACEME(("magic_check"));
5643 * The "magic number" is only for files, not when freezing in memory.
5647 /* This includes the '\0' at the end. I want to read the extra byte,
5648 which is usually going to be the major version number. */
5649 STRLEN len = sizeof(magicstr);
5652 READ(buf, (SSize_t)(len)); /* Not null-terminated */
5654 /* Point at the byte after the byte we read. */
5655 current = buf + --len; /* Do the -- outside of macros. */
5657 if (memNE(buf, magicstr, len)) {
5659 * Try to read more bytes to check for the old magic number, which
5663 TRACEME(("trying for old magic number"));
5665 old_len = sizeof(old_magicstr) - 1;
5666 READ(current + 1, (SSize_t)(old_len - len));
5668 if (memNE(buf, old_magicstr, old_len))
5669 CROAK(("File is not a perl storable"));
5670 current = buf + old_len;
5672 use_network_order = *current;
5674 GETMARK(use_network_order);
5677 * Starting with 0.6, the "use_network_order" byte flag is also used to
5678 * indicate the version number of the binary, and therefore governs the
5679 * setting of sv_retrieve_vtbl. See magic_write().
5682 version_major = use_network_order >> 1;
5683 cxt->retrieve_vtbl = (SV*(**)(pTHX_ stcxt_t *cxt, char *cname)) (version_major ? sv_retrieve : sv_old_retrieve);
5685 TRACEME(("magic_check: netorder = 0x%x", use_network_order));
5689 * Starting with 0.7 (binary major 2), a full byte is dedicated to the
5690 * minor version of the protocol. See magic_write().
5693 if (version_major > 1)
5694 GETMARK(version_minor);
5696 cxt->ver_major = version_major;
5697 cxt->ver_minor = version_minor;
5699 TRACEME(("binary image version is %d.%d", version_major, version_minor));
5702 * Inter-operability sanity check: we can't retrieve something stored
5703 * using a format more recent than ours, because we have no way to
5704 * know what has changed, and letting retrieval go would mean a probable
5705 * failure reporting a "corrupted" storable file.
5709 version_major > STORABLE_BIN_MAJOR ||
5710 (version_major == STORABLE_BIN_MAJOR &&
5711 version_minor > STORABLE_BIN_MINOR)
5714 TRACEME(("but I am version is %d.%d", STORABLE_BIN_MAJOR,
5715 STORABLE_BIN_MINOR));
5717 if (version_major == STORABLE_BIN_MAJOR) {
5718 TRACEME(("cxt->accept_future_minor is %d",
5719 cxt->accept_future_minor));
5720 if (cxt->accept_future_minor < 0)
5721 cxt->accept_future_minor
5722 = (SvTRUE(perl_get_sv("Storable::accept_future_minor",
5725 if (cxt->accept_future_minor == 1)
5726 croak_now = 0; /* Don't croak yet. */
5729 CROAK(("Storable binary image v%d.%d more recent than I am (v%d.%d)",
5730 version_major, version_minor,
5731 STORABLE_BIN_MAJOR, STORABLE_BIN_MINOR));
5736 * If they stored using network order, there's no byte ordering
5737 * information to check.
5740 if ((cxt->netorder = (use_network_order & 0x1))) /* Extra () for -Wall */
5741 return &PL_sv_undef; /* No byte ordering info */
5743 /* In C truth is 1, falsehood is 0. Very convienient. */
5744 use_NV_size = version_major >= 2 && version_minor >= 2;
5747 length = c + 3 + use_NV_size;
5748 READ(buf, length); /* Not null-terminated */
5750 TRACEME(("byte order '%.*s' %d", c, buf, c));
5752 #ifdef USE_56_INTERWORK_KLUDGE
5753 /* No point in caching this in the context as we only need it once per
5754 retrieve, and we need to recheck it each read. */
5755 if (SvTRUE(perl_get_sv("Storable::interwork_56_64bit", TRUE))) {
5756 if ((c != (sizeof (byteorderstr_56) - 1))
5757 || memNE(buf, byteorderstr_56, c))
5758 CROAK(("Byte order is not compatible"));
5762 if ((c != (sizeof (byteorderstr) - 1)) || memNE(buf, byteorderstr, c))
5763 CROAK(("Byte order is not compatible"));
5769 if ((int) *current++ != sizeof(int))
5770 CROAK(("Integer size is not compatible"));
5773 if ((int) *current++ != sizeof(long))
5774 CROAK(("Long integer size is not compatible"));
5776 /* sizeof(char *) */
5777 if ((int) *current != sizeof(char *))
5778 CROAK(("Pointer size is not compatible"));
5782 if ((int) *++current != sizeof(NV))
5783 CROAK(("Double size is not compatible"));
5786 return &PL_sv_undef; /* OK */
5792 * Recursively retrieve objects from the specified file and return their
5793 * root SV (which may be an AV or an HV for what we care).
5794 * Returns null if there is a problem.
5796 static SV *retrieve(pTHX_ stcxt_t *cxt, char *cname)
5802 TRACEME(("retrieve"));
5805 * Grab address tag which identifies the object if we are retrieving
5806 * an older format. Since the new binary format counts objects and no
5807 * longer explicitely tags them, we must keep track of the correspondance
5810 * The following section will disappear one day when the old format is
5811 * no longer supported, hence the final "goto" in the "if" block.
5814 if (cxt->hseen) { /* Retrieving old binary */
5816 if (cxt->netorder) {
5818 READ(&nettag, sizeof(I32)); /* Ordered sequence of I32 */
5819 tag = (stag_t) nettag;
5821 READ(&tag, sizeof(stag_t)); /* Original address of the SV */
5824 if (type == SX_OBJECT) {
5826 svh = hv_fetch(cxt->hseen, (char *) &tag, sizeof(tag), FALSE);
5828 CROAK(("Old tag 0x%"UVxf" should have been mapped already",
5830 tagn = SvIV(*svh); /* Mapped tag number computed earlier below */
5833 * The following code is common with the SX_OBJECT case below.
5836 svh = av_fetch(cxt->aseen, tagn, FALSE);
5838 CROAK(("Object #%"IVdf" should have been retrieved already",
5841 TRACEME(("has retrieved #%d at 0x%"UVxf, tagn, PTR2UV(sv)));
5842 SvREFCNT_inc(sv); /* One more reference to this same sv */
5843 return sv; /* The SV pointer where object was retrieved */
5847 * Map new object, but don't increase tagnum. This will be done
5848 * by each of the retrieve_* functions when they call SEEN().
5850 * The mapping associates the "tag" initially present with a unique
5851 * tag number. See test for SX_OBJECT above to see how this is perused.
5854 if (!hv_store(cxt->hseen, (char *) &tag, sizeof(tag),
5855 newSViv(cxt->tagnum), 0))
5862 * Regular post-0.6 binary format.
5867 TRACEME(("retrieve type = %d", type));
5870 * Are we dealing with an object we should have already retrieved?
5873 if (type == SX_OBJECT) {
5877 svh = av_fetch(cxt->aseen, tag, FALSE);
5879 CROAK(("Object #%"IVdf" should have been retrieved already",
5882 TRACEME(("had retrieved #%d at 0x%"UVxf, tag, PTR2UV(sv)));
5883 SvREFCNT_inc(sv); /* One more reference to this same sv */
5884 return sv; /* The SV pointer where object was retrieved */
5885 } else if (type >= SX_ERROR && cxt->ver_minor > STORABLE_BIN_MINOR) {
5886 if (cxt->accept_future_minor < 0)
5887 cxt->accept_future_minor
5888 = (SvTRUE(perl_get_sv("Storable::accept_future_minor",
5891 if (cxt->accept_future_minor == 1) {
5892 CROAK(("Storable binary image v%d.%d contains data of type %d. "
5893 "This Storable is v%d.%d and can only handle data types up to %d",
5894 cxt->ver_major, cxt->ver_minor, type,
5895 STORABLE_BIN_MAJOR, STORABLE_BIN_MINOR, SX_ERROR - 1));
5899 first_time: /* Will disappear when support for old format is dropped */
5902 * Okay, first time through for this one.
5905 sv = RETRIEVE(cxt, type)(aTHX_ cxt, cname);
5907 return (SV *) 0; /* Failed */
5910 * Old binary formats (pre-0.7).
5912 * Final notifications, ended by SX_STORED may now follow.
5913 * Currently, the only pertinent notification to apply on the
5914 * freshly retrieved object is either:
5915 * SX_CLASS <char-len> <classname> for short classnames.
5916 * SX_LG_CLASS <int-len> <classname> for larger one (rare!).
5917 * Class name is then read into the key buffer pool used by
5918 * hash table key retrieval.
5921 if (cxt->ver_major < 2) {
5922 while ((type = GETCHAR()) != SX_STORED) {
5926 GETMARK(len); /* Length coded on a single char */
5928 case SX_LG_CLASS: /* Length coded on a regular integer */
5933 return (SV *) 0; /* Failed */
5935 KBUFCHK((STRLEN)len); /* Grow buffer as necessary */
5938 kbuf[len] = '\0'; /* Mark string end */
5943 TRACEME(("ok (retrieved 0x%"UVxf", refcnt=%d, %s)", PTR2UV(sv),
5944 SvREFCNT(sv) - 1, sv_reftype(sv, FALSE)));
5952 * Retrieve data held in file and return the root object.
5953 * Common routine for pretrieve and mretrieve.
5955 static SV *do_retrieve(
5963 int is_tainted; /* Is input source tainted? */
5964 int pre_06_fmt = 0; /* True with pre Storable 0.6 formats */
5966 TRACEME(("do_retrieve (optype = 0x%x)", optype));
5968 optype |= ST_RETRIEVE;
5971 * Sanity assertions for retrieve dispatch tables.
5974 ASSERT(sizeof(sv_old_retrieve) == sizeof(sv_retrieve),
5975 ("old and new retrieve dispatch table have same size"));
5976 ASSERT(sv_old_retrieve[SX_ERROR] == retrieve_other,
5977 ("SX_ERROR entry correctly initialized in old dispatch table"));
5978 ASSERT(sv_retrieve[SX_ERROR] == retrieve_other,
5979 ("SX_ERROR entry correctly initialized in new dispatch table"));
5982 * Workaround for CROAK leak: if they enter with a "dirty" context,
5983 * free up memory for them now.
5987 clean_context(aTHX_ cxt);
5990 * Now that STORABLE_xxx hooks exist, it is possible that they try to
5991 * re-enter retrieve() via the hooks.
5995 cxt = allocate_context(aTHX_ cxt);
5999 ASSERT(cxt->entry == 1, ("starting new recursion"));
6000 ASSERT(!cxt->s_dirty, ("clean context"));
6005 * Data is loaded into the memory buffer when f is NULL, unless `in' is
6006 * also NULL, in which case we're expecting the data to already lie
6007 * in the buffer (dclone case).
6010 KBUFINIT(); /* Allocate hash key reading pool once */
6016 const char *orig = SvPV(in, length);
6018 /* This is quite deliberate. I want the UTF8 routines
6019 to encounter the '\0' which perl adds at the end
6020 of all scalars, so that any new string also has
6023 STRLEN klen_tmp = length + 1;
6024 bool is_utf8 = TRUE;
6026 /* Just casting the &klen to (STRLEN) won't work
6027 well if STRLEN and I32 are of different widths.
6029 asbytes = (char*)bytes_from_utf8((U8*)orig,
6033 CROAK(("Frozen string corrupt - contains characters outside 0-255"));
6035 if (asbytes != orig) {
6036 /* String has been converted.
6037 There is no need to keep any reference to
6039 in = sv_newmortal();
6040 /* We donate the SV the malloc()ed string
6041 bytes_from_utf8 returned us. */
6042 SvUPGRADE(in, SVt_PV);
6044 SvPV_set(in, asbytes);
6045 SvLEN_set(in, klen_tmp);
6046 SvCUR_set(in, klen_tmp - 1);
6050 MBUF_SAVE_AND_LOAD(in);
6054 * Magic number verifications.
6056 * This needs to be done before calling init_retrieve_context()
6057 * since the format indication in the file are necessary to conduct
6058 * some of the initializations.
6061 cxt->fio = f; /* Where I/O are performed */
6063 if (!magic_check(aTHX_ cxt))
6064 CROAK(("Magic number checking on storable %s failed",
6065 cxt->fio ? "file" : "string"));
6067 TRACEME(("data stored in %s format",
6068 cxt->netorder ? "net order" : "native"));
6071 * Check whether input source is tainted, so that we don't wrongly
6072 * taint perfectly good values...
6074 * We assume file input is always tainted. If both `f' and `in' are
6075 * NULL, then we come from dclone, and tainted is already filled in
6076 * the context. That's a kludge, but the whole dclone() thing is
6077 * already quite a kludge anyway! -- RAM, 15/09/2000.
6080 is_tainted = f ? 1 : (in ? SvTAINTED(in) : cxt->s_tainted);
6081 TRACEME(("input source is %s", is_tainted ? "tainted" : "trusted"));
6082 init_retrieve_context(aTHX_ cxt, optype, is_tainted);
6084 ASSERT(is_retrieving(aTHX), ("within retrieve operation"));
6086 sv = retrieve(aTHX_ cxt, 0); /* Recursively retrieve object, get root SV */
6095 pre_06_fmt = cxt->hseen != NULL; /* Before we clean context */
6098 * The "root" context is never freed.
6101 clean_retrieve_context(aTHX_ cxt);
6102 if (cxt->prev) /* This context was stacked */
6103 free_context(aTHX_ cxt); /* It was not the "root" context */
6106 * Prepare returned value.
6110 TRACEME(("retrieve ERROR"));
6111 #if (PATCHLEVEL <= 4)
6112 /* perl 5.00405 seems to screw up at this point with an
6113 'attempt to modify a read only value' error reported in the
6114 eval { $self = pretrieve(*FILE) } in _retrieve.
6115 I can't see what the cause of this error is, but I suspect a
6116 bug in 5.004, as it seems to be capable of issuing spurious
6117 errors or core dumping with matches on $@. I'm not going to
6118 spend time on what could be a fruitless search for the cause,
6119 so here's a bodge. If you're running 5.004 and don't like
6120 this inefficiency, either upgrade to a newer perl, or you are
6121 welcome to find the problem and send in a patch.
6125 return &PL_sv_undef; /* Something went wrong, return undef */
6129 TRACEME(("retrieve got %s(0x%"UVxf")",
6130 sv_reftype(sv, FALSE), PTR2UV(sv)));
6133 * Backward compatibility with Storable-0.5@9 (which we know we
6134 * are retrieving if hseen is non-null): don't create an extra RV
6135 * for objects since we special-cased it at store time.
6137 * Build a reference to the SV returned by pretrieve even if it is
6138 * already one and not a scalar, for consistency reasons.
6141 if (pre_06_fmt) { /* Was not handling overloading by then */
6143 TRACEME(("fixing for old formats -- pre 0.6"));
6144 if (sv_type(aTHX_ sv) == svis_REF && (rv = SvRV(sv)) && SvOBJECT(rv)) {
6145 TRACEME(("ended do_retrieve() with an object -- pre 0.6"));
6151 * If reference is overloaded, restore behaviour.
6153 * NB: minor glitch here: normally, overloaded refs are stored specially
6154 * so that we can croak when behaviour cannot be re-installed, and also
6155 * avoid testing for overloading magic at each reference retrieval.
6157 * Unfortunately, the root reference is implicitely stored, so we must
6158 * check for possible overloading now. Furthermore, if we don't restore
6159 * overloading, we cannot croak as if the original ref was, because we
6160 * have no way to determine whether it was an overloaded ref or not in
6163 * It's a pity that overloading magic is attached to the rv, and not to
6164 * the underlying sv as blessing is.
6168 HV *stash = (HV *) SvSTASH(sv);
6169 SV *rv = newRV_noinc(sv);
6170 if (stash && Gv_AMG(stash)) {
6172 TRACEME(("restored overloading on root reference"));
6174 TRACEME(("ended do_retrieve() with an object"));
6178 TRACEME(("regular do_retrieve() end"));
6180 return newRV_noinc(sv);
6186 * Retrieve data held in file and return the root object, undef on error.
6188 SV *pretrieve(pTHX_ PerlIO *f)
6190 TRACEME(("pretrieve"));
6191 return do_retrieve(aTHX_ f, Nullsv, 0);
6197 * Retrieve data held in scalar and return the root object, undef on error.
6199 SV *mretrieve(pTHX_ SV *sv)
6201 TRACEME(("mretrieve"));
6202 return do_retrieve(aTHX_ (PerlIO*) 0, sv, 0);
6212 * Deep clone: returns a fresh copy of the original referenced SV tree.
6214 * This is achieved by storing the object in memory and restoring from
6215 * there. Not that efficient, but it should be faster than doing it from
6218 SV *dclone(pTHX_ SV *sv)
6222 stcxt_t *real_context;
6225 TRACEME(("dclone"));
6228 * Workaround for CROAK leak: if they enter with a "dirty" context,
6229 * free up memory for them now.
6233 clean_context(aTHX_ cxt);
6236 * do_store() optimizes for dclone by not freeing its context, should
6237 * we need to allocate one because we're deep cloning from a hook.
6240 if (!do_store(aTHX_ (PerlIO*) 0, sv, ST_CLONE, FALSE, (SV**) 0))
6241 return &PL_sv_undef; /* Error during store */
6244 * Because of the above optimization, we have to refresh the context,
6245 * since a new one could have been allocated and stacked by do_store().
6248 { dSTCXT; real_context = cxt; } /* Sub-block needed for macro */
6249 cxt = real_context; /* And we need this temporary... */
6252 * Now, `cxt' may refer to a new context.
6255 ASSERT(!cxt->s_dirty, ("clean context"));
6256 ASSERT(!cxt->entry, ("entry will not cause new context allocation"));
6259 TRACEME(("dclone stored %d bytes", size));
6263 * Since we're passing do_retrieve() both a NULL file and sv, we need
6264 * to pre-compute the taintedness of the input by setting cxt->tainted
6265 * to whatever state our own input string was. -- RAM, 15/09/2000
6267 * do_retrieve() will free non-root context.
6270 cxt->s_tainted = SvTAINTED(sv);
6271 out = do_retrieve(aTHX_ (PerlIO*) 0, Nullsv, ST_CLONE);
6273 TRACEME(("dclone returns 0x%"UVxf, PTR2UV(out)));
6283 * The Perl IO GV object distinguishes between input and output for sockets
6284 * but not for plain files. To allow Storable to transparently work on
6285 * plain files and sockets transparently, we have to ask xsubpp to fetch the
6286 * right object for us. Hence the OutputStream and InputStream declarations.
6288 * Before perl 5.004_05, those entries in the standard typemap are not
6289 * defined in perl include files, so we do that here.
6292 #ifndef OutputStream
6293 #define OutputStream PerlIO *
6294 #define InputStream PerlIO *
6295 #endif /* !OutputStream */
6297 MODULE = Storable PACKAGE = Storable::Cxt
6303 stcxt_t *cxt = (stcxt_t *)SvPVX(SvRV(self));
6307 if (!cxt->membuf_ro && mbase)
6309 if (cxt->membuf_ro && (cxt->msaved).arena)
6310 Safefree((cxt->msaved).arena);
6313 MODULE = Storable PACKAGE = Storable
6318 init_perinterp(aTHX);
6319 gv_fetchpv("Storable::drop_utf8", GV_ADDMULTI, SVt_PV);
6321 /* Only disable the used only once warning if we are in debugging mode. */
6322 gv_fetchpv("Storable::DEBUGME", GV_ADDMULTI, SVt_PV);
6324 #ifdef USE_56_INTERWORK_KLUDGE
6325 gv_fetchpv("Storable::interwork_56_64bit", GV_ADDMULTI, SVt_PV);
6331 init_perinterp(aTHX);
6338 RETVAL = pstore(aTHX_ f, obj);
6347 RETVAL = net_pstore(aTHX_ f, obj);
6355 RETVAL = mstore(aTHX_ obj);
6363 RETVAL = net_mstore(aTHX_ obj);
6371 RETVAL = pretrieve(aTHX_ f);
6379 RETVAL = mretrieve(aTHX_ sv);
6387 RETVAL = dclone(aTHX_ sv);
6392 last_op_in_netorder()
6394 RETVAL = last_op_in_netorder(aTHX);
6401 RETVAL = is_storing(aTHX);
6408 RETVAL = is_retrieving(aTHX);