This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Storable 3.00: u64 strings, arrays and hashes >2G
[perl5.git] / dist / Storable / __Storable__.pm
1 #
2 #  Copyright (c) 1995-2001, Raphael Manfredi
3 #  Copyright (c) 2002-2014 by the Perl 5 Porters
4 #  Copyright (c) 2015-2016 cPanel Inc
5 #
6 #  You may redistribute only under the same terms as Perl 5, as specified
7 #  in the README file that comes with the distribution.
8 #
9
10 require XSLoader;
11 require Exporter;
12 package Storable;
13
14 our @ISA = qw(Exporter);
15 our @EXPORT = qw(store retrieve);
16 our @EXPORT_OK = qw(
17         nstore store_fd nstore_fd fd_retrieve
18         freeze nfreeze thaw
19         dclone
20         retrieve_fd
21         lock_store lock_nstore lock_retrieve
22         file_magic read_magic
23         BLESS_OK TIE_OK FLAGS_COMPAT
24 );
25
26 our ($canonical, $forgive_me);
27
28 our $VERSION = '2.65';
29
30 BEGIN {
31     if (eval {
32         local $SIG{__DIE__};
33         local @INC = @INC;
34         pop @INC if $INC[-1] eq '.';
35         require Log::Agent;
36         1;
37     }) {
38         Log::Agent->import;
39     }
40     #
41     # Use of Log::Agent is optional. If it hasn't imported these subs then
42     # provide a fallback implementation.
43     #
44     unless ($Storable::{logcroak} && *{$Storable::{logcroak}}{CODE}) {
45         require Carp;
46         *logcroak = sub {
47             Carp::croak(@_);
48         };
49     }
50     unless ($Storable::{logcarp} && *{$Storable::{logcarp}}{CODE}) {
51         require Carp;
52         *logcarp = sub {
53           Carp::carp(@_);
54         };
55     }
56 }
57
58 #
59 # They might miss :flock in Fcntl
60 #
61
62 BEGIN {
63     if (eval { require Fcntl; 1 } && exists $Fcntl::EXPORT_TAGS{'flock'}) {
64         Fcntl->import(':flock');
65     } else {
66         eval q{
67                   sub LOCK_SH () { 1 }
68                   sub LOCK_EX () { 2 }
69               };
70     }
71 }
72
73 sub CLONE {
74     # clone context under threads
75     Storable::init_perinterp();
76 }
77
78 sub BLESS_OK     () { 2 }
79 sub TIE_OK       () { 4 }
80 sub FLAGS_COMPAT () { BLESS_OK | TIE_OK }
81
82 # By default restricted hashes are downgraded on earlier perls.
83
84 $Storable::flags = FLAGS_COMPAT;
85 $Storable::downgrade_restricted = 1;
86 $Storable::accept_future_minor = 1;
87
88 XSLoader::load('Storable', $Storable::VERSION);
89
90 #
91 # Determine whether locking is possible, but only when needed.
92 #
93
94 sub CAN_FLOCK; # TEMPLATE - replaced by Storable.pm.PL
95
96 sub show_file_magic {
97     print <<EOM;
98 #
99 # To recognize the data files of the Perl module Storable,
100 # the following lines need to be added to the local magic(5) file,
101 # usually either /usr/share/misc/magic or /etc/magic.
102 #
103 0       string  perl-store      perl Storable(v0.6) data
104 >4      byte    >0      (net-order %d)
105 >>4     byte    &01     (network-ordered)
106 >>4     byte    =3      (major 1)
107 >>4     byte    =2      (major 1)
108
109 0       string  pst0    perl Storable(v0.7) data
110 >4      byte    >0
111 >>4     byte    &01     (network-ordered)
112 >>4     byte    =5      (major 2)
113 >>4     byte    =4      (major 2)
114 >>5     byte    >0      (minor %d)
115 EOM
116 }
117
118 sub file_magic {
119     require IO::File;
120
121     my $file = shift;
122     my $fh = IO::File->new;
123     open($fh, "<", $file) || die "Can't open '$file': $!";
124     binmode($fh);
125     defined(sysread($fh, my $buf, 32)) || die "Can't read from '$file': $!";
126     close($fh);
127
128     $file = "./$file" unless $file;  # ensure TRUE value
129
130     return read_magic($buf, $file);
131 }
132
133 sub read_magic {
134     my($buf, $file) = @_;
135     my %info;
136
137     my $buflen = length($buf);
138     my $magic;
139     if ($buf =~ s/^(pst0|perl-store)//) {
140         $magic = $1;
141         $info{file} = $file || 1;
142     }
143     else {
144         return undef if $file;
145         $magic = "";
146     }
147
148     return undef unless length($buf);
149
150     my $net_order;
151     if ($magic eq "perl-store" && ord(substr($buf, 0, 1)) > 1) {
152         $info{version} = -1;
153         $net_order = 0;
154     }
155     else {
156         $buf =~ s/(.)//s;
157         my $major = (ord $1) >> 1;
158         return undef if $major > 4; # sanity (assuming we never go that high)
159         $info{major} = $major;
160         $net_order = (ord $1) & 0x01;
161         if ($major > 1) {
162             return undef unless $buf =~ s/(.)//s;
163             my $minor = ord $1;
164             $info{minor} = $minor;
165             $info{version} = "$major.$minor";
166             $info{version_nv} = sprintf "%d.%03d", $major, $minor;
167         }
168         else {
169             $info{version} = $major;
170         }
171     }
172     $info{version_nv} ||= $info{version};
173     $info{netorder} = $net_order;
174
175     unless ($net_order) {
176         return undef unless $buf =~ s/(.)//s;
177         my $len = ord $1;
178         return undef unless length($buf) >= $len;
179         return undef unless $len == 4 || $len == 8;  # sanity
180         @info{qw(byteorder intsize longsize ptrsize)}
181             = unpack "a${len}CCC", $buf;
182         (substr $buf, 0, $len + 3) = '';
183         if ($info{version_nv} >= 2.002) {
184             return undef unless $buf =~ s/(.)//s;
185             $info{nvsize} = ord $1;
186         }
187     }
188     $info{hdrsize} = $buflen - length($buf);
189
190     return \%info;
191 }
192
193 sub BIN_VERSION_NV {
194     sprintf "%d.%03d", BIN_MAJOR(), BIN_MINOR();
195 }
196
197 sub BIN_WRITE_VERSION_NV {
198     sprintf "%d.%03d", BIN_MAJOR(), BIN_WRITE_MINOR();
199 }
200
201 #
202 # store
203 #
204 # Store target object hierarchy, identified by a reference to its root.
205 # The stored object tree may later be retrieved to memory via retrieve.
206 # Returns undef if an I/O error occurred, in which case the file is
207 # removed.
208 #
209 sub store {
210     return _store(\&pstore, @_, 0);
211 }
212
213 #
214 # nstore
215 #
216 # Same as store, but in network order.
217 #
218 sub nstore {
219     return _store(\&net_pstore, @_, 0);
220 }
221
222 #
223 # lock_store
224 #
225 # Same as store, but flock the file first (advisory locking).
226 #
227 sub lock_store {
228     return _store(\&pstore, @_, 1);
229 }
230
231 #
232 # lock_nstore
233 #
234 # Same as nstore, but flock the file first (advisory locking).
235 #
236 sub lock_nstore {
237     return _store(\&net_pstore, @_, 1);
238 }
239
240 # Internal store to file routine
241 sub _store {
242     my $xsptr = shift;
243     my $self = shift;
244     my ($file, $use_locking) = @_;
245     logcroak "not a reference" unless ref($self);
246     logcroak "wrong argument number" unless @_ == 2;    # No @foo in arglist
247     local *FILE;
248     if ($use_locking) {
249         open(FILE, ">>", $file) || logcroak "can't write into $file: $!";
250         unless (&CAN_FLOCK) {
251             logcarp
252               "Storable::lock_store: fcntl/flock emulation broken on $^O";
253             return undef;
254         }
255         flock(FILE, LOCK_EX) ||
256           logcroak "can't get exclusive lock on $file: $!";
257         truncate FILE, 0;
258         # Unlocking will happen when FILE is closed
259     } else {
260         open(FILE, ">", $file) || logcroak "can't create $file: $!";
261     }
262     binmode FILE;       # Archaic systems...
263     my $da = $@;        # Don't mess if called from exception handler
264     my $ret;
265     # Call C routine nstore or pstore, depending on network order
266     eval { $ret = &$xsptr(*FILE, $self) };
267     # close will return true on success, so the or short-circuits, the ()
268     # expression is true, and for that case the block will only be entered
269     # if $@ is true (ie eval failed)
270     # if close fails, it returns false, $ret is altered, *that* is (also)
271     # false, so the () expression is false, !() is true, and the block is
272     # entered.
273     if (!(close(FILE) or undef $ret) || $@) {
274         unlink($file) or warn "Can't unlink $file: $!\n";
275     }
276     logcroak $@ if $@ =~ s/\.?\n$/,/;
277     $@ = $da;
278     return $ret;
279 }
280
281 #
282 # store_fd
283 #
284 # Same as store, but perform on an already opened file descriptor instead.
285 # Returns undef if an I/O error occurred.
286 #
287 sub store_fd {
288     return _store_fd(\&pstore, @_);
289 }
290
291 #
292 # nstore_fd
293 #
294 # Same as store_fd, but in network order.
295 #
296 sub nstore_fd {
297     my ($self, $file) = @_;
298     return _store_fd(\&net_pstore, @_);
299 }
300
301 # Internal store routine on opened file descriptor
302 sub _store_fd {
303     my $xsptr = shift;
304     my $self = shift;
305     my ($file) = @_;
306     logcroak "not a reference" unless ref($self);
307     logcroak "too many arguments" unless @_ == 1;       # No @foo in arglist
308     my $fd = fileno($file);
309     logcroak "not a valid file descriptor" unless defined $fd;
310     my $da = $@;                # Don't mess if called from exception handler
311     my $ret;
312     # Call C routine nstore or pstore, depending on network order
313     eval { $ret = &$xsptr($file, $self) };
314     logcroak $@ if $@ =~ s/\.?\n$/,/;
315     local $\; print $file '';   # Autoflush the file if wanted
316     $@ = $da;
317     return $ret;
318 }
319
320 #
321 # freeze
322 #
323 # Store object and its hierarchy in memory and return a scalar
324 # containing the result.
325 #
326 sub freeze {
327     _freeze(\&mstore, @_);
328 }
329
330 #
331 # nfreeze
332 #
333 # Same as freeze but in network order.
334 #
335 sub nfreeze {
336     _freeze(\&net_mstore, @_);
337 }
338
339 # Internal freeze routine
340 sub _freeze {
341     my $xsptr = shift;
342     my $self = shift;
343     logcroak "not a reference" unless ref($self);
344     logcroak "too many arguments" unless @_ == 0;       # No @foo in arglist
345     my $da = $@;                # Don't mess if called from exception handler
346     my $ret;
347     # Call C routine mstore or net_mstore, depending on network order
348     eval { $ret = &$xsptr($self) };
349     logcroak $@ if $@ =~ s/\.?\n$/,/;
350     $@ = $da;
351     return $ret ? $ret : undef;
352 }
353
354 #
355 # retrieve
356 #
357 # Retrieve object hierarchy from disk, returning a reference to the root
358 # object of that tree.
359 #
360 # retrieve(file, flags)
361 # flags include by default BLESS_OK=2 | TIE_OK=4
362 # with flags=0 or the global $Storable::flags set to 0, no resulting object
363 # will be blessed nor tied.
364 #
365 sub retrieve {
366     _retrieve(shift, 0, @_);
367 }
368
369 #
370 # lock_retrieve
371 #
372 # Same as retrieve, but with advisory locking.
373 #
374 sub lock_retrieve {
375     _retrieve(shift, 1, @_);
376 }
377
378 # Internal retrieve routine
379 sub _retrieve {
380     my ($file, $use_locking, $flags) = @_;
381     $flags = $Storable::flags unless defined $flags;
382     my $FILE;
383     open($FILE, "<", $file) || logcroak "can't open $file: $!";
384     binmode $FILE;                      # Archaic systems...
385     my $self;
386     my $da = $@;                        # Could be from exception handler
387     if ($use_locking) {
388         unless (&CAN_FLOCK) {
389             logcarp
390               "Storable::lock_store: fcntl/flock emulation broken on $^O";
391             return undef;
392         }
393         flock($FILE, LOCK_SH) || logcroak "can't get shared lock on $file: $!";
394         # Unlocking will happen when FILE is closed
395     }
396     eval { $self = pretrieve($FILE, $flags) };          # Call C routine
397     close($FILE);
398     logcroak $@ if $@ =~ s/\.?\n$/,/;
399     $@ = $da;
400     return $self;
401 }
402
403 #
404 # fd_retrieve
405 #
406 # Same as retrieve, but perform from an already opened file descriptor instead.
407 #
408 sub fd_retrieve {
409     my ($file, $flags) = @_;
410     $flags = $Storable::flags unless defined $flags;
411     my $fd = fileno($file);
412     logcroak "not a valid file descriptor" unless defined $fd;
413     my $self;
414     my $da = $@;                                # Could be from exception handler
415     eval { $self = pretrieve($file, $flags) };  # Call C routine
416     logcroak $@ if $@ =~ s/\.?\n$/,/;
417     $@ = $da;
418     return $self;
419 }
420
421 sub retrieve_fd { &fd_retrieve }                # Backward compatibility
422
423 #
424 # thaw
425 #
426 # Recreate objects in memory from an existing frozen image created
427 # by freeze.  If the frozen image passed is undef, return undef.
428 #
429 # thaw(frozen_obj, flags)
430 # flags include by default BLESS_OK=2 | TIE_OK=4
431 # with flags=0 or the global $Storable::flags set to 0, no resulting object
432 # will be blessed nor tied.
433 #
434 sub thaw {
435     my ($frozen, $flags) = @_;
436     $flags = $Storable::flags unless defined $flags;
437     return undef unless defined $frozen;
438     my $self;
439     my $da = $@;                                # Could be from exception handler
440     eval { $self = mretrieve($frozen, $flags) };# Call C routine
441     logcroak $@ if $@ =~ s/\.?\n$/,/;
442     $@ = $da;
443     return $self;
444 }
445
446 1;
447 __END__
448
449 =head1 NAME
450
451 Storable - persistence for Perl data structures
452
453 =head1 SYNOPSIS
454
455  use Storable;
456  store \%table, 'file';
457  $hashref = retrieve('file');
458
459  use Storable qw(nstore store_fd nstore_fd freeze thaw dclone);
460
461  # Network order
462  nstore \%table, 'file';
463  $hashref = retrieve('file');   # There is NO nretrieve()
464
465  # Storing to and retrieving from an already opened file
466  store_fd \@array, \*STDOUT;
467  nstore_fd \%table, \*STDOUT;
468  $aryref = fd_retrieve(\*SOCKET);
469  $hashref = fd_retrieve(\*SOCKET);
470
471  # Serializing to memory
472  $serialized = freeze \%table;
473  %table_clone = %{ thaw($serialized) };
474
475  # Deep (recursive) cloning
476  $cloneref = dclone($ref);
477
478  # Advisory locking
479  use Storable qw(lock_store lock_nstore lock_retrieve)
480  lock_store \%table, 'file';
481  lock_nstore \%table, 'file';
482  $hashref = lock_retrieve('file');
483
484 =head1 DESCRIPTION
485
486 The Storable package brings persistence to your Perl data structures
487 containing SCALAR, ARRAY, HASH or REF objects, i.e. anything that can be
488 conveniently stored to disk and retrieved at a later time.
489
490 It can be used in the regular procedural way by calling C<store> with
491 a reference to the object to be stored, along with the file name where
492 the image should be written.
493
494 The routine returns C<undef> for I/O problems or other internal error,
495 a true value otherwise. Serious errors are propagated as a C<die> exception.
496
497 To retrieve data stored to disk, use C<retrieve> with a file name.
498 The objects stored into that file are recreated into memory for you,
499 and a I<reference> to the root object is returned. In case an I/O error
500 occurs while reading, C<undef> is returned instead. Other serious
501 errors are propagated via C<die>.
502
503 Since storage is performed recursively, you might want to stuff references
504 to objects that share a lot of common data into a single array or hash
505 table, and then store that object. That way, when you retrieve back the
506 whole thing, the objects will continue to share what they originally shared.
507
508 At the cost of a slight header overhead, you may store to an already
509 opened file descriptor using the C<store_fd> routine, and retrieve
510 from a file via C<fd_retrieve>. Those names aren't imported by default,
511 so you will have to do that explicitly if you need those routines.
512 The file descriptor you supply must be already opened, for read
513 if you're going to retrieve and for write if you wish to store.
514
515         store_fd(\%table, *STDOUT) || die "can't store to stdout\n";
516         $hashref = fd_retrieve(*STDIN);
517
518 You can also store data in network order to allow easy sharing across
519 multiple platforms, or when storing on a socket known to be remotely
520 connected. The routines to call have an initial C<n> prefix for I<network>,
521 as in C<nstore> and C<nstore_fd>. At retrieval time, your data will be
522 correctly restored so you don't have to know whether you're restoring
523 from native or network ordered data.  Double values are stored stringified
524 to ensure portability as well, at the slight risk of loosing some precision
525 in the last decimals.
526
527 When using C<fd_retrieve>, objects are retrieved in sequence, one
528 object (i.e. one recursive tree) per associated C<store_fd>.
529
530 If you're more from the object-oriented camp, you can inherit from
531 Storable and directly store your objects by invoking C<store> as
532 a method. The fact that the root of the to-be-stored tree is a
533 blessed reference (i.e. an object) is special-cased so that the
534 retrieve does not provide a reference to that object but rather the
535 blessed object reference itself. (Otherwise, you'd get a reference
536 to that blessed object).
537
538 =head1 MEMORY STORE
539
540 The Storable engine can also store data into a Perl scalar instead, to
541 later retrieve them. This is mainly used to freeze a complex structure in
542 some safe compact memory place (where it can possibly be sent to another
543 process via some IPC, since freezing the structure also serializes it in
544 effect). Later on, and maybe somewhere else, you can thaw the Perl scalar
545 out and recreate the original complex structure in memory.
546
547 Surprisingly, the routines to be called are named C<freeze> and C<thaw>.
548 If you wish to send out the frozen scalar to another machine, use
549 C<nfreeze> instead to get a portable image.
550
551 Note that freezing an object structure and immediately thawing it
552 actually achieves a deep cloning of that structure:
553
554     dclone(.) = thaw(freeze(.))
555
556 Storable provides you with a C<dclone> interface which does not create
557 that intermediary scalar but instead freezes the structure in some
558 internal memory space and then immediately thaws it out.
559
560 =head1 ADVISORY LOCKING
561
562 The C<lock_store> and C<lock_nstore> routine are equivalent to
563 C<store> and C<nstore>, except that they get an exclusive lock on
564 the file before writing.  Likewise, C<lock_retrieve> does the same
565 as C<retrieve>, but also gets a shared lock on the file before reading.
566
567 As with any advisory locking scheme, the protection only works if you
568 systematically use C<lock_store> and C<lock_retrieve>.  If one side of
569 your application uses C<store> whilst the other uses C<lock_retrieve>,
570 you will get no protection at all.
571
572 The internal advisory locking is implemented using Perl's flock()
573 routine.  If your system does not support any form of flock(), or if
574 you share your files across NFS, you might wish to use other forms
575 of locking by using modules such as LockFile::Simple which lock a
576 file using a filesystem entry, instead of locking the file descriptor.
577
578 =head1 SPEED
579
580 The heart of Storable is written in C for decent speed. Extra low-level
581 optimizations have been made when manipulating perl internals, to
582 sacrifice encapsulation for the benefit of greater speed.
583
584 =head1 CANONICAL REPRESENTATION
585
586 Normally, Storable stores elements of hashes in the order they are
587 stored internally by Perl, i.e. pseudo-randomly.  If you set
588 C<$Storable::canonical> to some C<TRUE> value, Storable will store
589 hashes with the elements sorted by their key.  This allows you to
590 compare data structures by comparing their frozen representations (or
591 even the compressed frozen representations), which can be useful for
592 creating lookup tables for complicated queries.
593
594 Canonical order does not imply network order; those are two orthogonal
595 settings.
596
597 =head1 CODE REFERENCES
598
599 Since Storable version 2.05, CODE references may be serialized with
600 the help of L<B::Deparse>. To enable this feature, set
601 C<$Storable::Deparse> to a true value. To enable deserialization,
602 C<$Storable::Eval> should be set to a true value. Be aware that
603 deserialization is done through C<eval>, which is dangerous if the
604 Storable file contains malicious data. You can set C<$Storable::Eval>
605 to a subroutine reference which would be used instead of C<eval>. See
606 below for an example using a L<Safe> compartment for deserialization
607 of CODE references.
608
609 If C<$Storable::Deparse> and/or C<$Storable::Eval> are set to false
610 values, then the value of C<$Storable::forgive_me> (see below) is
611 respected while serializing and deserializing.
612
613 =head1 FORWARD COMPATIBILITY
614
615 This release of Storable can be used on a newer version of Perl to
616 serialize data which is not supported by earlier Perls.  By default,
617 Storable will attempt to do the right thing, by C<croak()>ing if it
618 encounters data that it cannot deserialize.  However, the defaults
619 can be changed as follows:
620
621 =over 4
622
623 =item utf8 data
624
625 Perl 5.6 added support for Unicode characters with code points > 255,
626 and Perl 5.8 has full support for Unicode characters in hash keys.
627 Perl internally encodes strings with these characters using utf8, and
628 Storable serializes them as utf8.  By default, if an older version of
629 Perl encounters a utf8 value it cannot represent, it will C<croak()>.
630 To change this behaviour so that Storable deserializes utf8 encoded
631 values as the string of bytes (effectively dropping the I<is_utf8> flag)
632 set C<$Storable::drop_utf8> to some C<TRUE> value.  This is a form of
633 data loss, because with C<$drop_utf8> true, it becomes impossible to tell
634 whether the original data was the Unicode string, or a series of bytes
635 that happen to be valid utf8.
636
637 =item restricted hashes
638
639 Perl 5.8 adds support for restricted hashes, which have keys
640 restricted to a given set, and can have values locked to be read only.
641 By default, when Storable encounters a restricted hash on a perl
642 that doesn't support them, it will deserialize it as a normal hash,
643 silently discarding any placeholder keys and leaving the keys and
644 all values unlocked.  To make Storable C<croak()> instead, set
645 C<$Storable::downgrade_restricted> to a C<FALSE> value.  To restore
646 the default set it back to some C<TRUE> value.
647
648 =item files from future versions of Storable
649
650 Earlier versions of Storable would immediately croak if they encountered
651 a file with a higher internal version number than the reading Storable
652 knew about.  Internal version numbers are increased each time new data
653 types (such as restricted hashes) are added to the vocabulary of the file
654 format.  This meant that a newer Storable module had no way of writing a
655 file readable by an older Storable, even if the writer didn't store newer
656 data types.
657
658 This version of Storable will defer croaking until it encounters a data
659 type in the file that it does not recognize.  This means that it will
660 continue to read files generated by newer Storable modules which are careful
661 in what they write out, making it easier to upgrade Storable modules in a
662 mixed environment.
663
664 The old behaviour of immediate croaking can be re-instated by setting
665 C<$Storable::accept_future_minor> to some C<FALSE> value.
666
667 =back
668
669 All these variables have no effect on a newer Perl which supports the
670 relevant feature.
671
672 =head1 ERROR REPORTING
673
674 Storable uses the "exception" paradigm, in that it does not try to workaround
675 failures: if something bad happens, an exception is generated from the
676 caller's perspective (see L<Carp> and C<croak()>).  Use eval {} to trap
677 those exceptions.
678
679 When Storable croaks, it tries to report the error via the C<logcroak()>
680 routine from the C<Log::Agent> package, if it is available.
681
682 Normal errors are reported by having store() or retrieve() return C<undef>.
683 Such errors are usually I/O errors (or truncated stream errors at retrieval).
684
685 =head1 WIZARDS ONLY
686
687 =head2 Hooks
688
689 Any class may define hooks that will be called during the serialization
690 and deserialization process on objects that are instances of that class.
691 Those hooks can redefine the way serialization is performed (and therefore,
692 how the symmetrical deserialization should be conducted).
693
694 Since we said earlier:
695
696     dclone(.) = thaw(freeze(.))
697
698 everything we say about hooks should also hold for deep cloning. However,
699 hooks get to know whether the operation is a mere serialization, or a cloning.
700
701 Therefore, when serializing hooks are involved,
702
703     dclone(.) <> thaw(freeze(.))
704
705 Well, you could keep them in sync, but there's no guarantee it will always
706 hold on classes somebody else wrote.  Besides, there is little to gain in
707 doing so: a serializing hook could keep only one attribute of an object,
708 which is probably not what should happen during a deep cloning of that
709 same object.
710
711 Here is the hooking interface:
712
713 =over 4
714
715 =item C<STORABLE_freeze> I<obj>, I<cloning>
716
717 The serializing hook, called on the object during serialization.  It can be
718 inherited, or defined in the class itself, like any other method.
719
720 Arguments: I<obj> is the object to serialize, I<cloning> is a flag indicating
721 whether we're in a dclone() or a regular serialization via store() or freeze().
722
723 Returned value: A LIST C<($serialized, $ref1, $ref2, ...)> where $serialized
724 is the serialized form to be used, and the optional $ref1, $ref2, etc... are
725 extra references that you wish to let the Storable engine serialize.
726
727 At deserialization time, you will be given back the same LIST, but all the
728 extra references will be pointing into the deserialized structure.
729
730 The B<first time> the hook is hit in a serialization flow, you may have it
731 return an empty list.  That will signal the Storable engine to further
732 discard that hook for this class and to therefore revert to the default
733 serialization of the underlying Perl data.  The hook will again be normally
734 processed in the next serialization.
735
736 Unless you know better, serializing hook should always say:
737
738     sub STORABLE_freeze {
739         my ($self, $cloning) = @_;
740         return if $cloning;         # Regular default serialization
741         ....
742     }
743
744 in order to keep reasonable dclone() semantics.
745
746 =item C<STORABLE_thaw> I<obj>, I<cloning>, I<serialized>, ...
747
748 The deserializing hook called on the object during deserialization.
749 But wait: if we're deserializing, there's no object yet... right?
750
751 Wrong: the Storable engine creates an empty one for you.  If you know Eiffel,
752 you can view C<STORABLE_thaw> as an alternate creation routine.
753
754 This means the hook can be inherited like any other method, and that
755 I<obj> is your blessed reference for this particular instance.
756
757 The other arguments should look familiar if you know C<STORABLE_freeze>:
758 I<cloning> is true when we're part of a deep clone operation, I<serialized>
759 is the serialized string you returned to the engine in C<STORABLE_freeze>,
760 and there may be an optional list of references, in the same order you gave
761 them at serialization time, pointing to the deserialized objects (which
762 have been processed courtesy of the Storable engine).
763
764 When the Storable engine does not find any C<STORABLE_thaw> hook routine,
765 it tries to load the class by requiring the package dynamically (using
766 the blessed package name), and then re-attempts the lookup.  If at that
767 time the hook cannot be located, the engine croaks.  Note that this mechanism
768 will fail if you define several classes in the same file, but L<perlmod>
769 warned you.
770
771 It is up to you to use this information to populate I<obj> the way you want.
772
773 Returned value: none.
774
775 =item C<STORABLE_attach> I<class>, I<cloning>, I<serialized>
776
777 While C<STORABLE_freeze> and C<STORABLE_thaw> are useful for classes where
778 each instance is independent, this mechanism has difficulty (or is
779 incompatible) with objects that exist as common process-level or
780 system-level resources, such as singleton objects, database pools, caches
781 or memoized objects.
782
783 The alternative C<STORABLE_attach> method provides a solution for these
784 shared objects. Instead of C<STORABLE_freeze> --E<gt> C<STORABLE_thaw>,
785 you implement C<STORABLE_freeze> --E<gt> C<STORABLE_attach> instead.
786
787 Arguments: I<class> is the class we are attaching to, I<cloning> is a flag
788 indicating whether we're in a dclone() or a regular de-serialization via
789 thaw(), and I<serialized> is the stored string for the resource object.
790
791 Because these resource objects are considered to be owned by the entire
792 process/system, and not the "property" of whatever is being serialized,
793 no references underneath the object should be included in the serialized
794 string. Thus, in any class that implements C<STORABLE_attach>, the
795 C<STORABLE_freeze> method cannot return any references, and C<Storable>
796 will throw an error if C<STORABLE_freeze> tries to return references.
797
798 All information required to "attach" back to the shared resource object
799 B<must> be contained B<only> in the C<STORABLE_freeze> return string.
800 Otherwise, C<STORABLE_freeze> behaves as normal for C<STORABLE_attach>
801 classes.
802
803 Because C<STORABLE_attach> is passed the class (rather than an object),
804 it also returns the object directly, rather than modifying the passed
805 object.
806
807 Returned value: object of type C<class>
808
809 =back
810
811 =head2 Predicates
812
813 Predicates are not exportable.  They must be called by explicitly prefixing
814 them with the Storable package name.
815
816 =over 4
817
818 =item C<Storable::last_op_in_netorder>
819
820 The C<Storable::last_op_in_netorder()> predicate will tell you whether
821 network order was used in the last store or retrieve operation.  If you
822 don't know how to use this, just forget about it.
823
824 =item C<Storable::is_storing>
825
826 Returns true if within a store operation (via STORABLE_freeze hook).
827
828 =item C<Storable::is_retrieving>
829
830 Returns true if within a retrieve operation (via STORABLE_thaw hook).
831
832 =back
833
834 =head2 Recursion
835
836 With hooks comes the ability to recurse back to the Storable engine.
837 Indeed, hooks are regular Perl code, and Storable is convenient when
838 it comes to serializing and deserializing things, so why not use it
839 to handle the serialization string?
840
841 There are a few things you need to know, however:
842
843 =over 4
844
845 =item *
846
847 You can create endless loops if the things you serialize via freeze()
848 (for instance) point back to the object we're trying to serialize in
849 the hook.
850
851 =item *
852
853 Shared references among objects will not stay shared: if we're serializing
854 the list of object [A, C] where both object A and C refer to the SAME object
855 B, and if there is a serializing hook in A that says freeze(B), then when
856 deserializing, we'll get [A', C'] where A' refers to B', but C' refers to D,
857 a deep clone of B'.  The topology was not preserved.
858
859 =back
860
861 That's why C<STORABLE_freeze> lets you provide a list of references
862 to serialize.  The engine guarantees that those will be serialized in the
863 same context as the other objects, and therefore that shared objects will
864 stay shared.
865
866 In the above [A, C] example, the C<STORABLE_freeze> hook could return:
867
868         ("something", $self->{B})
869
870 and the B part would be serialized by the engine.  In C<STORABLE_thaw>, you
871 would get back the reference to the B' object, deserialized for you.
872
873 Therefore, recursion should normally be avoided, but is nonetheless supported.
874
875 =head2 Deep Cloning
876
877 There is a Clone module available on CPAN which implements deep cloning
878 natively, i.e. without freezing to memory and thawing the result.  It is
879 aimed to replace Storable's dclone() some day.  However, it does not currently
880 support Storable hooks to redefine the way deep cloning is performed.
881
882 =head1 Storable magic
883
884 Yes, there's a lot of that :-) But more precisely, in UNIX systems
885 there's a utility called C<file>, which recognizes data files based on
886 their contents (usually their first few bytes).  For this to work,
887 a certain file called F<magic> needs to taught about the I<signature>
888 of the data.  Where that configuration file lives depends on the UNIX
889 flavour; often it's something like F</usr/share/misc/magic> or
890 F</etc/magic>.  Your system administrator needs to do the updating of
891 the F<magic> file.  The necessary signature information is output to
892 STDOUT by invoking Storable::show_file_magic().  Note that the GNU
893 implementation of the C<file> utility, version 3.38 or later,
894 is expected to contain support for recognising Storable files
895 out-of-the-box, in addition to other kinds of Perl files.
896
897 You can also use the following functions to extract the file header
898 information from Storable images:
899
900 =over
901
902 =item $info = Storable::file_magic( $filename )
903
904 If the given file is a Storable image return a hash describing it.  If
905 the file is readable, but not a Storable image return C<undef>.  If
906 the file does not exist or is unreadable then croak.
907
908 The hash returned has the following elements:
909
910 =over
911
912 =item C<version>
913
914 This returns the file format version.  It is a string like "2.7".
915
916 Note that this version number is not the same as the version number of
917 the Storable module itself.  For instance Storable v0.7 create files
918 in format v2.0 and Storable v2.15 create files in format v2.7.  The
919 file format version number only increment when additional features
920 that would confuse older versions of the module are added.
921
922 Files older than v2.0 will have the one of the version numbers "-1",
923 "0" or "1".  No minor number was used at that time.
924
925 =item C<version_nv>
926
927 This returns the file format version as number.  It is a string like
928 "2.007".  This value is suitable for numeric comparisons.
929
930 The constant function C<Storable::BIN_VERSION_NV> returns a comparable
931 number that represents the highest file version number that this
932 version of Storable fully supports (but see discussion of
933 C<$Storable::accept_future_minor> above).  The constant
934 C<Storable::BIN_WRITE_VERSION_NV> function returns what file version
935 is written and might be less than C<Storable::BIN_VERSION_NV> in some
936 configurations.
937
938 =item C<major>, C<minor>
939
940 This also returns the file format version.  If the version is "2.7"
941 then major would be 2 and minor would be 7.  The minor element is
942 missing for when major is less than 2.
943
944 =item C<hdrsize>
945
946 The is the number of bytes that the Storable header occupies.
947
948 =item C<netorder>
949
950 This is TRUE if the image store data in network order.  This means
951 that it was created with nstore() or similar.
952
953 =item C<byteorder>
954
955 This is only present when C<netorder> is FALSE.  It is the
956 $Config{byteorder} string of the perl that created this image.  It is
957 a string like "1234" (32 bit little endian) or "87654321" (64 bit big
958 endian).  This must match the current perl for the image to be
959 readable by Storable.
960
961 =item C<intsize>, C<longsize>, C<ptrsize>, C<nvsize>
962
963 These are only present when C<netorder> is FALSE. These are the sizes of
964 various C datatypes of the perl that created this image.  These must
965 match the current perl for the image to be readable by Storable.
966
967 The C<nvsize> element is only present for file format v2.2 and
968 higher.
969
970 =item C<file>
971
972 The name of the file.
973
974 =back
975
976 =item $info = Storable::read_magic( $buffer )
977
978 =item $info = Storable::read_magic( $buffer, $must_be_file )
979
980 The $buffer should be a Storable image or the first few bytes of it.
981 If $buffer starts with a Storable header, then a hash describing the
982 image is returned, otherwise C<undef> is returned.
983
984 The hash has the same structure as the one returned by
985 Storable::file_magic().  The C<file> element is true if the image is a
986 file image.
987
988 If the $must_be_file argument is provided and is TRUE, then return
989 C<undef> unless the image looks like it belongs to a file dump.
990
991 The maximum size of a Storable header is currently 21 bytes.  If the
992 provided $buffer is only the first part of a Storable image it should
993 at least be this long to ensure that read_magic() will recognize it as
994 such.
995
996 =back
997
998 =head1 EXAMPLES
999
1000 Here are some code samples showing a possible usage of Storable:
1001
1002  use Storable qw(store retrieve freeze thaw dclone);
1003
1004  %color = ('Blue' => 0.1, 'Red' => 0.8, 'Black' => 0, 'White' => 1);
1005
1006  store(\%color, 'mycolors') or die "Can't store %a in mycolors!\n";
1007
1008  $colref = retrieve('mycolors');
1009  die "Unable to retrieve from mycolors!\n" unless defined $colref;
1010  printf "Blue is still %lf\n", $colref->{'Blue'};
1011
1012  $colref2 = dclone(\%color);
1013
1014  $str = freeze(\%color);
1015  printf "Serialization of %%color is %d bytes long.\n", length($str);
1016  $colref3 = thaw($str);
1017
1018 which prints (on my machine):
1019
1020  Blue is still 0.100000
1021  Serialization of %color is 102 bytes long.
1022
1023 Serialization of CODE references and deserialization in a safe
1024 compartment:
1025
1026 =for example begin
1027
1028  use Storable qw(freeze thaw);
1029  use Safe;
1030  use strict;
1031  my $safe = new Safe;
1032         # because of opcodes used in "use strict":
1033  $safe->permit(qw(:default require));
1034  local $Storable::Deparse = 1;
1035  local $Storable::Eval = sub { $safe->reval($_[0]) };
1036  my $serialized = freeze(sub { 42 });
1037  my $code = thaw($serialized);
1038  $code->() == 42;
1039
1040 =for example end
1041
1042 =for example_testing
1043         is( $code->(), 42 );
1044
1045 =head1 SECURITY WARNING
1046
1047 B<Do not accept Storable documents from untrusted sources!>
1048
1049 Some features of Storable can lead to security vulnerabilities if you
1050 accept Storable documents from untrusted sources with the default
1051 flags. Most obviously, the optional (off by default) CODE reference
1052 serialization feature allows transfer of code to the deserializing
1053 process. Furthermore, any serialized object will cause Storable to
1054 helpfully load the module corresponding to the class of the object in
1055 the deserializing module.  For manipulated module names, this can load
1056 almost arbitrary code.  Finally, the deserialized object's destructors
1057 will be invoked when the objects get destroyed in the deserializing
1058 process. Maliciously crafted Storable documents may put such objects
1059 in the value of a hash key that is overridden by another key/value
1060 pair in the same hash, thus causing immediate destructor execution.
1061
1062 To disable blessing objects while thawing/retrieving remove the flag
1063 BLESS_OK = 2 from C<$Storable::flags> or set the 2nd argument for
1064 thaw/retrieve to 0.
1065
1066 To disable tieing data while thawing/retrieving remove the flag TIE_OK
1067 = 4 from C<$Storable::flags> or set the 2nd argument for thaw/retrieve
1068 to 0.
1069
1070 With the default setting of $Storable::flags = 6, creating or destroying
1071 random objects, even renamed objects can be controlled by an attacker.
1072 See CVE-2015-1592 and its metasploit module.
1073
1074 If your application requires accepting data from untrusted sources, you
1075 are best off with a less powerful and more-likely safe serialization format
1076 and implementation. If your data is sufficiently simple, JSON is the best
1077 choice and offers maximum interoperability.
1078
1079 =head1 WARNING
1080
1081 If you're using references as keys within your hash tables, you're bound
1082 to be disappointed when retrieving your data. Indeed, Perl stringifies
1083 references used as hash table keys. If you later wish to access the
1084 items via another reference stringification (i.e. using the same
1085 reference that was used for the key originally to record the value into
1086 the hash table), it will work because both references stringify to the
1087 same string.
1088
1089 It won't work across a sequence of C<store> and C<retrieve> operations,
1090 however, because the addresses in the retrieved objects, which are
1091 part of the stringified references, will probably differ from the
1092 original addresses. The topology of your structure is preserved,
1093 but not hidden semantics like those.
1094
1095 On platforms where it matters, be sure to call C<binmode()> on the
1096 descriptors that you pass to Storable functions.
1097
1098 Storing data canonically that contains large hashes can be
1099 significantly slower than storing the same data normally, as
1100 temporary arrays to hold the keys for each hash have to be allocated,
1101 populated, sorted and freed.  Some tests have shown a halving of the
1102 speed of storing -- the exact penalty will depend on the complexity of
1103 your data.  There is no slowdown on retrieval.
1104
1105 =head1 BUGS
1106
1107 You can't store GLOB, FORMLINE, REGEXP, etc.... If you can define semantics
1108 for those operations, feel free to enhance Storable so that it can
1109 deal with them.
1110
1111 The store functions will C<croak> if they run into such references
1112 unless you set C<$Storable::forgive_me> to some C<TRUE> value. In that
1113 case, the fatal message is converted to a warning and some meaningless
1114 string is stored instead.
1115
1116 Setting C<$Storable::canonical> may not yield frozen strings that
1117 compare equal due to possible stringification of numbers. When the
1118 string version of a scalar exists, it is the form stored; therefore,
1119 if you happen to use your numbers as strings between two freezing
1120 operations on the same data structures, you will get different
1121 results.
1122
1123 When storing doubles in network order, their value is stored as text.
1124 However, you should also not expect non-numeric floating-point values
1125 such as infinity and "not a number" to pass successfully through a
1126 nstore()/retrieve() pair.
1127
1128 As Storable neither knows nor cares about character sets (although it
1129 does know that characters may be more than eight bits wide), any difference
1130 in the interpretation of character codes between a host and a target
1131 system is your problem.  In particular, if host and target use different
1132 code points to represent the characters used in the text representation
1133 of floating-point numbers, you will not be able be able to exchange
1134 floating-point data, even with nstore().
1135
1136 C<Storable::drop_utf8> is a blunt tool.  There is no facility either to
1137 return B<all> strings as utf8 sequences, or to attempt to convert utf8
1138 data back to 8 bit and C<croak()> if the conversion fails.
1139
1140 Prior to Storable 2.01, no distinction was made between signed and
1141 unsigned integers on storing.  By default Storable prefers to store a
1142 scalars string representation (if it has one) so this would only cause
1143 problems when storing large unsigned integers that had never been converted
1144 to string or floating point.  In other words values that had been generated
1145 by integer operations such as logic ops and then not used in any string or
1146 arithmetic context before storing.
1147
1148 =head2 Large data on 64-bit platforms
1149
1150 Storable's current data format is incapable of representing lengths greater
1151 than fit into a signed 32-bit integer, or about 2 GB. In practice, this
1152 means that, even with the latest Perl and a 64-bit machine with plenty of
1153 memory, you cannot store, retrieve, or clone any of the following:
1154
1155 =over 4
1156
1157 =item *
1158
1159 A string containing 2**31 or more bytes (including as an element of an array, or
1160 a key or value in a hash)
1161
1162 =item *
1163
1164 An array with 2**31 or more elements
1165
1166 =item *
1167
1168 A hash with 2**31 or more keys
1169
1170 =back
1171
1172 Attempting to do so will yield an exception.
1173
1174 This may be fixed in the future.
1175
1176 =head2 64 bit data in perl 5.6.0 and 5.6.1
1177
1178 This section only applies to you if you have existing data written out
1179 by Storable 2.02 or earlier on perl 5.6.0 or 5.6.1 on Unix or Linux which
1180 has been configured with 64 bit integer support (not the default)
1181 If you got a precompiled perl, rather than running Configure to build
1182 your own perl from source, then it almost certainly does not affect you,
1183 and you can stop reading now (unless you're curious). If you're using perl
1184 on Windows it does not affect you.
1185
1186 Storable writes a file header which contains the sizes of various C
1187 language types for the C compiler that built Storable (when not writing in
1188 network order), and will refuse to load files written by a Storable not
1189 on the same (or compatible) architecture.  This check and a check on
1190 machine byteorder is needed because the size of various fields in the file
1191 are given by the sizes of the C language types, and so files written on
1192 different architectures are incompatible.  This is done for increased speed.
1193 (When writing in network order, all fields are written out as standard
1194 lengths, which allows full interworking, but takes longer to read and write)
1195
1196 Perl 5.6.x introduced the ability to optional configure the perl interpreter
1197 to use C's C<long long> type to allow scalars to store 64 bit integers on 32
1198 bit systems.  However, due to the way the Perl configuration system
1199 generated the C configuration files on non-Windows platforms, and the way
1200 Storable generates its header, nothing in the Storable file header reflected
1201 whether the perl writing was using 32 or 64 bit integers, despite the fact
1202 that Storable was storing some data differently in the file.  Hence Storable
1203 running on perl with 64 bit integers will read the header from a file
1204 written by a 32 bit perl, not realise that the data is actually in a subtly
1205 incompatible format, and then go horribly wrong (possibly crashing) if it
1206 encountered a stored integer.  This is a design failure.
1207
1208 Storable has now been changed to write out and read in a file header with
1209 information about the size of integers.  It's impossible to detect whether
1210 an old file being read in was written with 32 or 64 bit integers (they have
1211 the same header) so it's impossible to automatically switch to a correct
1212 backwards compatibility mode.  Hence this Storable defaults to the new,
1213 correct behaviour.
1214
1215 What this means is that if you have data written by Storable 1.x running
1216 on perl 5.6.0 or 5.6.1 configured with 64 bit integers on Unix or Linux
1217 then by default this Storable will refuse to read it, giving the error
1218 I<Byte order is not compatible>.  If you have such data then you
1219 should set C<$Storable::interwork_56_64bit> to a true value to make this
1220 Storable read and write files with the old header.  You should also
1221 migrate your data, or any older perl you are communicating with, to this
1222 current version of Storable.
1223
1224 If you don't have data written with specific configuration of perl described
1225 above, then you do not and should not do anything.  Don't set the flag -
1226 not only will Storable on an identically configured perl refuse to load them,
1227 but Storable a differently configured perl will load them believing them
1228 to be correct for it, and then may well fail or crash part way through
1229 reading them.
1230
1231 =head1 CREDITS
1232
1233 Thank you to (in chronological order):
1234
1235         Jarkko Hietaniemi <jhi@iki.fi>
1236         Ulrich Pfeifer <pfeifer@charly.informatik.uni-dortmund.de>
1237         Benjamin A. Holzman <bholzman@earthlink.net>
1238         Andrew Ford <A.Ford@ford-mason.co.uk>
1239         Gisle Aas <gisle@aas.no>
1240         Jeff Gresham <gresham_jeffrey@jpmorgan.com>
1241         Murray Nesbitt <murray@activestate.com>
1242         Marc Lehmann <pcg@opengroup.org>
1243         Justin Banks <justinb@wamnet.com>
1244         Jarkko Hietaniemi <jhi@iki.fi> (AGAIN, as perl 5.7.0 Pumpkin!)
1245         Salvador Ortiz Garcia <sog@msg.com.mx>
1246         Dominic Dunlop <domo@computer.org>
1247         Erik Haugan <erik@solbors.no>
1248         Benjamin A. Holzman <ben.holzman@grantstreet.com>
1249         Reini Urban <rurban@cpanel.net>
1250         Todd Rinaldo <toddr@cpanel.net>
1251         Aaron Crane <arc@cpan.org>
1252
1253 for their bug reports, suggestions and contributions.
1254
1255 Benjamin Holzman contributed the tied variable support, Andrew Ford
1256 contributed the canonical order for hashes, and Gisle Aas fixed
1257 a few misunderstandings of mine regarding the perl internals,
1258 and optimized the emission of "tags" in the output streams by
1259 simply counting the objects instead of tagging them (leading to
1260 a binary incompatibility for the Storable image starting at version
1261 0.6--older images are, of course, still properly understood).
1262 Murray Nesbitt made Storable thread-safe.  Marc Lehmann added overloading
1263 and references to tied items support.  Benjamin Holzman added a performance
1264 improvement for overloaded classes; thanks to Grant Street Group for footing
1265 the bill.
1266
1267 =head1 AUTHOR
1268
1269 Storable was written by Raphael Manfredi
1270 F<E<lt>Raphael_Manfredi@pobox.comE<gt>>
1271 Maintenance is now done by the perl5-porters
1272 F<E<lt>perl5-porters@perl.orgE<gt>>
1273
1274 Please e-mail us with problems, bug fixes, comments and complaints,
1275 although if you have compliments you should send them to Raphael.
1276 Please don't e-mail Raphael with problems, as he no longer works on
1277 Storable, and your message will be delayed while he forwards it to us.
1278
1279 =head1 SEE ALSO
1280
1281 L<Clone>.
1282
1283 =cut