This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
[perl #72062] Untaint DATA after it's reopened
[perl5.git] / dist / SelfLoader / lib / SelfLoader.pm
1 package SelfLoader;
2 use 5.008;
3 use strict;
4 use IO::Handle;
5 our $VERSION = "1.18";
6
7 # The following bit of eval-magic is necessary to make this work on
8 # perls < 5.009005.
9 use vars qw/$AttrList/;
10 BEGIN {
11   if ($] > 5.009004) {
12     eval <<'NEWERPERL';
13 use 5.009005; # due to new regexp features
14 # allow checking for valid ': attrlist' attachments
15 # see also AutoSplit
16 $AttrList = qr{
17     \s* : \s*
18     (?:
19         # one attribute
20         (?> # no backtrack
21             (?! \d) \w+
22             (?<nested> \( (?: [^()]++ | (?&nested)++ )*+ \) ) ?
23         )
24         (?: \s* : \s* | \s+ (?! :) )
25     )*
26 }x;
27
28 NEWERPERL
29   }
30   else {
31     eval <<'OLDERPERL';
32 # allow checking for valid ': attrlist' attachments
33 # (we use 'our' rather than 'my' here, due to the rather complex and buggy
34 # behaviour of lexicals with qr// and (??{$lex}) )
35 our $nested;
36 $nested = qr{ \( (?: (?> [^()]+ ) | (??{ $nested }) )* \) }x;
37 our $one_attr = qr{ (?> (?! \d) \w+ (?:$nested)? ) (?:\s*\:\s*|\s+(?!\:)) }x;
38 $AttrList = qr{ \s* : \s* (?: $one_attr )* }x;
39 OLDERPERL
40   }
41 }
42 use Exporter;
43 our @ISA = qw(Exporter);
44 our @EXPORT = qw(AUTOLOAD);
45 sub Version {$VERSION}
46 sub DEBUG () { 0 }
47
48 my %Cache;      # private cache for all SelfLoader's client packages
49
50 # in croak and carp, protect $@ from "require Carp;" RT #40216
51
52 sub croak { { local $@; require Carp; } goto &Carp::croak }
53 sub carp { { local $@; require Carp; } goto &Carp::carp }
54
55 AUTOLOAD {
56     our $AUTOLOAD;
57     print STDERR "SelfLoader::AUTOLOAD for $AUTOLOAD\n" if DEBUG;
58     my $SL_code = $Cache{$AUTOLOAD};
59     my $save = $@; # evals in both AUTOLOAD and _load_stubs can corrupt $@
60     unless ($SL_code) {
61         # Maybe this pack had stubs before __DATA__, and never initialized.
62         # Or, this maybe an automatic DESTROY method call when none exists.
63         $AUTOLOAD =~ m/^(.*)::/;
64         SelfLoader->_load_stubs($1) unless exists $Cache{"${1}::<DATA"};
65         $SL_code = $Cache{$AUTOLOAD};
66         $SL_code = "sub $AUTOLOAD { }"
67             if (!$SL_code and $AUTOLOAD =~ m/::DESTROY$/);
68         croak "Undefined subroutine $AUTOLOAD" unless $SL_code;
69     }
70     print STDERR "SelfLoader::AUTOLOAD eval: $SL_code\n" if DEBUG;
71
72     {
73         no strict;
74         eval $SL_code;
75     }
76     if ($@) {
77         $@ =~ s/ at .*\n//;
78         croak $@;
79     }
80     $@ = $save;
81     defined(&$AUTOLOAD) || die "SelfLoader inconsistency error";
82     delete $Cache{$AUTOLOAD};
83     goto &$AUTOLOAD
84 }
85
86 sub load_stubs { shift->_load_stubs((caller)[0]) }
87
88 sub _load_stubs {
89     # $endlines is used by Devel::SelfStubber to capture lines after __END__
90     my($self, $callpack, $endlines) = @_;
91     no strict "refs";
92     my $fh = \*{"${callpack}::DATA"};
93     use strict;
94     my $currpack = $callpack;
95     my($line,$name,@lines, @stubs, $protoype);
96
97     print STDERR "SelfLoader::load_stubs($callpack)\n" if DEBUG;
98     croak("$callpack doesn't contain an __DATA__ token")
99         unless defined fileno($fh);
100     # Protect: fork() shares the file pointer between the parent and the kid
101     if(sysseek($fh, tell($fh), 0)) {
102       open my $nfh, '<&', $fh or croak "reopen: $!";# dup() the fd
103       close $fh or die "close: $!";                 # autocloses, but be paranoid
104       open $fh, '<&', $nfh or croak "reopen2: $!";  # dup() the fd "back"
105       close $nfh or die "close after reopen: $!";   # autocloses, but be paranoid
106       $fh->untaint;
107     }
108     $Cache{"${currpack}::<DATA"} = 1;   # indicate package is cached
109
110     local($/) = "\n";
111     while(defined($line = <$fh>) and $line !~ m/^__END__/) {
112         if ($line =~ m/^\s*sub\s+([\w:]+)\s*((?:\([\\\$\@\%\&\*\;]*\))?(?:$AttrList)?)/) {
113             push(@stubs, $self->_add_to_cache($name, $currpack, \@lines, $protoype));
114             $protoype = $2;
115             @lines = ($line);
116             if (index($1,'::') == -1) {         # simple sub name
117                 $name = "${currpack}::$1";
118             } else {                            # sub name with package
119                 $name = $1;
120                 $name =~ m/^(.*)::/;
121                 if (defined(&{"${1}::AUTOLOAD"})) {
122                     \&{"${1}::AUTOLOAD"} == \&SelfLoader::AUTOLOAD ||
123                         die 'SelfLoader Error: attempt to specify Selfloading',
124                             " sub $name in non-selfloading module $1";
125                 } else {
126                     $self->export($1,'AUTOLOAD');
127                 }
128             }
129         } elsif ($line =~ m/^package\s+([\w:]+)/) { # A package declared
130             push(@stubs, $self->_add_to_cache($name, $currpack, \@lines, $protoype));
131             $self->_package_defined($line);
132             $name = '';
133             @lines = ();
134             $currpack = $1;
135             $Cache{"${currpack}::<DATA"} = 1;   # indicate package is cached
136             if (defined(&{"${1}::AUTOLOAD"})) {
137                 \&{"${1}::AUTOLOAD"} == \&SelfLoader::AUTOLOAD ||
138                     die 'SelfLoader Error: attempt to specify Selfloading',
139                         " package $currpack which already has AUTOLOAD";
140             } else {
141                 $self->export($currpack,'AUTOLOAD');
142             }
143         } else {
144             push(@lines,$line);
145         }
146     }
147     if (defined($line) && $line =~ /^__END__/) { # __END__
148         unless ($line =~ /^__END__\s*DATA/) {
149             if ($endlines) {
150                 # Devel::SelfStubber would like us to capture the lines after
151                 # __END__ so it can write out the entire file
152                 @$endlines = <$fh>;
153             }
154             close($fh);
155         }
156     }
157     push(@stubs, $self->_add_to_cache($name, $currpack, \@lines, $protoype));
158     no strict;
159     eval join('', @stubs) if @stubs;
160 }
161
162
163 sub _add_to_cache {
164     my($self,$fullname,$pack,$lines, $protoype) = @_;
165     return () unless $fullname;
166     carp("Redefining sub $fullname")
167       if exists $Cache{$fullname};
168     $Cache{$fullname} = join('', "\n\#line 1 \"sub $fullname\"\npackage $pack; ", @$lines);
169     #$Cache{$fullname} = join('', "package $pack; ",@$lines);
170     print STDERR "SelfLoader cached $fullname: $Cache{$fullname}" if DEBUG;
171     # return stub to be eval'd
172     defined($protoype) ? "sub $fullname $protoype;" : "sub $fullname;"
173 }
174
175 sub _package_defined {}
176
177 1;
178 __END__
179
180 =head1 NAME
181
182 SelfLoader - load functions only on demand
183
184 =head1 SYNOPSIS
185
186     package FOOBAR;
187     use SelfLoader;
188
189     ... (initializing code)
190
191     __DATA__
192     sub {....
193
194
195 =head1 DESCRIPTION
196
197 This module tells its users that functions in the FOOBAR package are to be
198 autoloaded from after the C<__DATA__> token.  See also
199 L<perlsub/"Autoloading">.
200
201 =head2 The __DATA__ token
202
203 The C<__DATA__> token tells the perl compiler that the perl code
204 for compilation is finished. Everything after the C<__DATA__> token
205 is available for reading via the filehandle FOOBAR::DATA,
206 where FOOBAR is the name of the current package when the C<__DATA__>
207 token is reached. This works just the same as C<__END__> does in
208 package 'main', but for other modules data after C<__END__> is not
209 automatically retrievable, whereas data after C<__DATA__> is.
210 The C<__DATA__> token is not recognized in versions of perl prior to
211 5.001m.
212
213 Note that it is possible to have C<__DATA__> tokens in the same package
214 in multiple files, and that the last C<__DATA__> token in a given
215 package that is encountered by the compiler is the one accessible
216 by the filehandle. This also applies to C<__END__> and main, i.e. if
217 the 'main' program has an C<__END__>, but a module 'require'd (_not_ 'use'd)
218 by that program has a 'package main;' declaration followed by an 'C<__DATA__>',
219 then the C<DATA> filehandle is set to access the data after the C<__DATA__>
220 in the module, _not_ the data after the C<__END__> token in the 'main'
221 program, since the compiler encounters the 'require'd file later.
222
223 =head2 SelfLoader autoloading
224
225 The B<SelfLoader> works by the user placing the C<__DATA__>
226 token I<after> perl code which needs to be compiled and
227 run at 'require' time, but I<before> subroutine declarations
228 that can be loaded in later - usually because they may never
229 be called.
230
231 The B<SelfLoader> will read from the FOOBAR::DATA filehandle to
232 load in the data after C<__DATA__>, and load in any subroutine
233 when it is called. The costs are the one-time parsing of the
234 data after C<__DATA__>, and a load delay for the _first_
235 call of any autoloaded function. The benefits (hopefully)
236 are a speeded up compilation phase, with no need to load
237 functions which are never used.
238
239 The B<SelfLoader> will stop reading from C<__DATA__> if
240 it encounters the C<__END__> token - just as you would expect.
241 If the C<__END__> token is present, and is followed by the
242 token DATA, then the B<SelfLoader> leaves the FOOBAR::DATA
243 filehandle open on the line after that token.
244
245 The B<SelfLoader> exports the C<AUTOLOAD> subroutine to the
246 package using the B<SelfLoader>, and this loads the called
247 subroutine when it is first called.
248
249 There is no advantage to putting subroutines which will _always_
250 be called after the C<__DATA__> token.
251
252 =head2 Autoloading and package lexicals
253
254 A 'my $pack_lexical' statement makes the variable $pack_lexical
255 local _only_ to the file up to the C<__DATA__> token. Subroutines
256 declared elsewhere _cannot_ see these types of variables,
257 just as if you declared subroutines in the package but in another
258 file, they cannot see these variables.
259
260 So specifically, autoloaded functions cannot see package
261 lexicals (this applies to both the B<SelfLoader> and the Autoloader).
262 The C<vars> pragma provides an alternative to defining package-level
263 globals that will be visible to autoloaded routines. See the documentation
264 on B<vars> in the pragma section of L<perlmod>.
265
266 =head2 SelfLoader and AutoLoader
267
268 The B<SelfLoader> can replace the AutoLoader - just change 'use AutoLoader'
269 to 'use SelfLoader' (though note that the B<SelfLoader> exports
270 the AUTOLOAD function - but if you have your own AUTOLOAD and
271 are using the AutoLoader too, you probably know what you're doing),
272 and the C<__END__> token to C<__DATA__>. You will need perl version 5.001m
273 or later to use this (version 5.001 with all patches up to patch m).
274
275 There is no need to inherit from the B<SelfLoader>.
276
277 The B<SelfLoader> works similarly to the AutoLoader, but picks up the
278 subs from after the C<__DATA__> instead of in the 'lib/auto' directory.
279 There is a maintenance gain in not needing to run AutoSplit on the module
280 at installation, and a runtime gain in not needing to keep opening and
281 closing files to load subs. There is a runtime loss in needing
282 to parse the code after the C<__DATA__>. Details of the B<AutoLoader> and
283 another view of these distinctions can be found in that module's
284 documentation.
285
286 =head2 __DATA__, __END__, and the FOOBAR::DATA filehandle.
287
288 This section is only relevant if you want to use
289 the C<FOOBAR::DATA> together with the B<SelfLoader>.
290
291 Data after the C<__DATA__> token in a module is read using the
292 FOOBAR::DATA filehandle. C<__END__> can still be used to denote the end
293 of the C<__DATA__> section if followed by the token DATA - this is supported
294 by the B<SelfLoader>. The C<FOOBAR::DATA> filehandle is left open if an
295 C<__END__> followed by a DATA is found, with the filehandle positioned at
296 the start of the line after the C<__END__> token. If no C<__END__> token is
297 present, or an C<__END__> token with no DATA token on the same line, then
298 the filehandle is closed.
299
300 The B<SelfLoader> reads from wherever the current
301 position of the C<FOOBAR::DATA> filehandle is, until the
302 EOF or C<__END__>. This means that if you want to use
303 that filehandle (and ONLY if you want to), you should either
304
305 1. Put all your subroutine declarations immediately after
306 the C<__DATA__> token and put your own data after those
307 declarations, using the C<__END__> token to mark the end
308 of subroutine declarations. You must also ensure that the B<SelfLoader>
309 reads first by  calling 'SelfLoader-E<gt>load_stubs();', or by using a
310 function which is selfloaded;
311
312 or
313
314 2. You should read the C<FOOBAR::DATA> filehandle first, leaving
315 the handle open and positioned at the first line of subroutine
316 declarations.
317
318 You could conceivably do both.
319
320 =head2 Classes and inherited methods.
321
322 For modules which are not classes, this section is not relevant.
323 This section is only relevant if you have methods which could
324 be inherited.
325
326 A subroutine stub (or forward declaration) looks like
327
328   sub stub;
329
330 i.e. it is a subroutine declaration without the body of the
331 subroutine. For modules which are not classes, there is no real
332 need for stubs as far as autoloading is concerned.
333
334 For modules which ARE classes, and need to handle inherited methods,
335 stubs are needed to ensure that the method inheritance mechanism works
336 properly. You can load the stubs into the module at 'require' time, by
337 adding the statement 'SelfLoader-E<gt>load_stubs();' to the module to do
338 this.
339
340 The alternative is to put the stubs in before the C<__DATA__> token BEFORE
341 releasing the module, and for this purpose the C<Devel::SelfStubber>
342 module is available.  However this does require the extra step of ensuring
343 that the stubs are in the module. If this is done I strongly recommend
344 that this is done BEFORE releasing the module - it should NOT be done
345 at install time in general.
346
347 =head1 Multiple packages and fully qualified subroutine names
348
349 Subroutines in multiple packages within the same file are supported - but you
350 should note that this requires exporting the C<SelfLoader::AUTOLOAD> to
351 every package which requires it. This is done automatically by the
352 B<SelfLoader> when it first loads the subs into the cache, but you should
353 really specify it in the initialization before the C<__DATA__> by putting
354 a 'use SelfLoader' statement in each package.
355
356 Fully qualified subroutine names are also supported. For example,
357
358    __DATA__
359    sub foo::bar {23}
360    package baz;
361    sub dob {32}
362
363 will all be loaded correctly by the B<SelfLoader>, and the B<SelfLoader>
364 will ensure that the packages 'foo' and 'baz' correctly have the
365 B<SelfLoader> C<AUTOLOAD> method when the data after C<__DATA__> is first
366 parsed.
367
368 =head1 AUTHOR
369
370 C<SelfLoader> is maintained by the perl5-porters. Please direct
371 any questions to the canonical mailing list. Anything that
372 is applicable to the CPAN release can be sent to its maintainer,
373 though.
374
375 Author and Maintainer: The Perl5-Porters <perl5-porters@perl.org>
376
377 Maintainer of the CPAN release: Steffen Mueller <smueller@cpan.org>
378
379 =head1 COPYRIGHT AND LICENSE
380
381 This package has been part of the perl core since the first release
382 of perl5. It has been released separately to CPAN so older installations
383 can benefit from bug fixes.
384
385 This package has the same copyright and license as the perl core:
386
387              Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999,
388         2000, 2001, 2002, 2003, 2004, 2005, 2006 by Larry Wall and others
389     
390                             All rights reserved.
391     
392     This program is free software; you can redistribute it and/or modify
393     it under the terms of either:
394     
395         a) the GNU General Public License as published by the Free
396         Software Foundation; either version 1, or (at your option) any
397         later version, or
398     
399         b) the "Artistic License" which comes with this Kit.
400     
401     This program is distributed in the hope that it will be useful,
402     but WITHOUT ANY WARRANTY; without even the implied warranty of
403     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See either
404     the GNU General Public License or the Artistic License for more details.
405     
406     You should have received a copy of the Artistic License with this
407     Kit, in the file named "Artistic".  If not, I'll be glad to provide one.
408     
409     You should also have received a copy of the GNU General Public License
410     along with this program in the file named "Copying". If not, write to the 
411     Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 
412     02111-1307, USA or visit their web page on the internet at
413     http://www.gnu.org/copyleft/gpl.html.
414     
415     For those of you that choose to use the GNU General Public License,
416     my interpretation of the GNU General Public License is that no Perl
417     script falls under the terms of the GPL unless you explicitly put
418     said script under the terms of the GPL yourself.  Furthermore, any
419     object code linked with perl does not automatically fall under the
420     terms of the GPL, provided such object code only adds definitions
421     of subroutines and variables, and does not otherwise impair the
422     resulting interpreter from executing any standard Perl script.  I
423     consider linking in C subroutines in this manner to be the moral
424     equivalent of defining subroutines in the Perl language itself.  You
425     may sell such an object file as proprietary provided that you provide
426     or offer to provide the Perl source, as specified by the GNU General
427     Public License.  (This is merely an alternate way of specifying input
428     to the program.)  You may also sell a binary produced by the dumping of
429     a running Perl script that belongs to you, provided that you provide or
430     offer to provide the Perl source as specified by the GPL.  (The
431     fact that a Perl interpreter and your code are in the same binary file
432     is, in this case, a form of mere aggregation.)  This is my interpretation
433     of the GPL.  If you still have concerns or difficulties understanding
434     my intent, feel free to contact me.  Of course, the Artistic License
435     spells all this out for your protection, so you may prefer to use that.
436
437 =cut