This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
range operator warnings / 64-bit fix
[perl5.git] / ext / Storable / Storable.xs
CommitLineData
7a6a85bf 1/*
6ad89a2f 2 * Store and retrieve mechanism.
7a6a85bf
RG
3 *
4 * Copyright (c) 1995-2000, Raphael Manfredi
5 *
9e21b3d0
JH
6 * You may redistribute only under the same terms as Perl 5, as specified
7 * in the README file that comes with the distribution.
7a6a85bf 8 *
7a6a85bf
RG
9 */
10
11#include <EXTERN.h>
12#include <perl.h>
a3bf621f
JH
13#include <XSUB.h>
14
eadddfac 15#ifndef PATCHLEVEL
a3bf621f
JH
16# include <patchlevel.h> /* Perl's one, needed since 5.6 */
17# if !(defined(PERL_VERSION) || (SUBVERSION > 0 && defined(PATCHLEVEL)))
18# include <could_not_find_Perl_patchlevel.h>
19# endif
069d7f71 20#endif
7a6a85bf 21
5dff01bc 22#ifndef NETWARE
e8189732 23#if 0
9e21b3d0
JH
24#define DEBUGME /* Debug mode, turns assertions on as well */
25#define DASSERT /* Assertion mode */
26#endif
5dff01bc
JH
27#else /* NETWARE */
28#if 0 /* On NetWare USE_PERLIO is not used */
29#define DEBUGME /* Debug mode, turns assertions on as well */
30#define DASSERT /* Assertion mode */
31#endif
32#endif
7a6a85bf
RG
33
34/*
35 * Pre PerlIO time when none of USE_PERLIO and PERLIO_IS_STDIO is defined
36 * Provide them with the necessary defines so they can build with pre-5.004.
37 */
38#ifndef USE_PERLIO
39#ifndef PERLIO_IS_STDIO
40#define PerlIO FILE
41#define PerlIO_getc(x) getc(x)
42#define PerlIO_putc(f,x) putc(x,f)
43#define PerlIO_read(x,y,z) fread(y,1,z,x)
44#define PerlIO_write(x,y,z) fwrite(y,1,z,x)
45#define PerlIO_stdoutf printf
46#endif /* PERLIO_IS_STDIO */
47#endif /* USE_PERLIO */
48
49/*
50 * Earlier versions of perl might be used, we can't assume they have the latest!
51 */
f0ffaed8
JH
52
53#ifndef PERL_VERSION /* For perls < 5.6 */
e993d95c 54#define PERL_VERSION PATCHLEVEL
7a6a85bf
RG
55#ifndef newRV_noinc
56#define newRV_noinc(sv) ((Sv = newRV(sv)), --SvREFCNT(SvRV(Sv)), Sv)
57#endif
e993d95c 58#if (PATCHLEVEL <= 4) /* Older perls (<= 5.004) lack PL_ namespace */
7a6a85bf
RG
59#define PL_sv_yes sv_yes
60#define PL_sv_no sv_no
61#define PL_sv_undef sv_undef
e993d95c 62#if (SUBVERSION <= 4) /* 5.004_04 has been reported to lack newSVpvn */
dd19458b 63#define newSVpvn newSVpv
7a6a85bf 64#endif
e993d95c 65#endif /* PATCHLEVEL <= 4 */
7a6a85bf
RG
66#ifndef HvSHAREKEYS_off
67#define HvSHAREKEYS_off(hv) /* Ignore */
68#endif
f0ffaed8
JH
69#ifndef AvFILLp /* Older perls (<=5.003) lack AvFILLp */
70#define AvFILLp AvFILL
71#endif
72typedef double NV; /* Older perls lack the NV type */
cc964657
JH
73#define IVdf "ld" /* Various printf formats for Perl types */
74#define UVuf "lu"
75#define UVof "lo"
76#define UVxf "lx"
77#define INT2PTR(t,v) (t)(IV)(v)
78#define PTR2UV(v) (unsigned long)(v)
f0ffaed8 79#endif /* PERL_VERSION -- perls < 5.6 */
7a6a85bf 80
cc964657 81#ifndef NVef /* The following were not part of perl 5.6 */
9e21b3d0
JH
82#if defined(USE_LONG_DOUBLE) && \
83 defined(HAS_LONG_DOUBLE) && defined(PERL_PRIfldbl)
84#define NVef PERL_PRIeldbl
85#define NVff PERL_PRIfldbl
86#define NVgf PERL_PRIgldbl
87#else
cc964657
JH
88#define NVef "e"
89#define NVff "f"
90#define NVgf "g"
91#endif
92#endif
93
7a6a85bf 94#ifdef DEBUGME
8be2b38b
JH
95
96#ifndef DASSERT
97#define DASSERT
98#endif
99
90826881
JH
100/*
101 * TRACEME() will only output things when the $Storable::DEBUGME is true.
102 */
103
111e03c1
RG
104#define TRACEME(x) \
105 STMT_START { \
90826881 106 if (SvTRUE(perl_get_sv("Storable::DEBUGME", TRUE))) \
111e03c1
RG
107 { PerlIO_stdoutf x; PerlIO_stdoutf("\n"); } \
108 } STMT_END
7a6a85bf
RG
109#else
110#define TRACEME(x)
8be2b38b 111#endif /* DEBUGME */
7a6a85bf
RG
112
113#ifdef DASSERT
111e03c1
RG
114#define ASSERT(x,y) \
115 STMT_START { \
7a6a85bf
RG
116 if (!(x)) { \
117 PerlIO_stdoutf("ASSERT FAILED (\"%s\", line %d): ", \
118 __FILE__, __LINE__); \
119 PerlIO_stdoutf y; PerlIO_stdoutf("\n"); \
120 } \
111e03c1 121 } STMT_END
7a6a85bf
RG
122#else
123#define ASSERT(x,y)
124#endif
125
126/*
127 * Type markers.
128 */
129
130#define C(x) ((char) (x)) /* For markers with dynamic retrieval handling */
131
132#define SX_OBJECT C(0) /* Already stored object */
dd19458b 133#define SX_LSCALAR C(1) /* Scalar (large binary) follows (length, data) */
7a6a85bf
RG
134#define SX_ARRAY C(2) /* Array forthcominng (size, item list) */
135#define SX_HASH C(3) /* Hash forthcoming (size, key/value pair list) */
136#define SX_REF C(4) /* Reference to object forthcoming */
137#define SX_UNDEF C(5) /* Undefined scalar */
138#define SX_INTEGER C(6) /* Integer forthcoming */
139#define SX_DOUBLE C(7) /* Double forthcoming */
140#define SX_BYTE C(8) /* (signed) byte forthcoming */
141#define SX_NETINT C(9) /* Integer in network order forthcoming */
dd19458b 142#define SX_SCALAR C(10) /* Scalar (binary, small) follows (length, data) */
f062ea6c
PN
143#define SX_TIED_ARRAY C(11) /* Tied array forthcoming */
144#define SX_TIED_HASH C(12) /* Tied hash forthcoming */
145#define SX_TIED_SCALAR C(13) /* Tied scalar forthcoming */
7a6a85bf
RG
146#define SX_SV_UNDEF C(14) /* Perl's immortal PL_sv_undef */
147#define SX_SV_YES C(15) /* Perl's immortal PL_sv_yes */
148#define SX_SV_NO C(16) /* Perl's immortal PL_sv_no */
149#define SX_BLESS C(17) /* Object is blessed */
150#define SX_IX_BLESS C(18) /* Object is blessed, classname given by index */
151#define SX_HOOK C(19) /* Stored via hook, user-defined */
152#define SX_OVERLOAD C(20) /* Overloaded reference */
f062ea6c
PN
153#define SX_TIED_KEY C(21) /* Tied magic key forthcoming */
154#define SX_TIED_IDX C(22) /* Tied magic index forthcoming */
155#define SX_UTF8STR C(23) /* UTF-8 string forthcoming (small) */
156#define SX_LUTF8STR C(24) /* UTF-8 string forthcoming (large) */
157#define SX_FLAG_HASH C(25) /* Hash with flags forthcoming (size, flags, key/flags/value triplet list) */
464b080a
SR
158#define SX_CODE C(26) /* Code references as perl source code */
159#define SX_ERROR C(27) /* Error */
7a6a85bf
RG
160
161/*
162 * Those are only used to retrieve "old" pre-0.6 binary images.
163 */
164#define SX_ITEM 'i' /* An array item introducer */
165#define SX_IT_UNDEF 'I' /* Undefined array item */
d1be9408
JF
166#define SX_KEY 'k' /* A hash key introducer */
167#define SX_VALUE 'v' /* A hash value introducer */
7a6a85bf
RG
168#define SX_VL_UNDEF 'V' /* Undefined hash value */
169
170/*
171 * Those are only used to retrieve "old" pre-0.7 binary images
172 */
173
174#define SX_CLASS 'b' /* Object is blessed, class name length <255 */
f062ea6c 175#define SX_LG_CLASS 'B' /* Object is blessed, class name length >255 */
7a6a85bf
RG
176#define SX_STORED 'X' /* End of object */
177
178/*
179 * Limits between short/long length representation.
180 */
181
182#define LG_SCALAR 255 /* Large scalar length limit */
183#define LG_BLESS 127 /* Large classname bless limit */
184
185/*
186 * Operation types
187 */
188
189#define ST_STORE 0x1 /* Store operation */
190#define ST_RETRIEVE 0x2 /* Retrieval operation */
191#define ST_CLONE 0x4 /* Deep cloning operation */
192
193/*
194 * The following structure is used for hash table key retrieval. Since, when
195 * retrieving objects, we'll be facing blessed hash references, it's best
196 * to pre-allocate that buffer once and resize it as the need arises, never
197 * freeing it (keys will be saved away someplace else anyway, so even large
198 * keys are not enough a motivation to reclaim that space).
199 *
200 * This structure is also used for memory store/retrieve operations which
201 * happen in a fixed place before being malloc'ed elsewhere if persistency
202 * is required. Hence the aptr pointer.
203 */
204struct extendable {
205 char *arena; /* Will hold hash key strings, resized as needed */
206 STRLEN asiz; /* Size of aforementionned buffer */
207 char *aptr; /* Arena pointer, for in-place read/write ops */
208 char *aend; /* First invalid address */
209};
210
211/*
212 * At store time:
d1be9408 213 * A hash table records the objects which have already been stored.
7a6a85bf
RG
214 * Those are referred to as SX_OBJECT in the file, and their "tag" (i.e.
215 * an arbitrary sequence number) is used to identify them.
216 *
217 * At retrieve time:
218 * An array table records the objects which have already been retrieved,
219 * as seen by the tag determind by counting the objects themselves. The
220 * reference to that retrieved object is kept in the table, and is returned
221 * when an SX_OBJECT is found bearing that same tag.
222 *
223 * The same processing is used to record "classname" for blessed objects:
224 * indexing by a hash at store time, and via an array at retrieve time.
225 */
226
227typedef unsigned long stag_t; /* Used by pre-0.6 binary format */
228
229/*
230 * The following "thread-safe" related defines were contributed by
231 * Murray Nesbitt <murray@activestate.com> and integrated by RAM, who
232 * only renamed things a little bit to ensure consistency with surrounding
233 * code. -- RAM, 14/09/1999
234 *
235 * The original patch suffered from the fact that the stcxt_t structure
236 * was global. Murray tried to minimize the impact on the code as much as
237 * possible.
238 *
239 * Starting with 0.7, Storable can be re-entrant, via the STORABLE_xxx hooks
240 * on objects. Therefore, the notion of context needs to be generalized,
241 * threading or not.
242 */
243
244#define MY_VERSION "Storable(" XS_VERSION ")"
245
530b72ba
NC
246
247/*
248 * Conditional UTF8 support.
249 *
250 */
251#ifdef SvUTF8_on
252#define STORE_UTF8STR(pv, len) STORE_PV_LEN(pv, len, SX_UTF8STR, SX_LUTF8STR)
253#define HAS_UTF8_SCALARS
254#ifdef HeKUTF8
255#define HAS_UTF8_HASHES
256#define HAS_UTF8_ALL
257#else
258/* 5.6 perl has utf8 scalars but not hashes */
259#endif
260#else
261#define SvUTF8(sv) 0
262#define STORE_UTF8STR(pv, len) CROAK(("panic: storing UTF8 in non-UTF8 perl"))
263#endif
264#ifndef HAS_UTF8_ALL
265#define UTF8_CROAK() CROAK(("Cannot retrieve UTF8 data in non-UTF8 perl"))
266#endif
267
268#ifdef HvPLACEHOLDERS
269#define HAS_RESTRICTED_HASHES
270#else
271#define HVhek_PLACEHOLD 0x200
272#define RESTRICTED_HASH_CROAK() CROAK(("Cannot retrieve restricted hash"))
273#endif
274
275#ifdef HvHASKFLAGS
276#define HAS_HASH_KEY_FLAGS
277#endif
278
dd19458b
JH
279/*
280 * Fields s_tainted and s_dirty are prefixed with s_ because Perl's include
281 * files remap tainted and dirty when threading is enabled. That's bad for
282 * perl to remap such common words. -- RAM, 29/09/00
283 */
284
7a6a85bf
RG
285typedef struct stcxt {
286 int entry; /* flags recursion */
287 int optype; /* type of traversal operation */
e993d95c
JH
288 HV *hseen; /* which objects have been seen, store time */
289 AV *hook_seen; /* which SVs were returned by STORABLE_freeze() */
290 AV *aseen; /* which objects have been seen, retrieve time */
dfd91409 291 IV where_is_undef; /* index in aseen of PL_sv_undef */
e993d95c
JH
292 HV *hclass; /* which classnames have been seen, store time */
293 AV *aclass; /* which classnames have been seen, retrieve time */
294 HV *hook; /* cache for hook methods per class name */
295 IV tagnum; /* incremented at store time for each seen object */
296 IV classnum; /* incremented at store time for each seen classname */
297 int netorder; /* true if network order used */
298 int s_tainted; /* true if input source is tainted, at retrieve time */
299 int forgive_me; /* whether to be forgiving... */
464b080a
SR
300 int deparse; /* whether to deparse code refs */
301 SV *eval; /* whether to eval source code */
e993d95c 302 int canonical; /* whether to store hashes sorted by key */
530b72ba
NC
303#ifndef HAS_RESTRICTED_HASHES
304 int derestrict; /* whether to downgrade restrcted hashes */
305#endif
306#ifndef HAS_UTF8_ALL
307 int use_bytes; /* whether to bytes-ify utf8 */
308#endif
e8189732 309 int accept_future_minor; /* croak immediately on future minor versions? */
dd19458b 310 int s_dirty; /* context is dirty due to CROAK() -- can be cleaned */
e993d95c
JH
311 int membuf_ro; /* true means membuf is read-only and msaved is rw */
312 struct extendable keybuf; /* for hash key retrieval */
313 struct extendable membuf; /* for memory store/retrieve operations */
314 struct extendable msaved; /* where potentially valid mbuf is saved */
7a6a85bf
RG
315 PerlIO *fio; /* where I/O are performed, NULL for memory */
316 int ver_major; /* major of version for retrieved object */
317 int ver_minor; /* minor of version for retrieved object */
318 SV *(**retrieve_vtbl)(); /* retrieve dispatch table */
111e03c1
RG
319 SV *prev; /* contexts chained backwards in real recursion */
320 SV *my_sv; /* the blessed scalar who's SvPVX() I am */
7a6a85bf
RG
321} stcxt_t;
322
111e03c1
RG
323#define NEW_STORABLE_CXT_OBJ(cxt) \
324 STMT_START { \
325 SV *self = newSV(sizeof(stcxt_t) - 1); \
326 SV *my_sv = newRV_noinc(self); \
327 sv_bless(my_sv, gv_stashpv("Storable::Cxt", TRUE)); \
328 cxt = (stcxt_t *)SvPVX(self); \
329 Zero(cxt, 1, stcxt_t); \
330 cxt->my_sv = my_sv; \
331 } STMT_END
332
7a6a85bf
RG
333#if defined(MULTIPLICITY) || defined(PERL_OBJECT) || defined(PERL_CAPI)
334
e993d95c 335#if (PATCHLEVEL <= 4) && (SUBVERSION < 68)
7a6a85bf
RG
336#define dSTCXT_SV \
337 SV *perinterp_sv = perl_get_sv(MY_VERSION, FALSE)
338#else /* >= perl5.004_68 */
339#define dSTCXT_SV \
340 SV *perinterp_sv = *hv_fetch(PL_modglobal, \
341 MY_VERSION, sizeof(MY_VERSION)-1, TRUE)
342#endif /* < perl5.004_68 */
343
344#define dSTCXT_PTR(T,name) \
111e03c1 345 T name = ((perinterp_sv && SvIOK(perinterp_sv) && SvIVX(perinterp_sv) \
436c6dd3 346 ? (T)SvPVX(SvRV(INT2PTR(SV*,SvIVX(perinterp_sv)))) : (T) 0))
7a6a85bf
RG
347#define dSTCXT \
348 dSTCXT_SV; \
349 dSTCXT_PTR(stcxt_t *, cxt)
350
111e03c1
RG
351#define INIT_STCXT \
352 dSTCXT; \
353 NEW_STORABLE_CXT_OBJ(cxt); \
354 sv_setiv(perinterp_sv, PTR2IV(cxt->my_sv))
7a6a85bf 355
111e03c1
RG
356#define SET_STCXT(x) \
357 STMT_START { \
7a6a85bf 358 dSTCXT_SV; \
111e03c1
RG
359 sv_setiv(perinterp_sv, PTR2IV(x->my_sv)); \
360 } STMT_END
7a6a85bf
RG
361
362#else /* !MULTIPLICITY && !PERL_OBJECT && !PERL_CAPI */
363
85535365 364static stcxt_t *Context_ptr = NULL;
7a6a85bf 365#define dSTCXT stcxt_t *cxt = Context_ptr
85535365 366#define SET_STCXT(x) Context_ptr = x
111e03c1
RG
367#define INIT_STCXT \
368 dSTCXT; \
85535365
RG
369 NEW_STORABLE_CXT_OBJ(cxt); \
370 SET_STCXT(cxt)
111e03c1 371
7a6a85bf
RG
372
373#endif /* MULTIPLICITY || PERL_OBJECT || PERL_CAPI */
374
375/*
376 * KNOWN BUG:
377 * Croaking implies a memory leak, since we don't use setjmp/longjmp
378 * to catch the exit and free memory used during store or retrieve
379 * operations. This is not too difficult to fix, but I need to understand
380 * how Perl does it, and croaking is exceptional anyway, so I lack the
381 * motivation to do it.
382 *
383 * The current workaround is to mark the context as dirty when croaking,
384 * so that data structures can be freed whenever we renter Storable code
385 * (but only *then*: it's a workaround, not a fix).
386 *
387 * This is also imperfect, because we don't really know how far they trapped
388 * the croak(), and when we were recursing, we won't be able to clean anything
389 * but the topmost context stacked.
390 */
391
111e03c1 392#define CROAK(x) STMT_START { cxt->s_dirty = 1; croak x; } STMT_END
7a6a85bf
RG
393
394/*
395 * End of "thread-safe" related definitions.
396 */
397
398/*
9e21b3d0
JH
399 * LOW_32BITS
400 *
401 * Keep only the low 32 bits of a pointer (used for tags, which are not
402 * really pointers).
403 */
404
405#if PTRSIZE <= 4
406#define LOW_32BITS(x) ((I32) (x))
407#else
408#define LOW_32BITS(x) ((I32) ((unsigned long) (x) & 0xffffffffUL))
409#endif
410
411/*
412 * oI, oS, oC
413 *
414 * Hack for Crays, where sizeof(I32) == 8, and which are big-endians.
415 * Used in the WLEN and RLEN macros.
416 */
417
418#if INTSIZE > 4
419#define oI(x) ((I32 *) ((char *) (x) + 4))
420#define oS(x) ((x) - 4)
421#define oC(x) (x = 0)
422#define CRAY_HACK
423#else
424#define oI(x) (x)
425#define oS(x) (x)
426#define oC(x)
427#endif
428
429/*
7a6a85bf
RG
430 * key buffer handling
431 */
432#define kbuf (cxt->keybuf).arena
433#define ksiz (cxt->keybuf).asiz
111e03c1
RG
434#define KBUFINIT() \
435 STMT_START { \
7a6a85bf
RG
436 if (!kbuf) { \
437 TRACEME(("** allocating kbuf of 128 bytes")); \
438 New(10003, kbuf, 128, char); \
439 ksiz = 128; \
440 } \
111e03c1
RG
441 } STMT_END
442#define KBUFCHK(x) \
443 STMT_START { \
7a6a85bf 444 if (x >= ksiz) { \
e993d95c 445 TRACEME(("** extending kbuf to %d bytes (had %d)", x+1, ksiz)); \
7a6a85bf
RG
446 Renew(kbuf, x+1, char); \
447 ksiz = x+1; \
448 } \
111e03c1 449 } STMT_END
7a6a85bf
RG
450
451/*
452 * memory buffer handling
453 */
454#define mbase (cxt->membuf).arena
455#define msiz (cxt->membuf).asiz
456#define mptr (cxt->membuf).aptr
457#define mend (cxt->membuf).aend
458
459#define MGROW (1 << 13)
460#define MMASK (MGROW - 1)
461
462#define round_mgrow(x) \
463 ((unsigned long) (((unsigned long) (x) + MMASK) & ~MMASK))
464#define trunc_int(x) \
465 ((unsigned long) ((unsigned long) (x) & ~(sizeof(int)-1)))
466#define int_aligned(x) \
467 ((unsigned long) (x) == trunc_int(x))
468
111e03c1
RG
469#define MBUF_INIT(x) \
470 STMT_START { \
7a6a85bf
RG
471 if (!mbase) { \
472 TRACEME(("** allocating mbase of %d bytes", MGROW)); \
473 New(10003, mbase, MGROW, char); \
2cc1b180 474 msiz = (STRLEN)MGROW; \
7a6a85bf
RG
475 } \
476 mptr = mbase; \
477 if (x) \
478 mend = mbase + x; \
479 else \
480 mend = mbase + msiz; \
111e03c1 481 } STMT_END
7a6a85bf
RG
482
483#define MBUF_TRUNC(x) mptr = mbase + x
484#define MBUF_SIZE() (mptr - mbase)
485
486/*
e993d95c
JH
487 * MBUF_SAVE_AND_LOAD
488 * MBUF_RESTORE
489 *
490 * Those macros are used in do_retrieve() to save the current memory
491 * buffer into cxt->msaved, before MBUF_LOAD() can be used to retrieve
492 * data from a string.
493 */
111e03c1
RG
494#define MBUF_SAVE_AND_LOAD(in) \
495 STMT_START { \
e993d95c
JH
496 ASSERT(!cxt->membuf_ro, ("mbase not already saved")); \
497 cxt->membuf_ro = 1; \
498 TRACEME(("saving mbuf")); \
499 StructCopy(&cxt->membuf, &cxt->msaved, struct extendable); \
500 MBUF_LOAD(in); \
111e03c1 501 } STMT_END
e993d95c 502
111e03c1
RG
503#define MBUF_RESTORE() \
504 STMT_START { \
e993d95c
JH
505 ASSERT(cxt->membuf_ro, ("mbase is read-only")); \
506 cxt->membuf_ro = 0; \
507 TRACEME(("restoring mbuf")); \
508 StructCopy(&cxt->msaved, &cxt->membuf, struct extendable); \
111e03c1 509 } STMT_END
e993d95c
JH
510
511/*
7a6a85bf
RG
512 * Use SvPOKp(), because SvPOK() fails on tainted scalars.
513 * See store_scalar() for other usage of this workaround.
514 */
111e03c1
RG
515#define MBUF_LOAD(v) \
516 STMT_START { \
e993d95c 517 ASSERT(cxt->membuf_ro, ("mbase is read-only")); \
7a6a85bf
RG
518 if (!SvPOKp(v)) \
519 CROAK(("Not a scalar string")); \
520 mptr = mbase = SvPV(v, msiz); \
521 mend = mbase + msiz; \
111e03c1 522 } STMT_END
7a6a85bf 523
111e03c1
RG
524#define MBUF_XTEND(x) \
525 STMT_START { \
7a6a85bf
RG
526 int nsz = (int) round_mgrow((x)+msiz); \
527 int offset = mptr - mbase; \
e993d95c
JH
528 ASSERT(!cxt->membuf_ro, ("mbase is not read-only")); \
529 TRACEME(("** extending mbase from %d to %d bytes (wants %d new)", \
530 msiz, nsz, (x))); \
7a6a85bf
RG
531 Renew(mbase, nsz, char); \
532 msiz = nsz; \
533 mptr = mbase + offset; \
534 mend = mbase + nsz; \
111e03c1 535 } STMT_END
7a6a85bf 536
111e03c1
RG
537#define MBUF_CHK(x) \
538 STMT_START { \
7a6a85bf
RG
539 if ((mptr + (x)) > mend) \
540 MBUF_XTEND(x); \
111e03c1 541 } STMT_END
7a6a85bf 542
111e03c1
RG
543#define MBUF_GETC(x) \
544 STMT_START { \
7a6a85bf
RG
545 if (mptr < mend) \
546 x = (int) (unsigned char) *mptr++; \
547 else \
548 return (SV *) 0; \
111e03c1 549 } STMT_END
7a6a85bf 550
9e21b3d0 551#ifdef CRAY_HACK
111e03c1
RG
552#define MBUF_GETINT(x) \
553 STMT_START { \
9e21b3d0
JH
554 oC(x); \
555 if ((mptr + 4) <= mend) { \
556 memcpy(oI(&x), mptr, 4); \
557 mptr += 4; \
558 } else \
559 return (SV *) 0; \
111e03c1 560 } STMT_END
9e21b3d0 561#else
111e03c1
RG
562#define MBUF_GETINT(x) \
563 STMT_START { \
7a6a85bf
RG
564 if ((mptr + sizeof(int)) <= mend) { \
565 if (int_aligned(mptr)) \
566 x = *(int *) mptr; \
567 else \
568 memcpy(&x, mptr, sizeof(int)); \
569 mptr += sizeof(int); \
570 } else \
571 return (SV *) 0; \
111e03c1 572 } STMT_END
9e21b3d0 573#endif
7a6a85bf 574
111e03c1
RG
575#define MBUF_READ(x,s) \
576 STMT_START { \
7a6a85bf
RG
577 if ((mptr + (s)) <= mend) { \
578 memcpy(x, mptr, s); \
579 mptr += s; \
580 } else \
581 return (SV *) 0; \
111e03c1 582 } STMT_END
7a6a85bf 583
111e03c1
RG
584#define MBUF_SAFEREAD(x,s,z) \
585 STMT_START { \
7a6a85bf
RG
586 if ((mptr + (s)) <= mend) { \
587 memcpy(x, mptr, s); \
588 mptr += s; \
589 } else { \
590 sv_free(z); \
591 return (SV *) 0; \
592 } \
111e03c1 593 } STMT_END
7a6a85bf 594
111e03c1
RG
595#define MBUF_PUTC(c) \
596 STMT_START { \
7a6a85bf
RG
597 if (mptr < mend) \
598 *mptr++ = (char) c; \
599 else { \
600 MBUF_XTEND(1); \
601 *mptr++ = (char) c; \
602 } \
111e03c1 603 } STMT_END
7a6a85bf 604
9e21b3d0 605#ifdef CRAY_HACK
111e03c1
RG
606#define MBUF_PUTINT(i) \
607 STMT_START { \
9e21b3d0
JH
608 MBUF_CHK(4); \
609 memcpy(mptr, oI(&i), 4); \
610 mptr += 4; \
111e03c1 611 } STMT_END
9e21b3d0 612#else
111e03c1
RG
613#define MBUF_PUTINT(i) \
614 STMT_START { \
7a6a85bf
RG
615 MBUF_CHK(sizeof(int)); \
616 if (int_aligned(mptr)) \
617 *(int *) mptr = i; \
618 else \
619 memcpy(mptr, &i, sizeof(int)); \
620 mptr += sizeof(int); \
111e03c1 621 } STMT_END
9e21b3d0 622#endif
7a6a85bf 623
111e03c1
RG
624#define MBUF_WRITE(x,s) \
625 STMT_START { \
7a6a85bf
RG
626 MBUF_CHK(s); \
627 memcpy(mptr, x, s); \
628 mptr += s; \
111e03c1 629 } STMT_END
7a6a85bf
RG
630
631/*
7a6a85bf
RG
632 * Possible return values for sv_type().
633 */
634
635#define svis_REF 0
636#define svis_SCALAR 1
637#define svis_ARRAY 2
638#define svis_HASH 3
639#define svis_TIED 4
640#define svis_TIED_ITEM 5
464b080a
SR
641#define svis_CODE 6
642#define svis_OTHER 7
7a6a85bf
RG
643
644/*
645 * Flags for SX_HOOK.
646 */
647
648#define SHF_TYPE_MASK 0x03
649#define SHF_LARGE_CLASSLEN 0x04
650#define SHF_LARGE_STRLEN 0x08
651#define SHF_LARGE_LISTLEN 0x10
652#define SHF_IDX_CLASSNAME 0x20
653#define SHF_NEED_RECURSE 0x40
654#define SHF_HAS_LIST 0x80
655
656/*
b12202d0 657 * Types for SX_HOOK (last 2 bits in flags).
7a6a85bf
RG
658 */
659
660#define SHT_SCALAR 0
661#define SHT_ARRAY 1
662#define SHT_HASH 2
b12202d0
JH
663#define SHT_EXTRA 3 /* Read extra byte for type */
664
665/*
666 * The following are held in the "extra byte"...
667 */
668
669#define SHT_TSCALAR 4 /* 4 + 0 -- tied scalar */
670#define SHT_TARRAY 5 /* 4 + 1 -- tied array */
671#define SHT_THASH 6 /* 4 + 2 -- tied hash */
7a6a85bf
RG
672
673/*
e16e2ff8
NC
674 * per hash flags for flagged hashes
675 */
676
677#define SHV_RESTRICTED 0x01
678
679/*
680 * per key flags for flagged hashes
681 */
682
683#define SHV_K_UTF8 0x01
684#define SHV_K_WASUTF8 0x02
685#define SHV_K_LOCKED 0x04
686#define SHV_K_ISSV 0x08
687#define SHV_K_PLACEHOLDER 0x10
688
689/*
7a6a85bf
RG
690 * Before 0.6, the magic string was "perl-store" (binary version number 0).
691 *
692 * Since 0.6 introduced many binary incompatibilities, the magic string has
693 * been changed to "pst0" to allow an old image to be properly retrieved by
694 * a newer Storable, but ensure a newer image cannot be retrieved with an
695 * older version.
696 *
697 * At 0.7, objects are given the ability to serialize themselves, and the
698 * set of markers is extended, backward compatibility is not jeopardized,
699 * so the binary version number could have remained unchanged. To correctly
700 * spot errors if a file making use of 0.7-specific extensions is given to
701 * 0.6 for retrieval, the binary version was moved to "2". And I'm introducing
702 * a "minor" version, to better track this kind of evolution from now on.
703 *
704 */
2aeb6432
NC
705static const char old_magicstr[] = "perl-store"; /* Magic number before 0.6 */
706static const char magicstr[] = "pst0"; /* Used as a magic number */
7a6a85bf 707
2aeb6432
NC
708#define MAGICSTR_BYTES 'p','s','t','0'
709#define OLDMAGICSTR_BYTES 'p','e','r','l','-','s','t','o','r','e'
710
ee0f7aac
NC
711/* 5.6.x introduced the ability to have IVs as long long.
712 However, Configure still defined BYTEORDER based on the size of a long.
713 Storable uses the BYTEORDER value as part of the header, but doesn't
714 explicity store sizeof(IV) anywhere in the header. Hence on 5.6.x built
715 with IV as long long on a platform that uses Configure (ie most things
716 except VMS and Windows) headers are identical for the different IV sizes,
717 despite the files containing some fields based on sizeof(IV)
718 Erk. Broken-ness.
719 5.8 is consistent - the following redifinition kludge is only needed on
720 5.6.x, but the interwork is needed on 5.8 while data survives in files
721 with the 5.6 header.
722
723*/
724
725#if defined (IVSIZE) && (IVSIZE == 8) && (LONGSIZE == 4)
726#ifndef NO_56_INTERWORK_KLUDGE
727#define USE_56_INTERWORK_KLUDGE
728#endif
729#if BYTEORDER == 0x1234
730#undef BYTEORDER
731#define BYTEORDER 0x12345678
732#else
733#if BYTEORDER == 0x4321
734#undef BYTEORDER
735#define BYTEORDER 0x87654321
736#endif
737#endif
738#endif
739
2aeb6432
NC
740#if BYTEORDER == 0x1234
741#define BYTEORDER_BYTES '1','2','3','4'
742#else
743#if BYTEORDER == 0x12345678
744#define BYTEORDER_BYTES '1','2','3','4','5','6','7','8'
ee0f7aac
NC
745#ifdef USE_56_INTERWORK_KLUDGE
746#define BYTEORDER_BYTES_56 '1','2','3','4'
747#endif
2aeb6432
NC
748#else
749#if BYTEORDER == 0x87654321
750#define BYTEORDER_BYTES '8','7','6','5','4','3','2','1'
ee0f7aac
NC
751#ifdef USE_56_INTERWORK_KLUDGE
752#define BYTEORDER_BYTES_56 '4','3','2','1'
753#endif
2aeb6432
NC
754#else
755#if BYTEORDER == 0x4321
756#define BYTEORDER_BYTES '4','3','2','1'
757#else
758#error Unknown byteoder. Please append your byteorder to Storable.xs
759#endif
760#endif
761#endif
762#endif
763
764static const char byteorderstr[] = {BYTEORDER_BYTES, 0};
ee0f7aac
NC
765#ifdef USE_56_INTERWORK_KLUDGE
766static const char byteorderstr_56[] = {BYTEORDER_BYTES_56, 0};
767#endif
530b72ba 768
e16e2ff8 769#define STORABLE_BIN_MAJOR 2 /* Binary major "version" */
464b080a 770#define STORABLE_BIN_MINOR 6 /* Binary minor "version" */
530b72ba
NC
771
772/* If we aren't 5.7.3 or later, we won't be writing out files that use the
773 * new flagged hash introdued in 2.5, so put 2.4 in the binary header to
774 * maximise ease of interoperation with older Storables.
775 * Could we write 2.3s if we're on 5.005_03? NWC
776 */
e16e2ff8 777#if (PATCHLEVEL <= 6)
530b72ba 778#define STORABLE_BIN_WRITE_MINOR 4
e16e2ff8
NC
779#else
780/*
781 * As of perl 5.7.3, utf8 hash key is introduced.
782 * So this must change -- dankogai
783*/
464b080a 784#define STORABLE_BIN_WRITE_MINOR 6
e16e2ff8 785#endif /* (PATCHLEVEL <= 6) */
7a6a85bf 786
e9822705 787#if (PATCHLEVEL < 8 || (PATCHLEVEL == 8 && SUBVERSION < 1))
fcaa57e7
AMS
788#define PL_sv_placeholder PL_sv_undef
789#endif
790
7a6a85bf
RG
791/*
792 * Useful store shortcuts...
793 */
794
a8b7ef86
AMS
795/*
796 * Note that if you put more than one mark for storing a particular
797 * type of thing, *and* in the retrieve_foo() function you mark both
798 * the thingy's you get off with SEEN(), you *must* increase the
799 * tagnum with cxt->tagnum++ along with this macro!
800 * - samv 20Jan04
801 */
111e03c1
RG
802#define PUTMARK(x) \
803 STMT_START { \
7a6a85bf
RG
804 if (!cxt->fio) \
805 MBUF_PUTC(x); \
806 else if (PerlIO_putc(cxt->fio, x) == EOF) \
807 return -1; \
111e03c1 808 } STMT_END
7a6a85bf 809
111e03c1
RG
810#define WRITE_I32(x) \
811 STMT_START { \
9e21b3d0
JH
812 ASSERT(sizeof(x) == sizeof(I32), ("writing an I32")); \
813 if (!cxt->fio) \
814 MBUF_PUTINT(x); \
815 else if (PerlIO_write(cxt->fio, oI(&x), oS(sizeof(x))) != oS(sizeof(x))) \
816 return -1; \
111e03c1 817 } STMT_END
9e21b3d0 818
7a6a85bf 819#ifdef HAS_HTONL
111e03c1
RG
820#define WLEN(x) \
821 STMT_START { \
7a6a85bf
RG
822 if (cxt->netorder) { \
823 int y = (int) htonl(x); \
824 if (!cxt->fio) \
825 MBUF_PUTINT(y); \
9e21b3d0 826 else if (PerlIO_write(cxt->fio,oI(&y),oS(sizeof(y))) != oS(sizeof(y))) \
7a6a85bf
RG
827 return -1; \
828 } else { \
829 if (!cxt->fio) \
830 MBUF_PUTINT(x); \
9e21b3d0 831 else if (PerlIO_write(cxt->fio,oI(&x),oS(sizeof(x))) != oS(sizeof(x))) \
7a6a85bf
RG
832 return -1; \
833 } \
111e03c1 834 } STMT_END
7a6a85bf 835#else
9e21b3d0 836#define WLEN(x) WRITE_I32(x)
7a6a85bf
RG
837#endif
838
111e03c1
RG
839#define WRITE(x,y) \
840 STMT_START { \
7a6a85bf
RG
841 if (!cxt->fio) \
842 MBUF_WRITE(x,y); \
843 else if (PerlIO_write(cxt->fio, x, y) != y) \
844 return -1; \
111e03c1 845 } STMT_END
7a6a85bf 846
111e03c1
RG
847#define STORE_PV_LEN(pv, len, small, large) \
848 STMT_START { \
7a6a85bf
RG
849 if (len <= LG_SCALAR) { \
850 unsigned char clen = (unsigned char) len; \
dd19458b 851 PUTMARK(small); \
7a6a85bf
RG
852 PUTMARK(clen); \
853 if (len) \
854 WRITE(pv, len); \
855 } else { \
dd19458b 856 PUTMARK(large); \
7a6a85bf
RG
857 WLEN(len); \
858 WRITE(pv, len); \
859 } \
111e03c1 860 } STMT_END
7a6a85bf 861
dd19458b
JH
862#define STORE_SCALAR(pv, len) STORE_PV_LEN(pv, len, SX_SCALAR, SX_LSCALAR)
863
864/*
20bb3f55 865 * Store &PL_sv_undef in arrays without recursing through store().
7a6a85bf 866 */
20bb3f55 867#define STORE_SV_UNDEF() \
111e03c1 868 STMT_START { \
7a6a85bf 869 cxt->tagnum++; \
20bb3f55 870 PUTMARK(SX_SV_UNDEF); \
111e03c1 871 } STMT_END
7a6a85bf
RG
872
873/*
874 * Useful retrieve shortcuts...
875 */
876
877#define GETCHAR() \
878 (cxt->fio ? PerlIO_getc(cxt->fio) : (mptr >= mend ? EOF : (int) *mptr++))
879
111e03c1
RG
880#define GETMARK(x) \
881 STMT_START { \
7a6a85bf
RG
882 if (!cxt->fio) \
883 MBUF_GETC(x); \
76df4757 884 else if ((int) (x = PerlIO_getc(cxt->fio)) == EOF) \
7a6a85bf 885 return (SV *) 0; \
111e03c1 886 } STMT_END
7a6a85bf 887
111e03c1
RG
888#define READ_I32(x) \
889 STMT_START { \
9e21b3d0
JH
890 ASSERT(sizeof(x) == sizeof(I32), ("reading an I32")); \
891 oC(x); \
7a6a85bf
RG
892 if (!cxt->fio) \
893 MBUF_GETINT(x); \
9e21b3d0 894 else if (PerlIO_read(cxt->fio, oI(&x), oS(sizeof(x))) != oS(sizeof(x))) \
7a6a85bf 895 return (SV *) 0; \
111e03c1 896 } STMT_END
9e21b3d0
JH
897
898#ifdef HAS_NTOHL
111e03c1
RG
899#define RLEN(x) \
900 STMT_START { \
9e21b3d0 901 oC(x); \
7a6a85bf
RG
902 if (!cxt->fio) \
903 MBUF_GETINT(x); \
9e21b3d0 904 else if (PerlIO_read(cxt->fio, oI(&x), oS(sizeof(x))) != oS(sizeof(x))) \
7a6a85bf 905 return (SV *) 0; \
9e21b3d0
JH
906 if (cxt->netorder) \
907 x = (int) ntohl(x); \
111e03c1 908 } STMT_END
9e21b3d0
JH
909#else
910#define RLEN(x) READ_I32(x)
7a6a85bf
RG
911#endif
912
111e03c1
RG
913#define READ(x,y) \
914 STMT_START { \
7a6a85bf
RG
915 if (!cxt->fio) \
916 MBUF_READ(x, y); \
917 else if (PerlIO_read(cxt->fio, x, y) != y) \
918 return (SV *) 0; \
111e03c1 919 } STMT_END
7a6a85bf 920
111e03c1
RG
921#define SAFEREAD(x,y,z) \
922 STMT_START { \
7a6a85bf
RG
923 if (!cxt->fio) \
924 MBUF_SAFEREAD(x,y,z); \
925 else if (PerlIO_read(cxt->fio, x, y) != y) { \
926 sv_free(z); \
927 return (SV *) 0; \
928 } \
111e03c1 929 } STMT_END
7a6a85bf
RG
930
931/*
932 * This macro is used at retrieve time, to remember where object 'y', bearing a
933 * given tag 'tagnum', has been retrieved. Next time we see an SX_OBJECT marker,
934 * we'll therefore know where it has been retrieved and will be able to
935 * share the same reference, as in the original stored memory image.
b12202d0
JH
936 *
937 * We also need to bless objects ASAP for hooks (which may compute "ref $x"
938 * on the objects given to STORABLE_thaw and expect that to be defined), and
939 * also for overloaded objects (for which we might not find the stash if the
940 * object is not blessed yet--this might occur for overloaded objects that
941 * refer to themselves indirectly: if we blessed upon return from a sub
942 * retrieve(), the SX_OBJECT marker we'd found could not have overloading
943 * restored on it because the underlying object would not be blessed yet!).
944 *
945 * To achieve that, the class name of the last retrieved object is passed down
946 * recursively, and the first SEEN() call for which the class name is not NULL
947 * will bless the object.
dfd91409
NC
948 *
949 * i should be true iff sv is immortal (ie PL_sv_yes, PL_sv_no or PL_sv_undef)
7a6a85bf 950 */
dfd91409 951#define SEEN(y,c,i) \
111e03c1 952 STMT_START { \
7a6a85bf
RG
953 if (!y) \
954 return (SV *) 0; \
dfd91409 955 if (av_store(cxt->aseen, cxt->tagnum++, i ? (SV*)(y) : SvREFCNT_inc(y)) == 0) \
7a6a85bf 956 return (SV *) 0; \
43d061fe 957 TRACEME(("aseen(#%d) = 0x%"UVxf" (refcnt=%d)", cxt->tagnum-1, \
b12202d0
JH
958 PTR2UV(y), SvREFCNT(y)-1)); \
959 if (c) \
960 BLESS((SV *) (y), c); \
111e03c1 961 } STMT_END
7a6a85bf
RG
962
963/*
964 * Bless `s' in `p', via a temporary reference, required by sv_bless().
965 */
111e03c1
RG
966#define BLESS(s,p) \
967 STMT_START { \
7a6a85bf
RG
968 SV *ref; \
969 HV *stash; \
43d061fe 970 TRACEME(("blessing 0x%"UVxf" in %s", PTR2UV(s), (p))); \
7a6a85bf
RG
971 stash = gv_stashpv((p), TRUE); \
972 ref = newRV_noinc(s); \
973 (void) sv_bless(ref, stash); \
974 SvRV(ref) = 0; \
975 SvREFCNT_dec(ref); \
111e03c1 976 } STMT_END
7a6a85bf
RG
977
978static int store();
b12202d0 979static SV *retrieve(stcxt_t *cxt, char *cname);
7a6a85bf
RG
980
981/*
982 * Dynamic dispatching table for SV store.
983 */
984
985static int store_ref(stcxt_t *cxt, SV *sv);
986static int store_scalar(stcxt_t *cxt, SV *sv);
987static int store_array(stcxt_t *cxt, AV *av);
988static int store_hash(stcxt_t *cxt, HV *hv);
989static int store_tied(stcxt_t *cxt, SV *sv);
990static int store_tied_item(stcxt_t *cxt, SV *sv);
464b080a 991static int store_code(stcxt_t *cxt, CV *cv);
7a6a85bf 992static int store_other(stcxt_t *cxt, SV *sv);
f0ffaed8 993static int store_blessed(stcxt_t *cxt, SV *sv, int type, HV *pkg);
7a6a85bf 994
862382c7
JH
995static int (*sv_store[])(stcxt_t *cxt, SV *sv) = {
996 store_ref, /* svis_REF */
997 store_scalar, /* svis_SCALAR */
998 (int (*)(stcxt_t *cxt, SV *sv)) store_array, /* svis_ARRAY */
999 (int (*)(stcxt_t *cxt, SV *sv)) store_hash, /* svis_HASH */
1000 store_tied, /* svis_TIED */
1001 store_tied_item, /* svis_TIED_ITEM */
464b080a 1002 (int (*)(stcxt_t *cxt, SV *sv)) store_code, /* svis_CODE */
862382c7 1003 store_other, /* svis_OTHER */
7a6a85bf
RG
1004};
1005
1006#define SV_STORE(x) (*sv_store[x])
1007
1008/*
1009 * Dynamic dispatching tables for SV retrieval.
1010 */
1011
b12202d0
JH
1012static SV *retrieve_lscalar(stcxt_t *cxt, char *cname);
1013static SV *retrieve_lutf8str(stcxt_t *cxt, char *cname);
1014static SV *old_retrieve_array(stcxt_t *cxt, char *cname);
1015static SV *old_retrieve_hash(stcxt_t *cxt, char *cname);
1016static SV *retrieve_ref(stcxt_t *cxt, char *cname);
1017static SV *retrieve_undef(stcxt_t *cxt, char *cname);
1018static SV *retrieve_integer(stcxt_t *cxt, char *cname);
1019static SV *retrieve_double(stcxt_t *cxt, char *cname);
1020static SV *retrieve_byte(stcxt_t *cxt, char *cname);
1021static SV *retrieve_netint(stcxt_t *cxt, char *cname);
1022static SV *retrieve_scalar(stcxt_t *cxt, char *cname);
1023static SV *retrieve_utf8str(stcxt_t *cxt, char *cname);
1024static SV *retrieve_tied_array(stcxt_t *cxt, char *cname);
1025static SV *retrieve_tied_hash(stcxt_t *cxt, char *cname);
1026static SV *retrieve_tied_scalar(stcxt_t *cxt, char *cname);
1027static SV *retrieve_other(stcxt_t *cxt, char *cname);
1028
1029static SV *(*sv_old_retrieve[])(stcxt_t *cxt, char *cname) = {
7a6a85bf
RG
1030 0, /* SX_OBJECT -- entry unused dynamically */
1031 retrieve_lscalar, /* SX_LSCALAR */
1032 old_retrieve_array, /* SX_ARRAY -- for pre-0.6 binaries */
1033 old_retrieve_hash, /* SX_HASH -- for pre-0.6 binaries */
1034 retrieve_ref, /* SX_REF */
1035 retrieve_undef, /* SX_UNDEF */
1036 retrieve_integer, /* SX_INTEGER */
1037 retrieve_double, /* SX_DOUBLE */
1038 retrieve_byte, /* SX_BYTE */
1039 retrieve_netint, /* SX_NETINT */
1040 retrieve_scalar, /* SX_SCALAR */
1041 retrieve_tied_array, /* SX_ARRAY */
1042 retrieve_tied_hash, /* SX_HASH */
1043 retrieve_tied_scalar, /* SX_SCALAR */
1044 retrieve_other, /* SX_SV_UNDEF not supported */
1045 retrieve_other, /* SX_SV_YES not supported */
1046 retrieve_other, /* SX_SV_NO not supported */
1047 retrieve_other, /* SX_BLESS not supported */
1048 retrieve_other, /* SX_IX_BLESS not supported */
1049 retrieve_other, /* SX_HOOK not supported */
1050 retrieve_other, /* SX_OVERLOADED not supported */
1051 retrieve_other, /* SX_TIED_KEY not supported */
1052 retrieve_other, /* SX_TIED_IDX not supported */
dd19458b
JH
1053 retrieve_other, /* SX_UTF8STR not supported */
1054 retrieve_other, /* SX_LUTF8STR not supported */
e16e2ff8 1055 retrieve_other, /* SX_FLAG_HASH not supported */
464b080a 1056 retrieve_other, /* SX_CODE not supported */
7a6a85bf
RG
1057 retrieve_other, /* SX_ERROR */
1058};
1059
b12202d0
JH
1060static SV *retrieve_array(stcxt_t *cxt, char *cname);
1061static SV *retrieve_hash(stcxt_t *cxt, char *cname);
1062static SV *retrieve_sv_undef(stcxt_t *cxt, char *cname);
1063static SV *retrieve_sv_yes(stcxt_t *cxt, char *cname);
1064static SV *retrieve_sv_no(stcxt_t *cxt, char *cname);
1065static SV *retrieve_blessed(stcxt_t *cxt, char *cname);
1066static SV *retrieve_idx_blessed(stcxt_t *cxt, char *cname);
1067static SV *retrieve_hook(stcxt_t *cxt, char *cname);
1068static SV *retrieve_overloaded(stcxt_t *cxt, char *cname);
1069static SV *retrieve_tied_key(stcxt_t *cxt, char *cname);
1070static SV *retrieve_tied_idx(stcxt_t *cxt, char *cname);
e16e2ff8 1071static SV *retrieve_flag_hash(stcxt_t *cxt, char *cname);
464b080a 1072static SV *retrieve_code(stcxt_t *cxt, char *cname);
b12202d0
JH
1073
1074static SV *(*sv_retrieve[])(stcxt_t *cxt, char *cname) = {
7a6a85bf
RG
1075 0, /* SX_OBJECT -- entry unused dynamically */
1076 retrieve_lscalar, /* SX_LSCALAR */
1077 retrieve_array, /* SX_ARRAY */
1078 retrieve_hash, /* SX_HASH */
1079 retrieve_ref, /* SX_REF */
1080 retrieve_undef, /* SX_UNDEF */
1081 retrieve_integer, /* SX_INTEGER */
1082 retrieve_double, /* SX_DOUBLE */
1083 retrieve_byte, /* SX_BYTE */
1084 retrieve_netint, /* SX_NETINT */
1085 retrieve_scalar, /* SX_SCALAR */
1086 retrieve_tied_array, /* SX_ARRAY */
1087 retrieve_tied_hash, /* SX_HASH */
1088 retrieve_tied_scalar, /* SX_SCALAR */
1089 retrieve_sv_undef, /* SX_SV_UNDEF */
1090 retrieve_sv_yes, /* SX_SV_YES */
1091 retrieve_sv_no, /* SX_SV_NO */
1092 retrieve_blessed, /* SX_BLESS */
1093 retrieve_idx_blessed, /* SX_IX_BLESS */
1094 retrieve_hook, /* SX_HOOK */
1095 retrieve_overloaded, /* SX_OVERLOAD */
1096 retrieve_tied_key, /* SX_TIED_KEY */
1097 retrieve_tied_idx, /* SX_TIED_IDX */
dd19458b
JH
1098 retrieve_utf8str, /* SX_UTF8STR */
1099 retrieve_lutf8str, /* SX_LUTF8STR */
e16e2ff8 1100 retrieve_flag_hash, /* SX_HASH */
464b080a 1101 retrieve_code, /* SX_CODE */
7a6a85bf
RG
1102 retrieve_other, /* SX_ERROR */
1103};
1104
1105#define RETRIEVE(c,x) (*(c)->retrieve_vtbl[(x) >= SX_ERROR ? SX_ERROR : (x)])
1106
f0ffaed8 1107static SV *mbuf2sv(void);
7a6a85bf
RG
1108
1109/***
1110 *** Context management.
1111 ***/
1112
1113/*
1114 * init_perinterp
1115 *
1116 * Called once per "thread" (interpreter) to initialize some global context.
1117 */
f0ffaed8
JH
1118static void init_perinterp(void)
1119{
7a6a85bf
RG
1120 INIT_STCXT;
1121
1122 cxt->netorder = 0; /* true if network order used */
1123 cxt->forgive_me = -1; /* whether to be forgiving... */
1124}
1125
1126/*
e993d95c
JH
1127 * reset_context
1128 *
1129 * Called at the end of every context cleaning, to perform common reset
1130 * operations.
1131 */
1132static void reset_context(stcxt_t *cxt)
1133{
1134 cxt->entry = 0;
1135 cxt->s_dirty = 0;
1136 cxt->optype &= ~(ST_STORE|ST_RETRIEVE); /* Leave ST_CLONE alone */
1137}
1138
1139/*
7a6a85bf
RG
1140 * init_store_context
1141 *
1142 * Initialize a new store context for real recursion.
1143 */
f0ffaed8
JH
1144static void init_store_context(
1145 stcxt_t *cxt,
1146 PerlIO *f,
1147 int optype,
1148 int network_order)
7a6a85bf
RG
1149{
1150 TRACEME(("init_store_context"));
1151
1152 cxt->netorder = network_order;
1153 cxt->forgive_me = -1; /* Fetched from perl if needed */
464b080a
SR
1154 cxt->deparse = -1; /* Idem */
1155 cxt->eval = NULL; /* Idem */
7a6a85bf
RG
1156 cxt->canonical = -1; /* Idem */
1157 cxt->tagnum = -1; /* Reset tag numbers */
1158 cxt->classnum = -1; /* Reset class numbers */
1159 cxt->fio = f; /* Where I/O are performed */
1160 cxt->optype = optype; /* A store, or a deep clone */
1161 cxt->entry = 1; /* No recursion yet */
1162
1163 /*
1164 * The `hseen' table is used to keep track of each SV stored and their
1165 * associated tag numbers is special. It is "abused" because the
1166 * values stored are not real SV, just integers cast to (SV *),
1167 * which explains the freeing below.
1168 *
1169 * It is also one possible bottlneck to achieve good storing speed,
1170 * so the "shared keys" optimization is turned off (unlikely to be
1171 * of any use here), and the hash table is "pre-extended". Together,
1172 * those optimizations increase the throughput by 12%.
1173 */
1174
1175 cxt->hseen = newHV(); /* Table where seen objects are stored */
1176 HvSHAREKEYS_off(cxt->hseen);
1177
1178 /*
1179 * The following does not work well with perl5.004_04, and causes
1180 * a core dump later on, in a completely unrelated spot, which
1181 * makes me think there is a memory corruption going on.
1182 *
1183 * Calling hv_ksplit(hseen, HBUCKETS) instead of manually hacking
1184 * it below does not make any difference. It seems to work fine
1185 * with perl5.004_68 but given the probable nature of the bug,
1186 * that does not prove anything.
1187 *
1188 * It's a shame because increasing the amount of buckets raises
1189 * store() throughput by 5%, but until I figure this out, I can't
1190 * allow for this to go into production.
1191 *
1192 * It is reported fixed in 5.005, hence the #if.
1193 */
f0ffaed8 1194#if PERL_VERSION >= 5
7a6a85bf
RG
1195#define HBUCKETS 4096 /* Buckets for %hseen */
1196 HvMAX(cxt->hseen) = HBUCKETS - 1; /* keys %hseen = $HBUCKETS; */
1197#endif
1198
1199 /*
1200 * The `hclass' hash uses the same settings as `hseen' above, but it is
1201 * used to assign sequential tags (numbers) to class names for blessed
1202 * objects.
1203 *
1204 * We turn the shared key optimization on.
1205 */
1206
1207 cxt->hclass = newHV(); /* Where seen classnames are stored */
1208
f0ffaed8 1209#if PERL_VERSION >= 5
7a6a85bf
RG
1210 HvMAX(cxt->hclass) = HBUCKETS - 1; /* keys %hclass = $HBUCKETS; */
1211#endif
1212
1213 /*
1214 * The `hook' hash table is used to keep track of the references on
1215 * the STORABLE_freeze hook routines, when found in some class name.
1216 *
1217 * It is assumed that the inheritance tree will not be changed during
1218 * storing, and that no new method will be dynamically created by the
1219 * hooks.
1220 */
1221
1222 cxt->hook = newHV(); /* Table where hooks are cached */
90826881
JH
1223
1224 /*
1225 * The `hook_seen' array keeps track of all the SVs returned by
1226 * STORABLE_freeze hooks for us to serialize, so that they are not
1227 * reclaimed until the end of the serialization process. Each SV is
1228 * only stored once, the first time it is seen.
1229 */
1230
1231 cxt->hook_seen = newAV(); /* Lists SVs returned by STORABLE_freeze */
7a6a85bf
RG
1232}
1233
1234/*
1235 * clean_store_context
1236 *
1237 * Clean store context by
1238 */
f0ffaed8 1239static void clean_store_context(stcxt_t *cxt)
7a6a85bf
RG
1240{
1241 HE *he;
1242
1243 TRACEME(("clean_store_context"));
1244
1245 ASSERT(cxt->optype & ST_STORE, ("was performing a store()"));
1246
1247 /*
1248 * Insert real values into hashes where we stored faked pointers.
1249 */
1250
e993d95c
JH
1251 if (cxt->hseen) {
1252 hv_iterinit(cxt->hseen);
1253 while ((he = hv_iternext(cxt->hseen))) /* Extra () for -Wall, grr.. */
da5add9b 1254 HeVAL(he) = &PL_sv_undef;
e993d95c 1255 }
7a6a85bf 1256
e993d95c
JH
1257 if (cxt->hclass) {
1258 hv_iterinit(cxt->hclass);
1259 while ((he = hv_iternext(cxt->hclass))) /* Extra () for -Wall, grr.. */
da5add9b 1260 HeVAL(he) = &PL_sv_undef;
e993d95c 1261 }
7a6a85bf
RG
1262
1263 /*
1264 * And now dispose of them...
862382c7
JH
1265 *
1266 * The surrounding if() protection has been added because there might be
1267 * some cases where this routine is called more than once, during
1268 * exceptionnal events. This was reported by Marc Lehmann when Storable
1269 * is executed from mod_perl, and the fix was suggested by him.
1270 * -- RAM, 20/12/2000
1271 */
1272
1273 if (cxt->hseen) {
1274 HV *hseen = cxt->hseen;
1275 cxt->hseen = 0;
1276 hv_undef(hseen);
1277 sv_free((SV *) hseen);
1278 }
7a6a85bf 1279
862382c7
JH
1280 if (cxt->hclass) {
1281 HV *hclass = cxt->hclass;
1282 cxt->hclass = 0;
1283 hv_undef(hclass);
1284 sv_free((SV *) hclass);
1285 }
7a6a85bf 1286
862382c7
JH
1287 if (cxt->hook) {
1288 HV *hook = cxt->hook;
1289 cxt->hook = 0;
1290 hv_undef(hook);
1291 sv_free((SV *) hook);
1292 }
7a6a85bf 1293
862382c7
JH
1294 if (cxt->hook_seen) {
1295 AV *hook_seen = cxt->hook_seen;
1296 cxt->hook_seen = 0;
1297 av_undef(hook_seen);
1298 sv_free((SV *) hook_seen);
1299 }
90826881 1300
e8189732 1301 cxt->forgive_me = -1; /* Fetched from perl if needed */
464b080a
SR
1302 cxt->deparse = -1; /* Idem */
1303 if (cxt->eval) {
1304 SvREFCNT_dec(cxt->eval);
1305 }
1306 cxt->eval = NULL; /* Idem */
e8189732
NC
1307 cxt->canonical = -1; /* Idem */
1308
e993d95c 1309 reset_context(cxt);
7a6a85bf
RG
1310}
1311
1312/*
1313 * init_retrieve_context
1314 *
1315 * Initialize a new retrieve context for real recursion.
1316 */
dd19458b 1317static void init_retrieve_context(stcxt_t *cxt, int optype, int is_tainted)
7a6a85bf
RG
1318{
1319 TRACEME(("init_retrieve_context"));
1320
1321 /*
1322 * The hook hash table is used to keep track of the references on
1323 * the STORABLE_thaw hook routines, when found in some class name.
1324 *
1325 * It is assumed that the inheritance tree will not be changed during
1326 * storing, and that no new method will be dynamically created by the
1327 * hooks.
1328 */
1329
1330 cxt->hook = newHV(); /* Caches STORABLE_thaw */
1331
1332 /*
1333 * If retrieving an old binary version, the cxt->retrieve_vtbl variable
1334 * was set to sv_old_retrieve. We'll need a hash table to keep track of
1335 * the correspondance between the tags and the tag number used by the
1336 * new retrieve routines.
1337 */
1338
2cc1b180
JH
1339 cxt->hseen = (((void*)cxt->retrieve_vtbl == (void*)sv_old_retrieve)
1340 ? newHV() : 0);
7a6a85bf
RG
1341
1342 cxt->aseen = newAV(); /* Where retrieved objects are kept */
dfd91409 1343 cxt->where_is_undef = -1; /* Special case for PL_sv_undef */
7a6a85bf
RG
1344 cxt->aclass = newAV(); /* Where seen classnames are kept */
1345 cxt->tagnum = 0; /* Have to count objects... */
1346 cxt->classnum = 0; /* ...and class names as well */
1347 cxt->optype = optype;
dd19458b 1348 cxt->s_tainted = is_tainted;
7a6a85bf 1349 cxt->entry = 1; /* No recursion yet */
530b72ba
NC
1350#ifndef HAS_RESTRICTED_HASHES
1351 cxt->derestrict = -1; /* Fetched from perl if needed */
1352#endif
1353#ifndef HAS_UTF8_ALL
1354 cxt->use_bytes = -1; /* Fetched from perl if needed */
1355#endif
e8189732 1356 cxt->accept_future_minor = -1; /* Fetched from perl if needed */
7a6a85bf
RG
1357}
1358
1359/*
1360 * clean_retrieve_context
1361 *
1362 * Clean retrieve context by
1363 */
dd19458b 1364static void clean_retrieve_context(stcxt_t *cxt)
7a6a85bf
RG
1365{
1366 TRACEME(("clean_retrieve_context"));
1367
1368 ASSERT(cxt->optype & ST_RETRIEVE, ("was performing a retrieve()"));
1369
862382c7
JH
1370 if (cxt->aseen) {
1371 AV *aseen = cxt->aseen;
1372 cxt->aseen = 0;
1373 av_undef(aseen);
1374 sv_free((SV *) aseen);
1375 }
dfd91409 1376 cxt->where_is_undef = -1;
7a6a85bf 1377
862382c7
JH
1378 if (cxt->aclass) {
1379 AV *aclass = cxt->aclass;
1380 cxt->aclass = 0;
1381 av_undef(aclass);
1382 sv_free((SV *) aclass);
1383 }
7a6a85bf 1384
862382c7
JH
1385 if (cxt->hook) {
1386 HV *hook = cxt->hook;
1387 cxt->hook = 0;
1388 hv_undef(hook);
1389 sv_free((SV *) hook);
1390 }
7a6a85bf 1391
862382c7
JH
1392 if (cxt->hseen) {
1393 HV *hseen = cxt->hseen;
1394 cxt->hseen = 0;
1395 hv_undef(hseen);
1396 sv_free((SV *) hseen); /* optional HV, for backward compat. */
1397 }
7a6a85bf 1398
e8189732
NC
1399#ifndef HAS_RESTRICTED_HASHES
1400 cxt->derestrict = -1; /* Fetched from perl if needed */
1401#endif
1402#ifndef HAS_UTF8_ALL
1403 cxt->use_bytes = -1; /* Fetched from perl if needed */
1404#endif
1405 cxt->accept_future_minor = -1; /* Fetched from perl if needed */
1406
e993d95c 1407 reset_context(cxt);
7a6a85bf
RG
1408}
1409
1410/*
1411 * clean_context
1412 *
1413 * A workaround for the CROAK bug: cleanup the last context.
1414 */
e993d95c 1415static void clean_context(stcxt_t *cxt)
7a6a85bf
RG
1416{
1417 TRACEME(("clean_context"));
1418
dd19458b 1419 ASSERT(cxt->s_dirty, ("dirty context"));
7a6a85bf 1420
e993d95c
JH
1421 if (cxt->membuf_ro)
1422 MBUF_RESTORE();
1423
1424 ASSERT(!cxt->membuf_ro, ("mbase is not read-only"));
1425
7a6a85bf
RG
1426 if (cxt->optype & ST_RETRIEVE)
1427 clean_retrieve_context(cxt);
e993d95c 1428 else if (cxt->optype & ST_STORE)
7a6a85bf 1429 clean_store_context(cxt);
e993d95c
JH
1430 else
1431 reset_context(cxt);
862382c7
JH
1432
1433 ASSERT(!cxt->s_dirty, ("context is clean"));
e993d95c 1434 ASSERT(cxt->entry == 0, ("context is reset"));
7a6a85bf
RG
1435}
1436
1437/*
1438 * allocate_context
1439 *
1440 * Allocate a new context and push it on top of the parent one.
1441 * This new context is made globally visible via SET_STCXT().
1442 */
1443static stcxt_t *allocate_context(parent_cxt)
1444stcxt_t *parent_cxt;
1445{
1446 stcxt_t *cxt;
1447
1448 TRACEME(("allocate_context"));
1449
dd19458b 1450 ASSERT(!parent_cxt->s_dirty, ("parent context clean"));
7a6a85bf 1451
111e03c1
RG
1452 NEW_STORABLE_CXT_OBJ(cxt);
1453 cxt->prev = parent_cxt->my_sv;
7a6a85bf
RG
1454 SET_STCXT(cxt);
1455
e993d95c
JH
1456 ASSERT(!cxt->s_dirty, ("clean context"));
1457
7a6a85bf
RG
1458 return cxt;
1459}
1460
1461/*
1462 * free_context
1463 *
1464 * Free current context, which cannot be the "root" one.
1465 * Make the context underneath globally visible via SET_STCXT().
1466 */
1467static void free_context(cxt)
1468stcxt_t *cxt;
1469{
111e03c1 1470 stcxt_t *prev = (stcxt_t *)(cxt->prev ? SvPVX(SvRV(cxt->prev)) : 0);
7a6a85bf
RG
1471
1472 TRACEME(("free_context"));
1473
dd19458b 1474 ASSERT(!cxt->s_dirty, ("clean context"));
7a6a85bf
RG
1475 ASSERT(prev, ("not freeing root context"));
1476
111e03c1 1477 SvREFCNT_dec(cxt->my_sv);
7a6a85bf 1478 SET_STCXT(prev);
e993d95c
JH
1479
1480 ASSERT(cxt, ("context not void"));
7a6a85bf
RG
1481}
1482
1483/***
1484 *** Predicates.
1485 ***/
1486
1487/*
1488 * is_storing
1489 *
1490 * Tells whether we're in the middle of a store operation.
1491 */
f0ffaed8 1492int is_storing(void)
7a6a85bf
RG
1493{
1494 dSTCXT;
1495
1496 return cxt->entry && (cxt->optype & ST_STORE);
1497}
1498
1499/*
1500 * is_retrieving
1501 *
1502 * Tells whether we're in the middle of a retrieve operation.
1503 */
f0ffaed8 1504int is_retrieving(void)
7a6a85bf
RG
1505{
1506 dSTCXT;
1507
1508 return cxt->entry && (cxt->optype & ST_RETRIEVE);
1509}
1510
1511/*
1512 * last_op_in_netorder
1513 *
1514 * Returns whether last operation was made using network order.
1515 *
1516 * This is typically out-of-band information that might prove useful
1517 * to people wishing to convert native to network order data when used.
1518 */
f0ffaed8 1519int last_op_in_netorder(void)
7a6a85bf
RG
1520{
1521 dSTCXT;
1522
1523 return cxt->netorder;
1524}
1525
1526/***
1527 *** Hook lookup and calling routines.
1528 ***/
1529
1530/*
1531 * pkg_fetchmeth
1532 *
1533 * A wrapper on gv_fetchmethod_autoload() which caches results.
1534 *
1535 * Returns the routine reference as an SV*, or null if neither the package
1536 * nor its ancestors know about the method.
1537 */
f0ffaed8
JH
1538static SV *pkg_fetchmeth(
1539 HV *cache,
1540 HV *pkg,
1541 char *method)
7a6a85bf
RG
1542{
1543 GV *gv;
1544 SV *sv;
7a6a85bf
RG
1545
1546 /*
1547 * The following code is the same as the one performed by UNIVERSAL::can
1548 * in the Perl core.
1549 */
1550
1551 gv = gv_fetchmethod_autoload(pkg, method, FALSE);
1552 if (gv && isGV(gv)) {
1553 sv = newRV((SV*) GvCV(gv));
9e21b3d0 1554 TRACEME(("%s->%s: 0x%"UVxf, HvNAME(pkg), method, PTR2UV(sv)));
7a6a85bf
RG
1555 } else {
1556 sv = newSVsv(&PL_sv_undef);
1557 TRACEME(("%s->%s: not found", HvNAME(pkg), method));
1558 }
1559
1560 /*
1561 * Cache the result, ignoring failure: if we can't store the value,
1562 * it just won't be cached.
1563 */
1564
1565 (void) hv_store(cache, HvNAME(pkg), strlen(HvNAME(pkg)), sv, 0);
1566
1567 return SvOK(sv) ? sv : (SV *) 0;
1568}
1569
1570/*
1571 * pkg_hide
1572 *
1573 * Force cached value to be undef: hook ignored even if present.
1574 */
f0ffaed8
JH
1575static void pkg_hide(
1576 HV *cache,
1577 HV *pkg,
1578 char *method)
7a6a85bf
RG
1579{
1580 (void) hv_store(cache,
1581 HvNAME(pkg), strlen(HvNAME(pkg)), newSVsv(&PL_sv_undef), 0);
1582}
1583
1584/*
212e9bde
JH
1585 * pkg_uncache
1586 *
1587 * Discard cached value: a whole fetch loop will be retried at next lookup.
1588 */
1589static void pkg_uncache(
1590 HV *cache,
1591 HV *pkg,
1592 char *method)
1593{
1594 (void) hv_delete(cache, HvNAME(pkg), strlen(HvNAME(pkg)), G_DISCARD);
1595}
1596
1597/*
7a6a85bf
RG
1598 * pkg_can
1599 *
1600 * Our own "UNIVERSAL::can", which caches results.
1601 *
1602 * Returns the routine reference as an SV*, or null if the object does not
1603 * know about the method.
1604 */
f0ffaed8
JH
1605static SV *pkg_can(
1606 HV *cache,
1607 HV *pkg,
1608 char *method)
7a6a85bf
RG
1609{
1610 SV **svh;
1611 SV *sv;
1612
1613 TRACEME(("pkg_can for %s->%s", HvNAME(pkg), method));
1614
1615 /*
1616 * Look into the cache to see whether we already have determined
1617 * where the routine was, if any.
1618 *
1619 * NOTA BENE: we don't use `method' at all in our lookup, since we know
1620 * that only one hook (i.e. always the same) is cached in a given cache.
1621 */
1622
1623 svh = hv_fetch(cache, HvNAME(pkg), strlen(HvNAME(pkg)), FALSE);
1624 if (svh) {
1625 sv = *svh;
1626 if (!SvOK(sv)) {
1627 TRACEME(("cached %s->%s: not found", HvNAME(pkg), method));
1628 return (SV *) 0;
1629 } else {
43d061fe 1630 TRACEME(("cached %s->%s: 0x%"UVxf,
9e21b3d0 1631 HvNAME(pkg), method, PTR2UV(sv)));
7a6a85bf
RG
1632 return sv;
1633 }
1634 }
1635
1636 TRACEME(("not cached yet"));
1637 return pkg_fetchmeth(cache, pkg, method); /* Fetch and cache */
1638}
1639
1640/*
1641 * scalar_call
1642 *
1643 * Call routine as obj->hook(av) in scalar context.
1644 * Propagates the single returned value if not called in void context.
1645 */
f0ffaed8
JH
1646static SV *scalar_call(
1647 SV *obj,
1648 SV *hook,
1649 int cloning,
1650 AV *av,
1651 I32 flags)
7a6a85bf
RG
1652{
1653 dSP;
1654 int count;
1655 SV *sv = 0;
1656
1657 TRACEME(("scalar_call (cloning=%d)", cloning));
1658
1659 ENTER;
1660 SAVETMPS;
1661
1662 PUSHMARK(sp);
1663 XPUSHs(obj);
1664 XPUSHs(sv_2mortal(newSViv(cloning))); /* Cloning flag */
1665 if (av) {
1666 SV **ary = AvARRAY(av);
1667 int cnt = AvFILLp(av) + 1;
1668 int i;
1669 XPUSHs(ary[0]); /* Frozen string */
1670 for (i = 1; i < cnt; i++) {
43d061fe
JH
1671 TRACEME(("pushing arg #%d (0x%"UVxf")...",
1672 i, PTR2UV(ary[i])));
7a6a85bf
RG
1673 XPUSHs(sv_2mortal(newRV(ary[i])));
1674 }
1675 }
1676 PUTBACK;
1677
1678 TRACEME(("calling..."));
1679 count = perl_call_sv(hook, flags); /* Go back to Perl code */
1680 TRACEME(("count = %d", count));
1681
1682 SPAGAIN;
1683
1684 if (count) {
1685 sv = POPs;
1686 SvREFCNT_inc(sv); /* We're returning it, must stay alive! */
1687 }
1688
1689 PUTBACK;
1690 FREETMPS;
1691 LEAVE;
1692
1693 return sv;
1694}
1695
1696/*
1697 * array_call
1698 *
f9a1036d 1699 * Call routine obj->hook(cloning) in list context.
7a6a85bf
RG
1700 * Returns the list of returned values in an array.
1701 */
f0ffaed8
JH
1702static AV *array_call(
1703 SV *obj,
1704 SV *hook,
1705 int cloning)
7a6a85bf
RG
1706{
1707 dSP;
1708 int count;
1709 AV *av;
1710 int i;
1711
f0ffaed8 1712 TRACEME(("array_call (cloning=%d)", cloning));
7a6a85bf
RG
1713
1714 ENTER;
1715 SAVETMPS;
1716
1717 PUSHMARK(sp);
1718 XPUSHs(obj); /* Target object */
1719 XPUSHs(sv_2mortal(newSViv(cloning))); /* Cloning flag */
1720 PUTBACK;
1721
1722 count = perl_call_sv(hook, G_ARRAY); /* Go back to Perl code */
1723
1724 SPAGAIN;
1725
1726 av = newAV();
1727 for (i = count - 1; i >= 0; i--) {
1728 SV *sv = POPs;
1729 av_store(av, i, SvREFCNT_inc(sv));
1730 }
1731
1732 PUTBACK;
1733 FREETMPS;
1734 LEAVE;
1735
1736 return av;
1737}
1738
1739/*
1740 * known_class
1741 *
1742 * Lookup the class name in the `hclass' table and either assign it a new ID
1743 * or return the existing one, by filling in `classnum'.
1744 *
1745 * Return true if the class was known, false if the ID was just generated.
1746 */
f0ffaed8
JH
1747static int known_class(
1748 stcxt_t *cxt,
1749 char *name, /* Class name */
1750 int len, /* Name length */
1751 I32 *classnum)
7a6a85bf
RG
1752{
1753 SV **svh;
1754 HV *hclass = cxt->hclass;
1755
1756 TRACEME(("known_class (%s)", name));
1757
1758 /*
1759 * Recall that we don't store pointers in this hash table, but tags.
1760 * Therefore, we need LOW_32BITS() to extract the relevant parts.
1761 */
1762
1763 svh = hv_fetch(hclass, name, len, FALSE);
1764 if (svh) {
1765 *classnum = LOW_32BITS(*svh);
1766 return TRUE;
1767 }
1768
1769 /*
1770 * Unknown classname, we need to record it.
7a6a85bf
RG
1771 */
1772
1773 cxt->classnum++;
3341c981 1774 if (!hv_store(hclass, name, len, INT2PTR(SV*, cxt->classnum), 0))
7a6a85bf
RG
1775 CROAK(("Unable to record new classname"));
1776
1777 *classnum = cxt->classnum;
1778 return FALSE;
1779}
1780
1781/***
1782 *** Sepcific store routines.
1783 ***/
1784
1785/*
1786 * store_ref
1787 *
1788 * Store a reference.
1789 * Layout is SX_REF <object> or SX_OVERLOAD <object>.
1790 */
f0ffaed8 1791static int store_ref(stcxt_t *cxt, SV *sv)
7a6a85bf 1792{
43d061fe 1793 TRACEME(("store_ref (0x%"UVxf")", PTR2UV(sv)));
7a6a85bf
RG
1794
1795 /*
1796 * Follow reference, and check if target is overloaded.
1797 */
1798
1799 sv = SvRV(sv);
1800
1801 if (SvOBJECT(sv)) {
1802 HV *stash = (HV *) SvSTASH(sv);
1803 if (stash && Gv_AMG(stash)) {
9e21b3d0 1804 TRACEME(("ref (0x%"UVxf") is overloaded", PTR2UV(sv)));
7a6a85bf
RG
1805 PUTMARK(SX_OVERLOAD);
1806 } else
1807 PUTMARK(SX_REF);
1808 } else
1809 PUTMARK(SX_REF);
1810
1811 return store(cxt, sv);
1812}
1813
1814/*
1815 * store_scalar
1816 *
1817 * Store a scalar.
1818 *
e16e2ff8 1819 * Layout is SX_LSCALAR <length> <data>, SX_SCALAR <length> <data> or SX_UNDEF.
7a6a85bf
RG
1820 * The <data> section is omitted if <length> is 0.
1821 *
1822 * If integer or double, the layout is SX_INTEGER <data> or SX_DOUBLE <data>.
1823 * Small integers (within [-127, +127]) are stored as SX_BYTE <byte>.
1824 */
f0ffaed8 1825static int store_scalar(stcxt_t *cxt, SV *sv)
7a6a85bf
RG
1826{
1827 IV iv;
1828 char *pv;
1829 STRLEN len;
1830 U32 flags = SvFLAGS(sv); /* "cc -O" may put it in register */
1831
43d061fe 1832 TRACEME(("store_scalar (0x%"UVxf")", PTR2UV(sv)));
7a6a85bf
RG
1833
1834 /*
1835 * For efficiency, break the SV encapsulation by peaking at the flags
1836 * directly without using the Perl macros to avoid dereferencing
1837 * sv->sv_flags each time we wish to check the flags.
1838 */
1839
1840 if (!(flags & SVf_OK)) { /* !SvOK(sv) */
1841 if (sv == &PL_sv_undef) {
1842 TRACEME(("immortal undef"));
1843 PUTMARK(SX_SV_UNDEF);
1844 } else {
86bbd6dc 1845 TRACEME(("undef at 0x%"UVxf, PTR2UV(sv)));
7a6a85bf
RG
1846 PUTMARK(SX_UNDEF);
1847 }
1848 return 0;
1849 }
1850
1851 /*
1852 * Always store the string representation of a scalar if it exists.
1853 * Gisle Aas provided me with this test case, better than a long speach:
1854 *
1855 * perl -MDevel::Peek -le '$a="abc"; $a+0; Dump($a)'
1856 * SV = PVNV(0x80c8520)
1857 * REFCNT = 1
1858 * FLAGS = (NOK,POK,pNOK,pPOK)
1859 * IV = 0
1860 * NV = 0
1861 * PV = 0x80c83d0 "abc"\0
1862 * CUR = 3
1863 * LEN = 4
1864 *
1865 * Write SX_SCALAR, length, followed by the actual data.
1866 *
1867 * Otherwise, write an SX_BYTE, SX_INTEGER or an SX_DOUBLE as
1868 * appropriate, followed by the actual (binary) data. A double
1869 * is written as a string if network order, for portability.
1870 *
1871 * NOTE: instead of using SvNOK(sv), we test for SvNOKp(sv).
1872 * The reason is that when the scalar value is tainted, the SvNOK(sv)
1873 * value is false.
1874 *
1875 * The test for a read-only scalar with both POK and NOK set is meant
1876 * to quickly detect &PL_sv_yes and &PL_sv_no without having to pay the
1877 * address comparison for each scalar we store.
1878 */
1879
1880#define SV_MAYBE_IMMORTAL (SVf_READONLY|SVf_POK|SVf_NOK)
1881
1882 if ((flags & SV_MAYBE_IMMORTAL) == SV_MAYBE_IMMORTAL) {
1883 if (sv == &PL_sv_yes) {
1884 TRACEME(("immortal yes"));
1885 PUTMARK(SX_SV_YES);
1886 } else if (sv == &PL_sv_no) {
1887 TRACEME(("immortal no"));
1888 PUTMARK(SX_SV_NO);
1889 } else {
1890 pv = SvPV(sv, len); /* We know it's SvPOK */
1891 goto string; /* Share code below */
1892 }
db670f21
NC
1893 } else if (flags & SVf_POK) {
1894 /* public string - go direct to string read. */
1895 goto string_readlen;
1896 } else if (
1897#if (PATCHLEVEL <= 6)
1898 /* For 5.6 and earlier NV flag trumps IV flag, so only use integer
1899 direct if NV flag is off. */
1900 (flags & (SVf_NOK | SVf_IOK)) == SVf_IOK
1901#else
1902 /* 5.7 rules are that if IV public flag is set, IV value is as
1903 good, if not better, than NV value. */
1904 flags & SVf_IOK
1905#endif
1906 ) {
1907 iv = SvIV(sv);
1908 /*
1909 * Will come here from below with iv set if double is an integer.
1910 */
1911 integer:
7a6a85bf 1912
db670f21
NC
1913 /* Sorry. This isn't in 5.005_56 (IIRC) or earlier. */
1914#ifdef SVf_IVisUV
1915 /* Need to do this out here, else 0xFFFFFFFF becomes iv of -1
1916 * (for example) and that ends up in the optimised small integer
1917 * case.
1918 */
1919 if ((flags & SVf_IVisUV) && SvUV(sv) > IV_MAX) {
1920 TRACEME(("large unsigned integer as string, value = %"UVuf, SvUV(sv)));
1921 goto string_readlen;
1922 }
1923#endif
1924 /*
1925 * Optimize small integers into a single byte, otherwise store as
1926 * a real integer (converted into network order if they asked).
1927 */
7a6a85bf 1928
db670f21
NC
1929 if (iv >= -128 && iv <= 127) {
1930 unsigned char siv = (unsigned char) (iv + 128); /* [0,255] */
1931 PUTMARK(SX_BYTE);
1932 PUTMARK(siv);
1933 TRACEME(("small integer stored as %d", siv));
1934 } else if (cxt->netorder) {
1935#ifndef HAS_HTONL
1936 TRACEME(("no htonl, fall back to string for integer"));
1937 goto string_readlen;
1938#else
1939 I32 niv;
7a6a85bf 1940
7a6a85bf 1941
db670f21
NC
1942#if IVSIZE > 4
1943 if (
1944#ifdef SVf_IVisUV
1945 /* Sorry. This isn't in 5.005_56 (IIRC) or earlier. */
1946 ((flags & SVf_IVisUV) && SvUV(sv) > 0x7FFFFFFF) ||
1947#endif
1948 (iv > 0x7FFFFFFF) || (iv < -0x80000000)) {
1949 /* Bigger than 32 bits. */
1950 TRACEME(("large network order integer as string, value = %"IVdf, iv));
1951 goto string_readlen;
1952 }
1953#endif
7a6a85bf 1954
db670f21
NC
1955 niv = (I32) htonl((I32) iv);
1956 TRACEME(("using network order"));
1957 PUTMARK(SX_NETINT);
1958 WRITE_I32(niv);
1959#endif
1960 } else {
1961 PUTMARK(SX_INTEGER);
1962 WRITE(&iv, sizeof(iv));
1963 }
1964
1965 TRACEME(("ok (integer 0x%"UVxf", value = %"IVdf")", PTR2UV(sv), iv));
1966 } else if (flags & SVf_NOK) {
1967 NV nv;
1968#if (PATCHLEVEL <= 6)
1969 nv = SvNV(sv);
1970 /*
1971 * Watch for number being an integer in disguise.
1972 */
1973 if (nv == (NV) (iv = I_V(nv))) {
1974 TRACEME(("double %"NVff" is actually integer %"IVdf, nv, iv));
1975 goto integer; /* Share code above */
1976 }
1977#else
7a6a85bf 1978
db670f21 1979 SvIV_please(sv);
3ddd445a 1980 if (SvIOK_notUV(sv)) {
db670f21
NC
1981 iv = SvIV(sv);
1982 goto integer; /* Share code above */
1983 }
1984 nv = SvNV(sv);
1985#endif
7a6a85bf 1986
db670f21
NC
1987 if (cxt->netorder) {
1988 TRACEME(("double %"NVff" stored as string", nv));
1989 goto string_readlen; /* Share code below */
1990 }
7a6a85bf 1991
db670f21
NC
1992 PUTMARK(SX_DOUBLE);
1993 WRITE(&nv, sizeof(nv));
7a6a85bf 1994
db670f21 1995 TRACEME(("ok (double 0x%"UVxf", value = %"NVff")", PTR2UV(sv), nv));
7a6a85bf 1996
db670f21
NC
1997 } else if (flags & (SVp_POK | SVp_NOK | SVp_IOK)) {
1998 I32 wlen; /* For 64-bit machines */
7a6a85bf 1999
db670f21
NC
2000 string_readlen:
2001 pv = SvPV(sv, len);
7a6a85bf 2002
db670f21
NC
2003 /*
2004 * Will come here from above if it was readonly, POK and NOK but
2005 * neither &PL_sv_yes nor &PL_sv_no.
2006 */
2007 string:
2008
2009 wlen = (I32) len; /* WLEN via STORE_SCALAR expects I32 */
2010 if (SvUTF8 (sv))
2011 STORE_UTF8STR(pv, wlen);
2012 else
2013 STORE_SCALAR(pv, wlen);
2014 TRACEME(("ok (scalar 0x%"UVxf" '%s', length = %"IVdf")",
2015 PTR2UV(sv), SvPVX(sv), (IV)len));
7a6a85bf 2016 } else
db670f21
NC
2017 CROAK(("Can't determine type of %s(0x%"UVxf")",
2018 sv_reftype(sv, FALSE),
2019 PTR2UV(sv)));
2020 return 0; /* Ok, no recursion on scalars */
7a6a85bf
RG
2021}
2022
2023/*
2024 * store_array
2025 *
2026 * Store an array.
2027 *
2028 * Layout is SX_ARRAY <size> followed by each item, in increading index order.
2029 * Each item is stored as <object>.
2030 */
f0ffaed8 2031static int store_array(stcxt_t *cxt, AV *av)
7a6a85bf
RG
2032{
2033 SV **sav;
2034 I32 len = av_len(av) + 1;
2035 I32 i;
2036 int ret;
2037
43d061fe 2038 TRACEME(("store_array (0x%"UVxf")", PTR2UV(av)));
7a6a85bf
RG
2039
2040 /*
2041 * Signal array by emitting SX_ARRAY, followed by the array length.
2042 */
2043
2044 PUTMARK(SX_ARRAY);
2045 WLEN(len);
2046 TRACEME(("size = %d", len));
2047
2048 /*
2049 * Now store each item recursively.
2050 */
2051
2052 for (i = 0; i < len; i++) {
2053 sav = av_fetch(av, i, 0);
2054 if (!sav) {
2055 TRACEME(("(#%d) undef item", i));
20bb3f55 2056 STORE_SV_UNDEF();
7a6a85bf
RG
2057 continue;
2058 }
2059 TRACEME(("(#%d) item", i));
e993d95c 2060 if ((ret = store(cxt, *sav))) /* Extra () for -Wall, grr... */
7a6a85bf
RG
2061 return ret;
2062 }
2063
2064 TRACEME(("ok (array)"));
2065
2066 return 0;
2067}
2068
2069/*
2070 * sortcmp
2071 *
2072 * Sort two SVs
2073 * Borrowed from perl source file pp_ctl.c, where it is used by pp_sort.
2074 */
2075static int
f0ffaed8 2076sortcmp(const void *a, const void *b)
7a6a85bf
RG
2077{
2078 return sv_cmp(*(SV * const *) a, *(SV * const *) b);
2079}
2080
2081
2082/*
2083 * store_hash
2084 *
d1be9408 2085 * Store a hash table.
7a6a85bf 2086 *
e16e2ff8
NC
2087 * For a "normal" hash (not restricted, no utf8 keys):
2088 *
7a6a85bf
RG
2089 * Layout is SX_HASH <size> followed by each key/value pair, in random order.
2090 * Values are stored as <object>.
2091 * Keys are stored as <length> <data>, the <data> section being omitted
2092 * if length is 0.
c194a0a3
TB
2093 *
2094 * For a "fancy" hash (restricted or utf8 keys):
2095 *
2096 * Layout is SX_FLAG_HASH <size> <hash flags> followed by each key/value pair,
e16e2ff8
NC
2097 * in random order.
2098 * Values are stored as <object>.
2099 * Keys are stored as <flags> <length> <data>, the <data> section being omitted
2100 * if length is 0.
2101 * Currently the only hash flag is "restriced"
2102 * Key flags are as for hv.h
7a6a85bf 2103 */
f0ffaed8 2104static int store_hash(stcxt_t *cxt, HV *hv)
7a6a85bf 2105{
530b72ba
NC
2106 I32 len =
2107#ifdef HAS_RESTRICTED_HASHES
2108 HvTOTALKEYS(hv);
2109#else
2110 HvKEYS(hv);
2111#endif
7a6a85bf
RG
2112 I32 i;
2113 int ret = 0;
2114 I32 riter;
2115 HE *eiter;
530b72ba
NC
2116 int flagged_hash = ((SvREADONLY(hv)
2117#ifdef HAS_HASH_KEY_FLAGS
2118 || HvHASKFLAGS(hv)
2119#endif
2120 ) ? 1 : 0);
e16e2ff8 2121 unsigned char hash_flags = (SvREADONLY(hv) ? SHV_RESTRICTED : 0);
7a6a85bf 2122
e16e2ff8
NC
2123 if (flagged_hash) {
2124 /* needs int cast for C++ compilers, doesn't it? */
2125 TRACEME(("store_hash (0x%"UVxf") (flags %x)", PTR2UV(hv),
2126 (int) hash_flags));
2127 } else {
2128 TRACEME(("store_hash (0x%"UVxf")", PTR2UV(hv)));
2129 }
7a6a85bf
RG
2130
2131 /*
2132 * Signal hash by emitting SX_HASH, followed by the table length.
2133 */
2134
e16e2ff8
NC
2135 if (flagged_hash) {
2136 PUTMARK(SX_FLAG_HASH);
2137 PUTMARK(hash_flags);
2138 } else {
2139 PUTMARK(SX_HASH);
2140 }
7a6a85bf
RG
2141 WLEN(len);
2142 TRACEME(("size = %d", len));
2143
2144 /*
2145 * Save possible iteration state via each() on that table.
2146 */
2147
2148 riter = HvRITER(hv);
2149 eiter = HvEITER(hv);
2150 hv_iterinit(hv);
2151
2152 /*
2153 * Now store each item recursively.
2154 *
2155 * If canonical is defined to some true value then store each
2156 * key/value pair in sorted order otherwise the order is random.
2157 * Canonical order is irrelevant when a deep clone operation is performed.
2158 *
2159 * Fetch the value from perl only once per store() operation, and only
2160 * when needed.
2161 */
2162
2163 if (
2164 !(cxt->optype & ST_CLONE) && (cxt->canonical == 1 ||
2165 (cxt->canonical < 0 && (cxt->canonical =
e16e2ff8 2166 (SvTRUE(perl_get_sv("Storable::canonical", TRUE)) ? 1 : 0))))
7a6a85bf
RG
2167 ) {
2168 /*
2169 * Storing in order, sorted by key.
2170 * Run through the hash, building up an array of keys in a
2171 * mortal array, sort the array and then run through the
2172 * array.
2173 */
2174
2175 AV *av = newAV();
2176
e16e2ff8
NC
2177 /*av_extend (av, len);*/
2178
7a6a85bf
RG
2179 TRACEME(("using canonical order"));
2180
2181 for (i = 0; i < len; i++) {
530b72ba 2182#ifdef HAS_RESTRICTED_HASHES
e16e2ff8 2183 HE *he = hv_iternext_flags(hv, HV_ITERNEXT_WANTPLACEHOLDERS);
530b72ba
NC
2184#else
2185 HE *he = hv_iternext(hv);
2186#endif
7a6a85bf
RG
2187 SV *key = hv_iterkeysv(he);
2188 av_store(av, AvFILLp(av)+1, key); /* av_push(), really */
2189 }
2190
2191 qsort((char *) AvARRAY(av), len, sizeof(SV *), sortcmp);
2192
2193 for (i = 0; i < len; i++) {
dfd91409
NC
2194#ifdef HAS_RESTRICTED_HASHES
2195 int placeholders = HvPLACEHOLDERS(hv);
2196#endif
2197 unsigned char flags = 0;
7a6a85bf 2198 char *keyval;
e16e2ff8
NC
2199 STRLEN keylen_tmp;
2200 I32 keylen;
7a6a85bf 2201 SV *key = av_shift(av);
dfd91409
NC
2202 /* This will fail if key is a placeholder.
2203 Track how many placeholders we have, and error if we
2204 "see" too many. */
7a6a85bf 2205 HE *he = hv_fetch_ent(hv, key, 0, 0);
dfd91409
NC
2206 SV *val;
2207
2208 if (he) {
2209 if (!(val = HeVAL(he))) {
2210 /* Internal error, not I/O error */
2211 return 1;
2212 }
2213 } else {
2214#ifdef HAS_RESTRICTED_HASHES
2215 /* Should be a placeholder. */
2216 if (placeholders-- < 0) {
2217 /* This should not happen - number of
2218 retrieves should be identical to
2219 number of placeholders. */
2220 return 1;
2221 }
2222 /* Value is never needed, and PL_sv_undef is
2223 more space efficient to store. */
2224 val = &PL_sv_undef;
2225 ASSERT (flags == 0,
2226 ("Flags not 0 but %d", flags));
2227 flags = SHV_K_PLACEHOLDER;
2228#else
2229 return 1;
2230#endif
2231 }
7a6a85bf
RG
2232
2233 /*
2234 * Store value first.
2235 */
2236
9e21b3d0 2237 TRACEME(("(#%d) value 0x%"UVxf, i, PTR2UV(val)));
7a6a85bf 2238
e993d95c 2239 if ((ret = store(cxt, val))) /* Extra () for -Wall, grr... */
7a6a85bf
RG
2240 goto out;
2241
2242 /*
2243 * Write key string.
2244 * Keys are written after values to make sure retrieval
2245 * can be optimal in terms of memory usage, where keys are
2246 * read into a fixed unique buffer called kbuf.
2247 * See retrieve_hash() for details.
2248 */
2249
e16e2ff8
NC
2250 /* Implementation of restricted hashes isn't nicely
2251 abstracted: */
dfd91409
NC
2252 if ((hash_flags & SHV_RESTRICTED) && SvREADONLY(val)) {
2253 flags |= SHV_K_LOCKED;
2254 }
e16e2ff8
NC
2255
2256 keyval = SvPV(key, keylen_tmp);
2257 keylen = keylen_tmp;
530b72ba
NC
2258#ifdef HAS_UTF8_HASHES
2259 /* If you build without optimisation on pre 5.6
2260 then nothing spots that SvUTF8(key) is always 0,
2261 so the block isn't optimised away, at which point
2262 the linker dislikes the reference to
2263 bytes_from_utf8. */
e16e2ff8
NC
2264 if (SvUTF8(key)) {
2265 const char *keysave = keyval;
2266 bool is_utf8 = TRUE;
2267
2268 /* Just casting the &klen to (STRLEN) won't work
2269 well if STRLEN and I32 are of different widths.
2270 --jhi */
2271 keyval = (char*)bytes_from_utf8((U8*)keyval,
2272 &keylen_tmp,
2273 &is_utf8);
2274
2275 /* If we were able to downgrade here, then than
2276 means that we have a key which only had chars
2277 0-255, but was utf8 encoded. */
2278
2279 if (keyval != keysave) {
2280 keylen = keylen_tmp;
2281 flags |= SHV_K_WASUTF8;
2282 } else {
2283 /* keylen_tmp can't have changed, so no need
2284 to assign back to keylen. */
2285 flags |= SHV_K_UTF8;
2286 }
2287 }
530b72ba 2288#endif
e16e2ff8
NC
2289
2290 if (flagged_hash) {
2291 PUTMARK(flags);
2292 TRACEME(("(#%d) key '%s' flags %x %u", i, keyval, flags, *keyval));
2293 } else {
fcaa57e7
AMS
2294 /* This is a workaround for a bug in 5.8.0
2295 that causes the HEK_WASUTF8 flag to be
2296 set on an HEK without the hash being
2297 marked as having key flags. We just
2298 cross our fingers and drop the flag.
2299 AMS 20030901 */
2300 assert (flags == 0 || flags == SHV_K_WASUTF8);
e16e2ff8
NC
2301 TRACEME(("(#%d) key '%s'", i, keyval));
2302 }
7a6a85bf
RG
2303 WLEN(keylen);
2304 if (keylen)
2305 WRITE(keyval, keylen);
e16e2ff8
NC
2306 if (flags & SHV_K_WASUTF8)
2307 Safefree (keyval);
7a6a85bf
RG
2308 }
2309
2310 /*
2311 * Free up the temporary array
2312 */
2313
2314 av_undef(av);
2315 sv_free((SV *) av);
2316
2317 } else {
2318
2319 /*
2320 * Storing in "random" order (in the order the keys are stored
a6d05634 2321 * within the hash). This is the default and will be faster!
7a6a85bf
RG
2322 */
2323
2324 for (i = 0; i < len; i++) {
2325 char *key;
2326 I32 len;
e16e2ff8 2327 unsigned char flags;
530b72ba 2328#ifdef HV_ITERNEXT_WANTPLACEHOLDERS
e16e2ff8 2329 HE *he = hv_iternext_flags(hv, HV_ITERNEXT_WANTPLACEHOLDERS);
530b72ba
NC
2330#else
2331 HE *he = hv_iternext(hv);
2332#endif
e16e2ff8
NC
2333 SV *val = (he ? hv_iterval(hv, he) : 0);
2334 SV *key_sv = NULL;
2335 HEK *hek;
7a6a85bf
RG
2336
2337 if (val == 0)
2338 return 1; /* Internal error, not I/O error */
2339
dfd91409
NC
2340 /* Implementation of restricted hashes isn't nicely
2341 abstracted: */
2342 flags
2343 = (((hash_flags & SHV_RESTRICTED)
2344 && SvREADONLY(val))
2345 ? SHV_K_LOCKED : 0);
2346
2347 if (val == &PL_sv_placeholder) {
2348 flags |= SHV_K_PLACEHOLDER;
2349 val = &PL_sv_undef;
2350 }
2351
7a6a85bf
RG
2352 /*
2353 * Store value first.
2354 */
2355
9e21b3d0 2356 TRACEME(("(#%d) value 0x%"UVxf, i, PTR2UV(val)));
7a6a85bf 2357
e993d95c 2358 if ((ret = store(cxt, val))) /* Extra () for -Wall, grr... */
7a6a85bf
RG
2359 goto out;
2360
e16e2ff8
NC
2361
2362 hek = HeKEY_hek(he);
2363 len = HEK_LEN(hek);
2364 if (len == HEf_SVKEY) {
2365 /* This is somewhat sick, but the internal APIs are
2366 * such that XS code could put one of these in in
2367 * a regular hash.
2368 * Maybe we should be capable of storing one if
2369 * found.
2370 */
2371 key_sv = HeKEY_sv(he);
2372 flags |= SHV_K_ISSV;
2373 } else {
2374 /* Regular string key. */
530b72ba 2375#ifdef HAS_HASH_KEY_FLAGS
e16e2ff8
NC
2376 if (HEK_UTF8(hek))
2377 flags |= SHV_K_UTF8;
2378 if (HEK_WASUTF8(hek))
2379 flags |= SHV_K_WASUTF8;
530b72ba 2380#endif
e16e2ff8
NC
2381 key = HEK_KEY(hek);
2382 }
7a6a85bf
RG
2383 /*
2384 * Write key string.
2385 * Keys are written after values to make sure retrieval
2386 * can be optimal in terms of memory usage, where keys are
2387 * read into a fixed unique buffer called kbuf.
2388 * See retrieve_hash() for details.
2389 */
2390
e16e2ff8
NC
2391 if (flagged_hash) {
2392 PUTMARK(flags);
2393 TRACEME(("(#%d) key '%s' flags %x", i, key, flags));
2394 } else {
fcaa57e7
AMS
2395 /* This is a workaround for a bug in 5.8.0
2396 that causes the HEK_WASUTF8 flag to be
2397 set on an HEK without the hash being
2398 marked as having key flags. We just
2399 cross our fingers and drop the flag.
2400 AMS 20030901 */
2401 assert (flags == 0 || flags == SHV_K_WASUTF8);
e16e2ff8
NC
2402 TRACEME(("(#%d) key '%s'", i, key));
2403 }
2404 if (flags & SHV_K_ISSV) {
2405 store(cxt, key_sv);
2406 } else {
2407 WLEN(len);
2408 if (len)
7a6a85bf 2409 WRITE(key, len);
e16e2ff8 2410 }
7a6a85bf
RG
2411 }
2412 }
2413
43d061fe 2414 TRACEME(("ok (hash 0x%"UVxf")", PTR2UV(hv)));
7a6a85bf
RG
2415
2416out:
2417 HvRITER(hv) = riter; /* Restore hash iterator state */
2418 HvEITER(hv) = eiter;
2419
2420 return ret;
2421}
2422
2423/*
464b080a
SR
2424 * store_code
2425 *
2426 * Store a code reference.
2427 *
2428 * Layout is SX_CODE <length> followed by a scalar containing the perl
2429 * source code of the code reference.
2430 */
2431static int store_code(stcxt_t *cxt, CV *cv)
2432{
2433#if PERL_VERSION < 6
2434 /*
2435 * retrieve_code does not work with perl 5.005 or less
2436 */
2437 return store_other(cxt, (SV*)cv);
2438#else
2439 dSP;
2440 I32 len;
c5661c80 2441 int count, reallen;
464b080a
SR
2442 SV *text, *bdeparse;
2443
2444 TRACEME(("store_code (0x%"UVxf")", PTR2UV(cv)));
2445
2446 if (
2447 cxt->deparse == 0 ||
2448 (cxt->deparse < 0 && !(cxt->deparse =
2449 SvTRUE(perl_get_sv("Storable::Deparse", TRUE)) ? 1 : 0))
2450 ) {
2451 return store_other(cxt, (SV*)cv);
2452 }
2453
2454 /*
2455 * Require B::Deparse. At least B::Deparse 0.61 is needed for
2456 * blessed code references.
2457 */
17625bd2 2458 /* Ownership of both SVs is passed to load_module, which frees them. */
464b080a
SR
2459 load_module(PERL_LOADMOD_NOIMPORT, newSVpvn("B::Deparse",10), newSVnv(0.61));
2460
2461 ENTER;
2462 SAVETMPS;
2463
2464 /*
2465 * create the B::Deparse object
2466 */
2467
2468 PUSHMARK(sp);
2469 XPUSHs(sv_2mortal(newSVpvn("B::Deparse",10)));
2470 PUTBACK;
2471 count = call_method("new", G_SCALAR);
2472 SPAGAIN;
2473 if (count != 1)
2474 CROAK(("Unexpected return value from B::Deparse::new\n"));
2475 bdeparse = POPs;
2476
2477 /*
2478 * call the coderef2text method
2479 */
2480
2481 PUSHMARK(sp);
2482 XPUSHs(bdeparse); /* XXX is this already mortal? */
2483 XPUSHs(sv_2mortal(newRV_inc((SV*)cv)));
2484 PUTBACK;
2485 count = call_method("coderef2text", G_SCALAR);
2486 SPAGAIN;
2487 if (count != 1)
2488 CROAK(("Unexpected return value from B::Deparse::coderef2text\n"));
2489
2490 text = POPs;
2491 len = SvLEN(text);
e3feee4e 2492 reallen = strlen(SvPV_nolen(text));
464b080a
SR
2493
2494 /*
2495 * Empty code references or XS functions are deparsed as
2496 * "(prototype) ;" or ";".
2497 */
2498
e3feee4e 2499 if (len == 0 || *(SvPV_nolen(text)+reallen-1) == ';') {
464b080a
SR
2500 CROAK(("The result of B::Deparse::coderef2text was empty - maybe you're trying to serialize an XS function?\n"));
2501 }
2502
2503 /*
2504 * Signal code by emitting SX_CODE.
2505 */
2506
2507 PUTMARK(SX_CODE);
a8b7ef86 2508 cxt->tagnum++; /* necessary, as SX_CODE is a SEEN() candidate */
464b080a 2509 TRACEME(("size = %d", len));
e3feee4e 2510 TRACEME(("code = %s", SvPV_nolen(text)));
464b080a
SR
2511
2512 /*
2513 * Now store the source code.
2514 */
2515
e3feee4e 2516 STORE_SCALAR(SvPV_nolen(text), len);
464b080a
SR
2517
2518 FREETMPS;
2519 LEAVE;
2520
2521 TRACEME(("ok (code)"));
2522
2523 return 0;
2524#endif
2525}
2526
2527/*
7a6a85bf
RG
2528 * store_tied
2529 *
2530 * When storing a tied object (be it a tied scalar, array or hash), we lay out
2531 * a special mark, followed by the underlying tied object. For instance, when
2532 * dealing with a tied hash, we store SX_TIED_HASH <hash object>, where
2533 * <hash object> stands for the serialization of the tied hash.
2534 */
f0ffaed8 2535static int store_tied(stcxt_t *cxt, SV *sv)
7a6a85bf
RG
2536{
2537 MAGIC *mg;
72edffd8 2538 SV *obj = NULL;
7a6a85bf
RG
2539 int ret = 0;
2540 int svt = SvTYPE(sv);
2541 char mtype = 'P';
2542
43d061fe 2543 TRACEME(("store_tied (0x%"UVxf")", PTR2UV(sv)));
7a6a85bf
RG
2544
2545 /*
2546 * We have a small run-time penalty here because we chose to factorise
2547 * all tieds objects into the same routine, and not have a store_tied_hash,
2548 * a store_tied_array, etc...
2549 *
2550 * Don't use a switch() statement, as most compilers don't optimize that
2551 * well for 2/3 values. An if() else if() cascade is just fine. We put
2552 * tied hashes first, as they are the most likely beasts.
2553 */
2554
2555 if (svt == SVt_PVHV) {
2556 TRACEME(("tied hash"));
2557 PUTMARK(SX_TIED_HASH); /* Introduces tied hash */
2558 } else if (svt == SVt_PVAV) {
2559 TRACEME(("tied array"));
2560 PUTMARK(SX_TIED_ARRAY); /* Introduces tied array */
2561 } else {
2562 TRACEME(("tied scalar"));
2563 PUTMARK(SX_TIED_SCALAR); /* Introduces tied scalar */
2564 mtype = 'q';
2565 }
2566
2567 if (!(mg = mg_find(sv, mtype)))
2568 CROAK(("No magic '%c' found while storing tied %s", mtype,
2569 (svt == SVt_PVHV) ? "hash" :
2570 (svt == SVt_PVAV) ? "array" : "scalar"));
2571
2572 /*
2573 * The mg->mg_obj found by mg_find() above actually points to the
2574 * underlying tied Perl object implementation. For instance, if the
2575 * original SV was that of a tied array, then mg->mg_obj is an AV.
2576 *
2577 * Note that we store the Perl object as-is. We don't call its FETCH
2578 * method along the way. At retrieval time, we won't call its STORE
2579 * method either, but the tieing magic will be re-installed. In itself,
2580 * that ensures that the tieing semantics are preserved since futher
2581 * accesses on the retrieved object will indeed call the magic methods...
2582 */
2583
72edffd8
AMS
2584 /* [#17040] mg_obj is NULL for scalar self-ties. AMS 20030416 */
2585 obj = mg->mg_obj ? mg->mg_obj : newSV(0);
2586 if ((ret = store(cxt, obj)))
7a6a85bf
RG
2587 return ret;
2588
2589 TRACEME(("ok (tied)"));
2590
2591 return 0;
2592}
2593
2594/*
2595 * store_tied_item
2596 *
2597 * Stores a reference to an item within a tied structure:
2598 *
2599 * . \$h{key}, stores both the (tied %h) object and 'key'.
2600 * . \$a[idx], stores both the (tied @a) object and 'idx'.
2601 *
2602 * Layout is therefore either:
2603 * SX_TIED_KEY <object> <key>
2604 * SX_TIED_IDX <object> <index>
2605 */
f0ffaed8 2606static int store_tied_item(stcxt_t *cxt, SV *sv)
7a6a85bf
RG
2607{
2608 MAGIC *mg;
2609 int ret;
2610
43d061fe 2611 TRACEME(("store_tied_item (0x%"UVxf")", PTR2UV(sv)));
7a6a85bf
RG
2612
2613 if (!(mg = mg_find(sv, 'p')))
2614 CROAK(("No magic 'p' found while storing reference to tied item"));
2615
2616 /*
2617 * We discriminate between \$h{key} and \$a[idx] via mg_ptr.
2618 */
2619
2620 if (mg->mg_ptr) {
2621 TRACEME(("store_tied_item: storing a ref to a tied hash item"));
2622 PUTMARK(SX_TIED_KEY);
9e21b3d0 2623 TRACEME(("store_tied_item: storing OBJ 0x%"UVxf, PTR2UV(mg->mg_obj)));
7a6a85bf 2624
e993d95c 2625 if ((ret = store(cxt, mg->mg_obj))) /* Extra () for -Wall, grr... */
7a6a85bf
RG
2626 return ret;
2627
9e21b3d0 2628 TRACEME(("store_tied_item: storing PTR 0x%"UVxf, PTR2UV(mg->mg_ptr)));
7a6a85bf 2629
e993d95c 2630 if ((ret = store(cxt, (SV *) mg->mg_ptr))) /* Idem, for -Wall */
7a6a85bf
RG
2631 return ret;
2632 } else {
2633 I32 idx = mg->mg_len;
2634
2635 TRACEME(("store_tied_item: storing a ref to a tied array item "));
2636 PUTMARK(SX_TIED_IDX);
9e21b3d0 2637 TRACEME(("store_tied_item: storing OBJ 0x%"UVxf, PTR2UV(mg->mg_obj)));
7a6a85bf 2638
e993d95c 2639 if ((ret = store(cxt, mg->mg_obj))) /* Idem, for -Wall */
7a6a85bf
RG
2640 return ret;
2641
2642 TRACEME(("store_tied_item: storing IDX %d", idx));
2643
2644 WLEN(idx);
2645 }
2646
2647 TRACEME(("ok (tied item)"));
2648
2649 return 0;
2650}
2651
2652/*
2653 * store_hook -- dispatched manually, not via sv_store[]
2654 *
2655 * The blessed SV is serialized by a hook.
2656 *
2657 * Simple Layout is:
2658 *
2659 * SX_HOOK <flags> <len> <classname> <len2> <str> [<len3> <object-IDs>]
2660 *
2661 * where <flags> indicates how long <len>, <len2> and <len3> are, whether
2662 * the trailing part [] is present, the type of object (scalar, array or hash).
2663 * There is also a bit which says how the classname is stored between:
2664 *
2665 * <len> <classname>
2666 * <index>
2667 *
2668 * and when the <index> form is used (classname already seen), the "large
2669 * classname" bit in <flags> indicates how large the <index> is.
2670 *
2671 * The serialized string returned by the hook is of length <len2> and comes
2672 * next. It is an opaque string for us.
2673 *
2674 * Those <len3> object IDs which are listed last represent the extra references
2675 * not directly serialized by the hook, but which are linked to the object.
2676 *
2677 * When recursion is mandated to resolve object-IDs not yet seen, we have
2678 * instead, with <header> being flags with bits set to indicate the object type
2679 * and that recursion was indeed needed:
2680 *
2681 * SX_HOOK <header> <object> <header> <object> <flags>
2682 *
2683 * that same header being repeated between serialized objects obtained through
2684 * recursion, until we reach flags indicating no recursion, at which point
2685 * we know we've resynchronized with a single layout, after <flags>.
b12202d0
JH
2686 *
2687 * When storing a blessed ref to a tied variable, the following format is
2688 * used:
2689 *
2690 * SX_HOOK <flags> <extra> ... [<len3> <object-IDs>] <magic object>
2691 *
2692 * The first <flags> indication carries an object of type SHT_EXTRA, and the
2693 * real object type is held in the <extra> flag. At the very end of the
2694 * serialization stream, the underlying magic object is serialized, just like
2695 * any other tied variable.
7a6a85bf 2696 */
f0ffaed8
JH
2697static int store_hook(
2698 stcxt_t *cxt,
2699 SV *sv,
2700 int type,
2701 HV *pkg,
2702 SV *hook)
7a6a85bf
RG
2703{
2704 I32 len;
2705 char *class;
2706 STRLEN len2;
2707 SV *ref;
2708 AV *av;
2709 SV **ary;
2710 int count; /* really len3 + 1 */
2711 unsigned char flags;
2712 char *pv;
2713 int i;
2714 int recursed = 0; /* counts recursion */
2715 int obj_type; /* object type, on 2 bits */
2716 I32 classnum;
2717 int ret;
2718 int clone = cxt->optype & ST_CLONE;
e993d95c
JH
2719 char mtype = '\0'; /* for blessed ref to tied structures */
2720 unsigned char eflags = '\0'; /* used when object type is SHT_EXTRA */
7a6a85bf
RG
2721
2722 TRACEME(("store_hook, class \"%s\", tagged #%d", HvNAME(pkg), cxt->tagnum));
2723
2724 /*
2725 * Determine object type on 2 bits.
2726 */
2727
2728 switch (type) {
2729 case svis_SCALAR:
2730 obj_type = SHT_SCALAR;
2731 break;
2732 case svis_ARRAY:
2733 obj_type = SHT_ARRAY;
2734 break;
2735 case svis_HASH:
2736 obj_type = SHT_HASH;
2737 break;
b12202d0
JH
2738 case svis_TIED:
2739 /*
2740 * Produced by a blessed ref to a tied data structure, $o in the
2741 * following Perl code.
2742 *
2743 * my %h;
2744 * tie %h, 'FOO';
2745 * my $o = bless \%h, 'BAR';
2746 *
2747 * Signal the tie-ing magic by setting the object type as SHT_EXTRA
2748 * (since we have only 2 bits in <flags> to store the type), and an
2749 * <extra> byte flag will be emitted after the FIRST <flags> in the
2750 * stream, carrying what we put in `eflags'.
2751 */
2752 obj_type = SHT_EXTRA;
2753 switch (SvTYPE(sv)) {
2754 case SVt_PVHV:
2755 eflags = (unsigned char) SHT_THASH;
2756 mtype = 'P';
2757 break;
2758 case SVt_PVAV:
2759 eflags = (unsigned char) SHT_TARRAY;
2760 mtype = 'P';
2761 break;
2762 default:
2763 eflags = (unsigned char) SHT_TSCALAR;
2764 mtype = 'q';
2765 break;
2766 }
2767 break;
7a6a85bf
RG
2768 default:
2769 CROAK(("Unexpected object type (%d) in store_hook()", type));
2770 }
2771 flags = SHF_NEED_RECURSE | obj_type;
2772
2773 class = HvNAME(pkg);
2774 len = strlen(class);
2775
2776 /*
2777 * To call the hook, we need to fake a call like:
2778 *
2779 * $object->STORABLE_freeze($cloning);
2780 *
2781 * but we don't have the $object here. For instance, if $object is
2782 * a blessed array, what we have in `sv' is the array, and we can't
2783 * call a method on those.
2784 *
2785 * Therefore, we need to create a temporary reference to the object and
2786 * make the call on that reference.
2787 */
2788
2789 TRACEME(("about to call STORABLE_freeze on class %s", class));
2790
2791 ref = newRV_noinc(sv); /* Temporary reference */
2792 av = array_call(ref, hook, clone); /* @a = $object->STORABLE_freeze($c) */
2793 SvRV(ref) = 0;
2794 SvREFCNT_dec(ref); /* Reclaim temporary reference */
2795
2796 count = AvFILLp(av) + 1;
2797 TRACEME(("store_hook, array holds %d items", count));
2798
2799 /*
2800 * If they return an empty list, it means they wish to ignore the
2801 * hook for this class (and not just this instance -- that's for them
2802 * to handle if they so wish).
2803 *
2804 * Simply disable the cached entry for the hook (it won't be recomputed
2805 * since it's present in the cache) and recurse to store_blessed().
2806 */
2807
2808 if (!count) {
2809 /*
2810 * They must not change their mind in the middle of a serialization.
2811 */
2812
2813 if (hv_fetch(cxt->hclass, class, len, FALSE))
2814 CROAK(("Too late to ignore hooks for %s class \"%s\"",
2815 (cxt->optype & ST_CLONE) ? "cloning" : "storing", class));
2816
2817 pkg_hide(cxt->hook, pkg, "STORABLE_freeze");
2818
2819 ASSERT(!pkg_can(cxt->hook, pkg, "STORABLE_freeze"), ("hook invisible"));
cc964657 2820 TRACEME(("ignoring STORABLE_freeze in class \"%s\"", class));
7a6a85bf
RG
2821
2822 return store_blessed(cxt, sv, type, pkg);
2823 }
2824
2825 /*
2826 * Get frozen string.
2827 */
2828
2829 ary = AvARRAY(av);
2830 pv = SvPV(ary[0], len2);
2831
2832 /*
7a6a85bf
RG
2833 * If they returned more than one item, we need to serialize some
2834 * extra references if not already done.
2835 *
10ffa93f 2836 * Loop over the array, starting at position #1, and for each item,
7a6a85bf
RG
2837 * ensure it is a reference, serialize it if not already done, and
2838 * replace the entry with the tag ID of the corresponding serialized
2839 * object.
2840 *
2841 * We CHEAT by not calling av_fetch() and read directly within the
2842 * array, for speed.
2843 */
2844
2845 for (i = 1; i < count; i++) {
2846 SV **svh;
90826881
JH
2847 SV *rsv = ary[i];
2848 SV *xsv;
2849 AV *av_hook = cxt->hook_seen;
7a6a85bf 2850
90826881
JH
2851 if (!SvROK(rsv))
2852 CROAK(("Item #%d returned by STORABLE_freeze "
2853 "for %s is not a reference", i, class));
2854 xsv = SvRV(rsv); /* Follow ref to know what to look for */
7a6a85bf
RG
2855
2856 /*
2857 * Look in hseen and see if we have a tag already.
2858 * Serialize entry if not done already, and get its tag.
2859 */
2860
13689cfe 2861 if ((svh = hv_fetch(cxt->hseen, (char *) &xsv, sizeof(xsv), FALSE)))
7a6a85bf
RG
2862 goto sv_seen; /* Avoid moving code too far to the right */
2863
9e21b3d0 2864 TRACEME(("listed object %d at 0x%"UVxf" is unknown", i-1, PTR2UV(xsv)));
7a6a85bf
RG
2865
2866 /*
2867 * We need to recurse to store that object and get it to be known
2868 * so that we can resolve the list of object-IDs at retrieve time.
2869 *
2870 * The first time we do this, we need to emit the proper header
2871 * indicating that we recursed, and what the type of object is (the
2872 * object we're storing via a user-hook). Indeed, during retrieval,
2873 * we'll have to create the object before recursing to retrieve the
2874 * others, in case those would point back at that object.
2875 */
2876
b12202d0
JH
2877 /* [SX_HOOK] <flags> [<extra>] <object>*/
2878 if (!recursed++) {
7a6a85bf 2879 PUTMARK(SX_HOOK);
b12202d0
JH
2880 PUTMARK(flags);
2881 if (obj_type == SHT_EXTRA)
2882 PUTMARK(eflags);
2883 } else
2884 PUTMARK(flags);
7a6a85bf 2885
e993d95c 2886 if ((ret = store(cxt, xsv))) /* Given by hook for us to store */
7a6a85bf
RG
2887 return ret;
2888
2889 svh = hv_fetch(cxt->hseen, (char *) &xsv, sizeof(xsv), FALSE);
2890 if (!svh)
2891 CROAK(("Could not serialize item #%d from hook in %s", i, class));
2892
2893 /*
90826881
JH
2894 * It was the first time we serialized `xsv'.
2895 *
2896 * Keep this SV alive until the end of the serialization: if we
2897 * disposed of it right now by decrementing its refcount, and it was
2898 * a temporary value, some next temporary value allocated during
2899 * another STORABLE_freeze might take its place, and we'd wrongly
2900 * assume that new SV was already serialized, based on its presence
2901 * in cxt->hseen.
2902 *
2903 * Therefore, push it away in cxt->hook_seen.
7a6a85bf
RG
2904 */
2905
90826881
JH
2906 av_store(av_hook, AvFILLp(av_hook)+1, SvREFCNT_inc(xsv));
2907
7a6a85bf 2908 sv_seen:
90826881
JH
2909 /*
2910 * Dispose of the REF they returned. If we saved the `xsv' away
2911 * in the array of returned SVs, that will not cause the underlying
2912 * referenced SV to be reclaimed.
2913 */
2914
2915 ASSERT(SvREFCNT(xsv) > 1, ("SV will survive disposal of its REF"));
2916 SvREFCNT_dec(rsv); /* Dispose of reference */
2917
2918 /*
2919 * Replace entry with its tag (not a real SV, so no refcnt increment)
2920 */
2921
7a6a85bf 2922 ary[i] = *svh;
76edffbb 2923 TRACEME(("listed object %d at 0x%"UVxf" is tag #%"UVuf,
d67b2c17 2924 i-1, PTR2UV(xsv), PTR2UV(*svh)));
7a6a85bf
RG
2925 }
2926
2927 /*
dd19458b
JH
2928 * Allocate a class ID if not already done.
2929 *
2930 * This needs to be done after the recursion above, since at retrieval
2931 * time, we'll see the inner objects first. Many thanks to
2932 * Salvador Ortiz Garcia <sog@msg.com.mx> who spot that bug and
2933 * proposed the right fix. -- RAM, 15/09/2000
2934 */
2935
2936 if (!known_class(cxt, class, len, &classnum)) {
2937 TRACEME(("first time we see class %s, ID = %d", class, classnum));
2938 classnum = -1; /* Mark: we must store classname */
2939 } else {
2940 TRACEME(("already seen class %s, ID = %d", class, classnum));
2941 }
2942
2943 /*
7a6a85bf
RG
2944 * Compute leading flags.
2945 */
2946
2947 flags = obj_type;
2948 if (((classnum == -1) ? len : classnum) > LG_SCALAR)
2949 flags |= SHF_LARGE_CLASSLEN;
2950 if (classnum != -1)
2951 flags |= SHF_IDX_CLASSNAME;
2952 if (len2 > LG_SCALAR)
2953 flags |= SHF_LARGE_STRLEN;
2954 if (count > 1)
2955 flags |= SHF_HAS_LIST;
2956 if (count > (LG_SCALAR + 1))
2957 flags |= SHF_LARGE_LISTLEN;
2958
2959 /*
2960 * We're ready to emit either serialized form:
2961 *
2962 * SX_HOOK <flags> <len> <classname> <len2> <str> [<len3> <object-IDs>]
2963 * SX_HOOK <flags> <index> <len2> <str> [<len3> <object-IDs>]
2964 *
2965 * If we recursed, the SX_HOOK has already been emitted.
2966 */
2967
9e21b3d0
JH
2968 TRACEME(("SX_HOOK (recursed=%d) flags=0x%x "
2969 "class=%"IVdf" len=%"IVdf" len2=%"IVdf" len3=%d",
d67b2c17 2970 recursed, flags, (IV)classnum, (IV)len, (IV)len2, count-1));
7a6a85bf 2971
b12202d0
JH
2972 /* SX_HOOK <flags> [<extra>] */
2973 if (!recursed) {
7a6a85bf 2974 PUTMARK(SX_HOOK);
b12202d0
JH
2975 PUTMARK(flags);
2976 if (obj_type == SHT_EXTRA)
2977 PUTMARK(eflags);
2978 } else
2979 PUTMARK(flags);
7a6a85bf
RG
2980
2981 /* <len> <classname> or <index> */
2982 if (flags & SHF_IDX_CLASSNAME) {
2983 if (flags & SHF_LARGE_CLASSLEN)
2984 WLEN(classnum);
2985 else {
2986 unsigned char cnum = (unsigned char) classnum;
2987 PUTMARK(cnum);
2988 }
2989 } else {
2990 if (flags & SHF_LARGE_CLASSLEN)
2991 WLEN(len);
2992 else {
2993 unsigned char clen = (unsigned char) len;
2994 PUTMARK(clen);
2995 }
2996 WRITE(class, len); /* Final \0 is omitted */
2997 }
2998
2999 /* <len2> <frozen-str> */
cc964657
JH
3000 if (flags & SHF_LARGE_STRLEN) {
3001 I32 wlen2 = len2; /* STRLEN might be 8 bytes */
3002 WLEN(wlen2); /* Must write an I32 for 64-bit machines */
3003 } else {
7a6a85bf
RG
3004 unsigned char clen = (unsigned char) len2;
3005 PUTMARK(clen);
3006 }
3007 if (len2)
7c436af3 3008 WRITE(pv, (SSize_t)len2); /* Final \0 is omitted */
7a6a85bf
RG
3009
3010 /* [<len3> <object-IDs>] */
3011 if (flags & SHF_HAS_LIST) {
3012 int len3 = count - 1;
3013 if (flags & SHF_LARGE_LISTLEN)
3014 WLEN(len3);
3015 else {
3016 unsigned char clen = (unsigned char) len3;
3017 PUTMARK(clen);
3018 }
3019
3020 /*
3021 * NOTA BENE, for 64-bit machines: the ary[i] below does not yield a
3022 * real pointer, rather a tag number, well under the 32-bit limit.
3023 */
3024
3025 for (i = 1; i < count; i++) {
3026 I32 tagval = htonl(LOW_32BITS(ary[i]));
9e21b3d0 3027 WRITE_I32(tagval);
7a6a85bf
RG
3028 TRACEME(("object %d, tag #%d", i-1, ntohl(tagval)));
3029 }
3030 }
3031
3032 /*
3033 * Free the array. We need extra care for indices after 0, since they
3034 * don't hold real SVs but integers cast.
3035 */
3036
3037 if (count > 1)
3038 AvFILLp(av) = 0; /* Cheat, nothing after 0 interests us */
3039 av_undef(av);
3040 sv_free((SV *) av);
3041
b12202d0
JH
3042 /*
3043 * If object was tied, need to insert serialization of the magic object.
3044 */
3045
3046 if (obj_type == SHT_EXTRA) {
3047 MAGIC *mg;
3048
3049 if (!(mg = mg_find(sv, mtype))) {
3050 int svt = SvTYPE(sv);
3051 CROAK(("No magic '%c' found while storing ref to tied %s with hook",
3052 mtype, (svt == SVt_PVHV) ? "hash" :
3053 (svt == SVt_PVAV) ? "array" : "scalar"));
3054 }
3055
3056 TRACEME(("handling the magic object 0x%"UVxf" part of 0x%"UVxf,
3057 PTR2UV(mg->mg_obj), PTR2UV(sv)));
3058
3059 /*
3060 * [<magic object>]
3061 */
3062
e993d95c 3063 if ((ret = store(cxt, mg->mg_obj))) /* Extra () for -Wall, grr... */
b12202d0
JH
3064 return ret;
3065 }
3066
7a6a85bf
RG
3067 return 0;
3068}
3069
3070/*
3071 * store_blessed -- dispatched manually, not via sv_store[]
3072 *
3073 * Check whether there is a STORABLE_xxx hook defined in the class or in one
3074 * of its ancestors. If there is, then redispatch to store_hook();
3075 *
3076 * Otherwise, the blessed SV is stored using the following layout:
3077 *
3078 * SX_BLESS <flag> <len> <classname> <object>
3079 *
3080 * where <flag> indicates whether <len> is stored on 0 or 4 bytes, depending
3081 * on the high-order bit in flag: if 1, then length follows on 4 bytes.
3082 * Otherwise, the low order bits give the length, thereby giving a compact
3083 * representation for class names less than 127 chars long.
3084 *
3085 * Each <classname> seen is remembered and indexed, so that the next time
3086 * an object in the blessed in the same <classname> is stored, the following
3087 * will be emitted:
3088 *
3089 * SX_IX_BLESS <flag> <index> <object>
3090 *
3091 * where <index> is the classname index, stored on 0 or 4 bytes depending
3092 * on the high-order bit in flag (same encoding as above for <len>).
3093 */
f0ffaed8
JH
3094static int store_blessed(
3095 stcxt_t *cxt,
3096 SV *sv,
3097 int type,
3098 HV *pkg)
7a6a85bf
RG
3099{
3100 SV *hook;
3101 I32 len;
3102 char *class;
3103 I32 classnum;
3104
3105 TRACEME(("store_blessed, type %d, class \"%s\"", type, HvNAME(pkg)));
3106
3107 /*
3108 * Look for a hook for this blessed SV and redirect to store_hook()
3109 * if needed.
3110 */
3111
3112 hook = pkg_can(cxt->hook, pkg, "STORABLE_freeze");
3113 if (hook)
3114 return store_hook(cxt, sv, type, pkg, hook);
3115
3116 /*
3117 * This is a blessed SV without any serialization hook.
3118 */
3119
3120 class = HvNAME(pkg);
3121 len = strlen(class);
3122
43d061fe
JH
3123 TRACEME(("blessed 0x%"UVxf" in %s, no hook: tagged #%d",
3124 PTR2UV(sv), class, cxt->tagnum));
7a6a85bf
RG
3125
3126 /*
3127 * Determine whether it is the first time we see that class name (in which
3128 * case it will be stored in the SX_BLESS form), or whether we already
3129 * saw that class name before (in which case the SX_IX_BLESS form will be
3130 * used).
3131 */
3132
3133 if (known_class(cxt, class, len, &classnum)) {
3134 TRACEME(("already seen class %s, ID = %d", class, classnum));
3135 PUTMARK(SX_IX_BLESS);
3136 if (classnum <= LG_BLESS) {
3137 unsigned char cnum = (unsigned char) classnum;
3138 PUTMARK(cnum);
3139 } else {
3140 unsigned char flag = (unsigned char) 0x80;
3141 PUTMARK(flag);
3142 WLEN(classnum);
3143 }
3144 } else {
3145 TRACEME(("first time we see class %s, ID = %d", class, classnum));
3146 PUTMARK(SX_BLESS);
3147 if (len <= LG_BLESS) {
3148 unsigned char clen = (unsigned char) len;
3149 PUTMARK(clen);
3150 } else {
3151 unsigned char flag = (unsigned char) 0x80;
3152 PUTMARK(flag);
3153 WLEN(len); /* Don't BER-encode, this should be rare */
3154 }
3155 WRITE(class, len); /* Final \0 is omitted */
3156 }
3157
3158 /*
3159 * Now emit the <object> part.
3160 */
3161
3162 return SV_STORE(type)(cxt, sv);
3163}
3164
3165/*
3166 * store_other
3167 *
3168 * We don't know how to store the item we reached, so return an error condition.
3169 * (it's probably a GLOB, some CODE reference, etc...)
3170 *
3171 * If they defined the `forgive_me' variable at the Perl level to some
3172 * true value, then don't croak, just warn, and store a placeholder string
3173 * instead.
3174 */
f0ffaed8 3175static int store_other(stcxt_t *cxt, SV *sv)
7a6a85bf 3176{
cc964657 3177 I32 len;
7a6a85bf
RG
3178 static char buf[80];
3179
3180 TRACEME(("store_other"));
3181
3182 /*
3183 * Fetch the value from perl only once per store() operation.
3184 */
3185
3186 if (
3187 cxt->forgive_me == 0 ||
3188 (cxt->forgive_me < 0 && !(cxt->forgive_me =
3189 SvTRUE(perl_get_sv("Storable::forgive_me", TRUE)) ? 1 : 0))
3190 )
3191 CROAK(("Can't store %s items", sv_reftype(sv, FALSE)));
3192
43d061fe
JH
3193 warn("Can't store item %s(0x%"UVxf")",
3194 sv_reftype(sv, FALSE), PTR2UV(sv));
7a6a85bf
RG
3195
3196 /*
3197 * Store placeholder string as a scalar instead...
3198 */
3199
13689cfe 3200 (void) sprintf(buf, "You lost %s(0x%"UVxf")%c", sv_reftype(sv, FALSE),
e993d95c 3201 PTR2UV(sv), (char) 0);
7a6a85bf
RG
3202
3203 len = strlen(buf);
3204 STORE_SCALAR(buf, len);
1cf92b12 3205 TRACEME(("ok (dummy \"%s\", length = %"IVdf")", buf, (IV) len));
7a6a85bf
RG
3206
3207 return 0;
3208}
3209
3210/***
3211 *** Store driving routines
3212 ***/
3213
3214/*
3215 * sv_type
3216 *
3217 * WARNING: partially duplicates Perl's sv_reftype for speed.
3218 *
3219 * Returns the type of the SV, identified by an integer. That integer
3220 * may then be used to index the dynamic routine dispatch table.
3221 */
f0ffaed8 3222static int sv_type(SV *sv)
7a6a85bf
RG
3223{
3224 switch (SvTYPE(sv)) {
3225 case SVt_NULL:
3226 case SVt_IV:
3227 case SVt_NV:
3228 /*
3229 * No need to check for ROK, that can't be set here since there
3230 * is no field capable of hodling the xrv_rv reference.
3231 */
3232 return svis_SCALAR;
3233 case SVt_PV:
3234 case SVt_RV:
3235 case SVt_PVIV:
3236 case SVt_PVNV:
3237 /*
3238 * Starting from SVt_PV, it is possible to have the ROK flag
3239 * set, the pointer to the other SV being either stored in
3240 * the xrv_rv (in the case of a pure SVt_RV), or as the
3241 * xpv_pv field of an SVt_PV and its heirs.
3242 *
3243 * However, those SV cannot be magical or they would be an
3244 * SVt_PVMG at least.
3245 */
3246 return SvROK(sv) ? svis_REF : svis_SCALAR;
3247 case SVt_PVMG:
3248 case SVt_PVLV: /* Workaround for perl5.004_04 "LVALUE" bug */
3249 if (SvRMAGICAL(sv) && (mg_find(sv, 'p')))
3250 return svis_TIED_ITEM;
3251 /* FALL THROUGH */
3252 case SVt_PVBM:
3253 if (SvRMAGICAL(sv) && (mg_find(sv, 'q')))
3254 return svis_TIED;
3255 return SvROK(sv) ? svis_REF : svis_SCALAR;
3256 case SVt_PVAV:
3257 if (SvRMAGICAL(sv) && (mg_find(sv, 'P')))
3258 return svis_TIED;
3259 return svis_ARRAY;
3260 case SVt_PVHV:
3261 if (SvRMAGICAL(sv) && (mg_find(sv, 'P')))
3262 return svis_TIED;
3263 return svis_HASH;
464b080a
SR
3264 case SVt_PVCV:
3265 return svis_CODE;
7a6a85bf
RG
3266 default:
3267 break;
3268 }
3269
3270 return svis_OTHER;
3271}
3272
3273/*
3274 * store
3275 *
3276 * Recursively store objects pointed to by the sv to the specified file.
3277 *
3278 * Layout is <content> or SX_OBJECT <tagnum> if we reach an already stored
3279 * object (one for which storage has started -- it may not be over if we have
3280 * a self-referenced structure). This data set forms a stored <object>.
3281 */
f0ffaed8 3282static int store(stcxt_t *cxt, SV *sv)
7a6a85bf
RG
3283{
3284 SV **svh;
3285 int ret;
7a6a85bf 3286 int type;
43d061fe 3287 HV *hseen = cxt->hseen;
7a6a85bf 3288
43d061fe 3289 TRACEME(("store (0x%"UVxf")", PTR2UV(sv)));
7a6a85bf
RG
3290
3291 /*
3292 * If object has already been stored, do not duplicate data.
3293 * Simply emit the SX_OBJECT marker followed by its tag data.
3294 * The tag is always written in network order.
3295 *
3296 * NOTA BENE, for 64-bit machines: the "*svh" below does not yield a
3297 * real pointer, rather a tag number (watch the insertion code below).
464b080a 3298 * That means it probably safe to assume it is well under the 32-bit limit,
7a6a85bf
RG
3299 * and makes the truncation safe.
3300 * -- RAM, 14/09/1999
3301 */
3302
3303 svh = hv_fetch(hseen, (char *) &sv, sizeof(sv), FALSE);
3304 if (svh) {
dfd91409
NC
3305 I32 tagval;
3306
3307 if (sv == &PL_sv_undef) {
3308 /* We have seen PL_sv_undef before, but fake it as
3309 if we have not.
3310
3311 Not the simplest solution to making restricted
3312 hashes work on 5.8.0, but it does mean that
3313 repeated references to the one true undef will
3314 take up less space in the output file.
3315 */
3316 /* Need to jump past the next hv_store, because on the
3317 second store of undef the old hash value will be
17625bd2 3318 SvREFCNT_dec()ed, and as Storable cheats horribly
dfd91409
NC
3319 by storing non-SVs in the hash a SEGV will ensure.
3320 Need to increase the tag number so that the
3321 receiver has no idea what games we're up to. This
3322 special casing doesn't affect hooks that store
3323 undef, as the hook routine does its own lookup into
3324 hseen. Also this means that any references back
3325 to PL_sv_undef (from the pathological case of hooks
3326 storing references to it) will find the seen hash
3327 entry for the first time, as if we didn't have this
3328 hackery here. (That hseen lookup works even on 5.8.0
3329 because it's a key of &PL_sv_undef and a value
3330 which is a tag number, not a value which is
3331 PL_sv_undef.) */
3332 cxt->tagnum++;
3333 type = svis_SCALAR;
3334 goto undef_special_case;
3335 }
3336
3337 tagval = htonl(LOW_32BITS(*svh));
7a6a85bf 3338
9e21b3d0 3339 TRACEME(("object 0x%"UVxf" seen as #%d", PTR2UV(sv), ntohl(tagval)));
7a6a85bf
RG
3340
3341 PUTMARK(SX_OBJECT);
9e21b3d0 3342 WRITE_I32(tagval);
7a6a85bf
RG
3343 return 0;
3344 }
3345
3346 /*
3347 * Allocate a new tag and associate it with the address of the sv being
3348 * stored, before recursing...
3349 *
3350 * In order to avoid creating new SvIVs to hold the tagnum we just
d1be9408 3351 * cast the tagnum to an SV pointer and store that in the hash. This
7a6a85bf
RG
3352 * means that we must clean up the hash manually afterwards, but gives
3353 * us a 15% throughput increase.
3354 *
7a6a85bf
RG
3355 */
3356
3357 cxt->tagnum++;
3358 if (!hv_store(hseen,
3341c981 3359 (char *) &sv, sizeof(sv), INT2PTR(SV*, cxt->tagnum), 0))
7a6a85bf
RG
3360 return -1;
3361
3362 /*
3363 * Store `sv' and everything beneath it, using appropriate routine.
3364 * Abort immediately if we get a non-zero status back.
3365 */
3366
3367 type = sv_type(sv);
3368
dfd91409 3369undef_special_case:
43d061fe
JH
3370 TRACEME(("storing 0x%"UVxf" tag #%d, type %d...",
3371 PTR2UV(sv), cxt->tagnum, type));
7a6a85bf
RG
3372
3373 if (SvOBJECT(sv)) {
3374 HV *pkg = SvSTASH(sv);
3375 ret = store_blessed(cxt, sv, type, pkg);
3376 } else
3377 ret = SV_STORE(type)(cxt, sv);
3378
43d061fe
JH
3379 TRACEME(("%s (stored 0x%"UVxf", refcnt=%d, %s)",
3380 ret ? "FAILED" : "ok", PTR2UV(sv),
7a6a85bf
RG
3381 SvREFCNT(sv), sv_reftype(sv, FALSE)));
3382
3383 return ret;
3384}
3385
3386/*
3387 * magic_write
3388 *
3389 * Write magic number and system information into the file.
3390 * Layout is <magic> <network> [<len> <byteorder> <sizeof int> <sizeof long>
3391 * <sizeof ptr>] where <len> is the length of the byteorder hexa string.
3392 * All size and lenghts are written as single characters here.
3393 *
3394 * Note that no byte ordering info is emitted when <network> is true, since
3395 * integers will be emitted in network order in that case.
3396 */
f0ffaed8 3397static int magic_write(stcxt_t *cxt)
7a6a85bf 3398{
2aeb6432
NC
3399 /*
3400 * Starting with 0.6, the "use_network_order" byte flag is also used to
3401 * indicate the version number of the binary image, encoded in the upper
3402 * bits. The bit 0 is always used to indicate network order.
3403 */
3404 /*
3405 * Starting with 0.7, a full byte is dedicated to the minor version of
3406 * the binary format, which is incremented only when new markers are
3407 * introduced, for instance, but when backward compatibility is preserved.
3408 */
7a6a85bf 3409
2aeb6432
NC
3410 /* Make these at compile time. The WRITE() macro is sufficiently complex
3411 that it saves about 200 bytes doing it this way and only using it
3412 once. */
3413 static const unsigned char network_file_header[] = {
3414 MAGICSTR_BYTES,
3415 (STORABLE_BIN_MAJOR << 1) | 1,
3416 STORABLE_BIN_WRITE_MINOR
3417 };
3418 static const unsigned char file_header[] = {
3419 MAGICSTR_BYTES,
3420 (STORABLE_BIN_MAJOR << 1) | 0,
3421 STORABLE_BIN_WRITE_MINOR,
3422 /* sizeof the array includes the 0 byte at the end: */
3423 (char) sizeof (byteorderstr) - 1,
3424 BYTEORDER_BYTES,
3425 (unsigned char) sizeof(int),
3426 (unsigned char) sizeof(long),
3427 (unsigned char) sizeof(char *),
3428 (unsigned char) sizeof(NV)
3429 };
ee0f7aac
NC
3430#ifdef USE_56_INTERWORK_KLUDGE
3431 static const unsigned char file_header_56[] = {
3432 MAGICSTR_BYTES,
3433 (STORABLE_BIN_MAJOR << 1) | 0,
3434 STORABLE_BIN_WRITE_MINOR,
3435 /* sizeof the array includes the 0 byte at the end: */
3436 (char) sizeof (byteorderstr_56) - 1,
3437 BYTEORDER_BYTES_56,
3438 (unsigned char) sizeof(int),
3439 (unsigned char) sizeof(long),
3440 (unsigned char) sizeof(char *),
3441 (unsigned char) sizeof(NV)
3442 };
3443#endif
2aeb6432
NC
3444 const unsigned char *header;
3445 SSize_t length;
3446
3447 TRACEME(("magic_write on fd=%d", cxt->fio ? PerlIO_fileno(cxt->fio) : -1));
3448
3449 if (cxt->netorder) {
3450 header = network_file_header;
3451 length = sizeof (network_file_header);
3452 } else {
ee0f7aac
NC
3453#ifdef USE_56_INTERWORK_KLUDGE
3454 if (SvTRUE(perl_get_sv("Storable::interwork_56_64bit", TRUE))) {
3455 header = file_header_56;
3456 length = sizeof (file_header_56);
3457 } else
3458#endif
3459 {
3460 header = file_header;
3461 length = sizeof (file_header);
3462 }
2aeb6432
NC
3463 }
3464
3465 if (!cxt->fio) {
3466 /* sizeof the array includes the 0 byte at the end. */
3467 header += sizeof (magicstr) - 1;
3468 length -= sizeof (magicstr) - 1;
3469 }
3470
69495e6a 3471 WRITE( (unsigned char*) header, length);
2aeb6432
NC
3472
3473 if (!cxt->netorder) {
9e21b3d0 3474 TRACEME(("ok (magic_write byteorder = 0x%lx [%d], I%d L%d P%d D%d)",
2aeb6432 3475 (unsigned long) BYTEORDER, (int) sizeof (byteorderstr) - 1,
9e21b3d0
JH
3476 (int) sizeof(int), (int) sizeof(long),
3477 (int) sizeof(char *), (int) sizeof(NV)));
2aeb6432
NC
3478 }
3479 return 0;
7a6a85bf
RG
3480}
3481
3482/*
3483 * do_store
3484 *
3485 * Common code for store operations.
3486 *
3487 * When memory store is requested (f = NULL) and a non null SV* is given in
3488 * `res', it is filled with a new SV created out of the memory buffer.
3489 *
3490 * It is required to provide a non-null `res' when the operation type is not
3491 * dclone() and store() is performed to memory.
3492 */
f0ffaed8
JH
3493static int do_store(
3494 PerlIO *f,
3495 SV *sv,
3496 int optype,
3497 int network_order,
3498 SV **res)
7a6a85bf
RG
3499{
3500 dSTCXT;
3501 int status;
3502
3503 ASSERT(!(f == 0 && !(optype & ST_CLONE)) || res,
3504 ("must supply result SV pointer for real recursion to memory"));
3505
3506 TRACEME(("do_store (optype=%d, netorder=%d)",
3507 optype, network_order));
3508
3509 optype |= ST_STORE;
3510
3511 /*
3512 * Workaround for CROAK leak: if they enter with a "dirty" context,
3513 * free up memory for them now.
3514 */
3515
dd19458b 3516 if (cxt->s_dirty)
7a6a85bf
RG
3517 clean_context(cxt);
3518
3519 /*
3520 * Now that STORABLE_xxx hooks exist, it is possible that they try to
3521 * re-enter store() via the hooks. We need to stack contexts.
3522 */
3523
3524 if (cxt->entry)
3525 cxt = allocate_context(cxt);
3526
3527 cxt->entry++;
3528
3529 ASSERT(cxt->entry == 1, ("starting new recursion"));
dd19458b 3530 ASSERT(!cxt->s_dirty, ("clean context"));
7a6a85bf
RG
3531
3532 /*
3533 * Ensure sv is actually a reference. From perl, we called something
3534 * like:
3535 * pstore(FILE, \@array);
3536 * so we must get the scalar value behing that reference.
3537 */
3538
3539 if (!SvROK(sv))
3540 CROAK(("Not a reference"));
3541 sv = SvRV(sv); /* So follow it to know what to store */
3542
3543 /*
3544 * If we're going to store to memory, reset the buffer.
3545 */
3546
3547 if (!f)
3548 MBUF_INIT(0);
3549
3550 /*
3551 * Prepare context and emit headers.
3552 */
3553
3554 init_store_context(cxt, f, optype, network_order);
3555
3556 if (-1 == magic_write(cxt)) /* Emit magic and ILP info */
3557 return 0; /* Error */
3558
3559 /*
3560 * Recursively store object...
3561 */
3562
3563 ASSERT(is_storing(), ("within store operation"));
3564
3565 status = store(cxt, sv); /* Just do it! */
3566
3567 /*
3568 * If they asked for a memory store and they provided an SV pointer,
3569 * make an SV string out of the buffer and fill their pointer.
3570 *
3571 * When asking for ST_REAL, it's MANDATORY for the caller to provide
3572 * an SV, since context cleanup might free the buffer if we did recurse.
3573 * (unless caller is dclone(), which is aware of that).
3574 */
3575
3576 if (!cxt->fio && res)
3577 *res = mbuf2sv();
3578
3579 /*
3580 * Final cleanup.
3581 *
3582 * The "root" context is never freed, since it is meant to be always
3583 * handy for the common case where no recursion occurs at all (i.e.
3584 * we enter store() outside of any Storable code and leave it, period).
3585 * We know it's the "root" context because there's nothing stacked
3586 * underneath it.
3587 *
3588 * OPTIMIZATION:
3589 *
3590 * When deep cloning, we don't free the context: doing so would force
3591 * us to copy the data in the memory buffer. Sicne we know we're
3592 * about to enter do_retrieve...
3593 */
3594
3595 clean_store_context(cxt);
3596 if (cxt->prev && !(cxt->optype & ST_CLONE))
3597 free_context(cxt);
3598
3599 TRACEME(("do_store returns %d", status));
3600
3601 return status == 0;
3602}
3603
3604/*
3605 * pstore
3606 *
3607 * Store the transitive data closure of given object to disk.
3608 * Returns 0 on error, a true value otherwise.
3609 */
f0ffaed8 3610int pstore(PerlIO *f, SV *sv)
7a6a85bf
RG
3611{
3612 TRACEME(("pstore"));
f0ffaed8 3613 return do_store(f, sv, 0, FALSE, (SV**) 0);
7a6a85bf
RG
3614
3615}
3616
3617/*
3618 * net_pstore
3619 *
3620 * Same as pstore(), but network order is used for integers and doubles are
3621 * emitted as strings.
3622 */
f0ffaed8 3623int net_pstore(PerlIO *f, SV *sv)
7a6a85bf
RG
3624{
3625 TRACEME(("net_pstore"));
f0ffaed8 3626 return do_store(f, sv, 0, TRUE, (SV**) 0);
7a6a85bf
RG
3627}
3628
3629/***
3630 *** Memory stores.
3631 ***/
3632
3633/*
3634 * mbuf2sv
3635 *
3636 * Build a new SV out of the content of the internal memory buffer.
3637 */
f0ffaed8 3638static SV *mbuf2sv(void)
7a6a85bf
RG
3639{
3640 dSTCXT;
3641
3642 return newSVpv(mbase, MBUF_SIZE());
3643}
3644
3645/*
3646 * mstore
3647 *
3648 * Store the transitive data closure of given object to memory.
3649 * Returns undef on error, a scalar value containing the data otherwise.
3650 */
f0ffaed8 3651SV *mstore(SV *sv)
7a6a85bf 3652{
7a6a85bf
RG
3653 SV *out;
3654
3655 TRACEME(("mstore"));
3656
f0ffaed8 3657 if (!do_store((PerlIO*) 0, sv, 0, FALSE, &out))
7a6a85bf
RG
3658 return &PL_sv_undef;
3659
3660 return out;
3661}
3662
3663/*
3664 * net_mstore
3665 *
3666 * Same as mstore(), but network order is used for integers and doubles are
3667 * emitted as strings.
3668 */
f0ffaed8 3669SV *net_mstore(SV *sv)
7a6a85bf 3670{
7a6a85bf
RG
3671 SV *out;
3672
3673 TRACEME(("net_mstore"));
3674
f0ffaed8 3675 if (!do_store((PerlIO*) 0, sv, 0, TRUE, &out))
7a6a85bf
RG
3676 return &PL_sv_undef;
3677
3678 return out;
3679}
3680
3681/***
3682 *** Specific retrieve callbacks.
3683 ***/
3684
3685/*
3686 * retrieve_other
3687 *
3688 * Return an error via croak, since it is not possible that we get here
3689 * under normal conditions, when facing a file produced via pstore().
3690 */
b12202d0 3691static SV *retrieve_other(stcxt_t *cxt, char *cname)
7a6a85bf
RG
3692{
3693 if (
3694 cxt->ver_major != STORABLE_BIN_MAJOR &&
3695 cxt->ver_minor != STORABLE_BIN_MINOR
3696 ) {
3697 CROAK(("Corrupted storable %s (binary v%d.%d), current is v%d.%d",
3698 cxt->fio ? "file" : "string",
3699 cxt->ver_major, cxt->ver_minor,
3700 STORABLE_BIN_MAJOR, STORABLE_BIN_MINOR));
3701 } else {
3702 CROAK(("Corrupted storable %s (binary v%d.%d)",
3703 cxt->fio ? "file" : "string",
3704 cxt->ver_major, cxt->ver_minor));
3705 }
3706
3707 return (SV *) 0; /* Just in case */
3708}
3709
3710/*
3711 * retrieve_idx_blessed
3712 *
3713 * Layout is SX_IX_BLESS <index> <object> with SX_IX_BLESS already read.
3714 * <index> can be coded on either 1 or 5 bytes.
3715 */
b12202d0 3716static SV *retrieve_idx_blessed(stcxt_t *cxt, char *cname)
7a6a85bf
RG
3717{
3718 I32 idx;
3719 char *class;
3720 SV **sva;
3721 SV *sv;
3722
3723 TRACEME(("retrieve_idx_blessed (#%d)", cxt->tagnum));
b12202d0 3724 ASSERT(!cname, ("no bless-into class given here, got %s", cname));
7a6a85bf
RG
3725
3726 GETMARK(idx); /* Index coded on a single char? */
3727 if (idx & 0x80)
3728 RLEN(idx);
3729
3730 /*
3731 * Fetch classname in `aclass'
3732 */
3733
3734 sva = av_fetch(cxt->aclass, idx, FALSE);
3735 if (!sva)
e993d95c 3736 CROAK(("Class name #%"IVdf" should have been seen already", (IV) idx));
7a6a85bf
RG
3737
3738 class = SvPVX(*sva); /* We know it's a PV, by construction */
3739
3740 TRACEME(("class ID %d => %s", idx, class));
3741
3742 /*
3743 * Retrieve object and bless it.
3744 */
3745
b12202d0 3746 sv = retrieve(cxt, class); /* First SV which is SEEN will be blessed */
7a6a85bf
RG
3747
3748 return sv;
3749}
3750
3751/*
3752 * retrieve_blessed
3753 *
3754 * Layout is SX_BLESS <len> <classname> <object> with SX_BLESS already read.
3755 * <len> can be coded on either 1 or 5 bytes.
3756 */
b12202d0<