File Coverage

blib/lib/Module/Runtime.pm
Criterion Covered Total %
statement 55 55 100.0
branch 30 32 93.7
condition 11 15 73.3
subroutine 15 15 100.0
pod 9 9 100.0
total 120 126 95.2


line stmt bran cond sub pod time code
1             =head1 NAME
2              
3             Module::Runtime - runtime module handling
4              
5             =head1 SYNOPSIS
6              
7             use Module::Runtime qw(
8             $module_name_rx is_module_name check_module_name
9             module_notional_filename require_module);
10              
11             if($module_name =~ /\A$module_name_rx\z/o) { ...
12             if(is_module_name($module_name)) { ...
13             check_module_name($module_name);
14              
15             $notional_filename = module_notional_filename($module_name);
16             require_module($module_name);
17              
18             use Module::Runtime qw(use_module use_package_optimistically);
19              
20             $bi = use_module("Math::BigInt", 1.31)->new("1_234");
21             $widget = use_package_optimistically("Local::Widget")->new;
22              
23             use Module::Runtime qw(
24             $top_module_spec_rx $sub_module_spec_rx
25             is_module_spec check_module_spec
26             compose_module_name);
27              
28             if($spec =~ /\A$top_module_spec_rx\z/o) { ...
29             if($spec =~ /\A$sub_module_spec_rx\z/o) { ...
30             if(is_module_spec("Standard::Prefix", $spec)) { ...
31             check_module_spec("Standard::Prefix", $spec);
32              
33             $module_name = compose_module_name("Standard::Prefix", $spec);
34              
35             =head1 DESCRIPTION
36              
37             The functions exported by this module deal with runtime handling of
38             Perl modules, which are normally handled at compile time. This module
39             avoids using any other modules, so that it can be used in low-level
40             infrastructure.
41              
42             The parts of this module that work with module names apply the same syntax
43             that is used for barewords in Perl source. In principle this syntax
44             can vary between versions of Perl, and this module applies the syntax of
45             the Perl on which it is running. In practice the usable syntax hasn't
46             changed yet. There's some intent for Unicode module names to be supported
47             in the future, but this hasn't yet amounted to any consistent facility.
48              
49             The functions of this module whose purpose is to load modules include
50             workarounds for three old Perl core bugs regarding C. These
51             workarounds are applied on any Perl version where the bugs exist, except
52             for a case where one of the bugs cannot be adequately worked around in
53             pure Perl.
54              
55             =head2 Module name syntax
56              
57             The usable module name syntax has not changed from Perl 5.000 up to
58             Perl 5.19.8. The syntax is composed entirely of ASCII characters.
59             From Perl 5.6 onwards there has been some attempt to allow the use of
60             non-ASCII Unicode characters in Perl source, but it was fundamentally
61             broken (like the entirety of Perl 5.6's Unicode handling) and remained
62             pretty much entirely unusable until it got some attention in the Perl
63             5.15 series. Although Unicode is now consistently accepted by the
64             parser in some places, it remains broken for module names. Furthermore,
65             there has not yet been any work on how to map Unicode module names into
66             filenames, so in that respect also Unicode module names are unusable.
67              
68             The module name syntax is, precisely: the string must consist of one or
69             more segments separated by C<::>; each segment must consist of one or more
70             identifier characters (ASCII alphanumerics plus "_"); the first character
71             of the string must not be a digit. Thus "C", "C",
72             and "C" are all valid module names, whereas "C"
73             and "C<1foo::bar>" are not. C<'> separators are not permitted by this
74             module, though they remain usable in Perl source, being translated to
75             C<::> in the parser.
76              
77             =head2 Core bugs worked around
78              
79             The first bug worked around is core bug [perl #68590], which causes
80             lexical state in one file to leak into another that is Cd/Cd
81             from it. This bug is present from Perl 5.6 up to Perl 5.10, and is
82             fixed in Perl 5.11.0. From Perl 5.9.4 up to Perl 5.10.0 no satisfactory
83             workaround is possible in pure Perl. The workaround means that modules
84             loaded via this module don't suffer this pollution of their lexical
85             state. Modules loaded in other ways, or via this module on the Perl
86             versions where the pure Perl workaround is impossible, remain vulnerable.
87             The module L provides a complete workaround
88             for this bug.
89              
90             The second bug worked around causes some kinds of failure in module
91             loading, principally compilation errors in the loaded module, to be
92             recorded in C<%INC> as if they were successful, so later attempts to load
93             the same module immediately indicate success. This bug is present up
94             to Perl 5.8.9, and is fixed in Perl 5.9.0. The workaround means that a
95             compilation error in a module loaded via this module won't be cached as
96             a success. Modules loaded in other ways remain liable to produce bogus
97             C<%INC> entries, and if a bogus entry exists then it will mislead this
98             module if it is used to re-attempt loading.
99              
100             The third bug worked around causes the wrong context to be seen at
101             file scope of a loaded module, if C is invoked in a location
102             that inherits context from a higher scope. This bug is present up to
103             Perl 5.11.2, and is fixed in Perl 5.11.3. The workaround means that
104             a module loaded via this module will always see the correct context.
105             Modules loaded in other ways remain vulnerable.
106              
107             =cut
108              
109             package Module::Runtime;
110              
111             # Don't "use 5.006" here, because Perl 5.15.6 will load feature.pm if
112             # the version check is done that way.
113 11     11   522552 BEGIN { require 5.006; }
114             # Don't "use warnings" here, to avoid dependencies. Do standardise the
115             # warning status by lexical override; unfortunately the only safe bitset
116             # to build in is the empty set, equivalent to "no warnings".
117 11     11   8634 BEGIN { ${^WARNING_BITS} = ""; }
118             # Don't "use strict" here, to avoid dependencies.
119              
120             our $VERSION = "0.016";
121              
122             # Don't use Exporter here, to avoid dependencies.
123             our @EXPORT_OK = qw(
124             $module_name_rx is_module_name is_valid_module_name check_module_name
125             module_notional_filename require_module
126             use_module use_package_optimistically
127             $top_module_spec_rx $sub_module_spec_rx
128             is_module_spec is_valid_module_spec check_module_spec
129             compose_module_name
130             );
131             my %export_ok = map { ($_ => undef) } @EXPORT_OK;
132             sub import {
133 15     15   1646 my $me = shift;
134 15         41 my $callpkg = caller(0);
135 15         34 my $errs = "";
136 15         42 foreach(@_) {
137 26 100       80 if(exists $export_ok{$_}) {
138             # We would need to do "no strict 'refs'" here
139             # if we had enabled strict at file scope.
140 22 100       82 if(/\A\$(.*)\z/s) {
141 3         15 *{$callpkg."::".$1} = \$$1;
  3         23  
142             } else {
143 19         43 *{$callpkg."::".$_} = \&$_;
  19         112  
144             }
145             } else {
146 4         11 $errs .= "\"$_\" is not exported by the $me module\n";
147             }
148             }
149 15 100       319 if($errs ne "") {
150 3         6 die "${errs}Can't continue after import errors ".
151 3         19 "at @{[(caller(0))[1]]} line @{[(caller(0))[2]]}.\n";
  3         46  
152             }
153             }
154              
155             # Logic duplicated from Params::Classify. Duplicating it here avoids
156             # an extensive and potentially circular dependency graph.
157             sub _is_string($) {
158 307     307   857 my($arg) = @_;
159 307   100     4871 return defined($arg) && ref(\$arg) eq "SCALAR";
160             }
161              
162             =head1 REGULAR EXPRESSIONS
163              
164             These regular expressions do not include any anchors, so to check
165             whether an entire string matches a syntax item you must supply the
166             anchors yourself.
167              
168             =over
169              
170             =item $module_name_rx
171              
172             Matches a valid Perl module name in bareword syntax.
173              
174             =cut
175              
176             our $module_name_rx = qr/[A-Z_a-z][0-9A-Z_a-z]*(?:::[0-9A-Z_a-z]+)*/;
177              
178             =item $top_module_spec_rx
179              
180             Matches a module specification for use with L,
181             where no prefix is being used.
182              
183             =cut
184              
185             my $qual_module_spec_rx =
186             qr#(?:/|::)[A-Z_a-z][0-9A-Z_a-z]*(?:(?:/|::)[0-9A-Z_a-z]+)*#;
187              
188             my $unqual_top_module_spec_rx =
189             qr#[A-Z_a-z][0-9A-Z_a-z]*(?:(?:/|::)[0-9A-Z_a-z]+)*#;
190              
191             our $top_module_spec_rx = qr/$qual_module_spec_rx|$unqual_top_module_spec_rx/o;
192              
193             =item $sub_module_spec_rx
194              
195             Matches a module specification for use with L,
196             where a prefix is being used.
197              
198             =cut
199              
200             my $unqual_sub_module_spec_rx = qr#[0-9A-Z_a-z]+(?:(?:/|::)[0-9A-Z_a-z]+)*#;
201              
202             our $sub_module_spec_rx = qr/$qual_module_spec_rx|$unqual_sub_module_spec_rx/o;
203              
204             =back
205              
206             =head1 FUNCTIONS
207              
208             =head2 Basic module handling
209              
210             =over
211              
212             =item is_module_name(ARG)
213              
214             Returns a truth value indicating whether I is a plain string
215             satisfying Perl module name syntax as described for L.
216              
217             =cut
218              
219 151 100   151 1 11446 sub is_module_name($) { _is_string($_[0]) && $_[0] =~ /\A$module_name_rx\z/o }
220              
221             =item is_valid_module_name(ARG)
222              
223             Deprecated alias for L.
224              
225             =cut
226              
227             *is_valid_module_name = \&is_module_name;
228              
229             =item check_module_name(ARG)
230              
231             Check whether I is a plain string
232             satisfying Perl module name syntax as described for L.
233             Return normally if it is, or C if it is not.
234              
235             =cut
236              
237             sub check_module_name($) {
238 134 100   134 1 248 unless(&is_module_name) {
239 12 100       27 die +(_is_string($_[0]) ? "`$_[0]'" : "argument").
240             " is not a module name\n";
241             }
242             }
243              
244             =item module_notional_filename(NAME)
245              
246             Generates a notional relative filename for a module, which is used in
247             some Perl core interfaces.
248             The I is a string, which should be a valid module name (one or
249             more C<::>-separated segments). If it is not a valid name, the function
250             Cs.
251              
252             The notional filename for the named module is generated and returned.
253             This filename is always in Unix style, with C directory separators
254             and a C<.pm> suffix. This kind of filename can be used as an argument to
255             C, and is the key that appears in C<%INC> to identify a module,
256             regardless of actual local filename syntax.
257              
258             =cut
259              
260             sub module_notional_filename($) {
261 109     109 1 358 &check_module_name;
262 109         311 my($name) = @_;
263 109         419 $name =~ s!::!/!g;
264 109         10875 return $name.".pm";
265             }
266              
267             =item require_module(NAME)
268              
269             This is essentially the bareword form of C, in runtime form.
270             The I is a string, which should be a valid module name (one or
271             more C<::>-separated segments). If it is not a valid name, the function
272             Cs.
273              
274             The module specified by I is loaded, if it hasn't been already,
275             in the manner of the bareword form of C. That means that a
276             search through C<@INC> is performed, and a byte-compiled form of the
277             module will be used if available.
278              
279             The return value is as for C. That is, it is the value returned
280             by the module itself if the module is loaded anew, or C<1> if the module
281             was already loaded.
282              
283             =cut
284              
285             # Don't "use constant" here, to avoid dependencies.
286             BEGIN {
287             *_WORK_AROUND_HINT_LEAKAGE =
288             "$]" < 5.011 && !("$]" >= 5.009004 && "$]" < 5.010001)
289 11 50 33 11   141 ? sub(){1} : sub(){0};
290 11 50       503 *_WORK_AROUND_BROKEN_MODULE_STATE = "$]" < 5.009 ? sub(){1} : sub(){0};
291             }
292              
293 11     11   5954 BEGIN { if(_WORK_AROUND_BROKEN_MODULE_STATE) { eval q{
294             sub Module::Runtime::__GUARD__::DESTROY {
295             delete $INC{$_[0]->[0]} if @{$_[0]};
296             }
297             1;
298             }; die $@ if $@ ne ""; } }
299              
300             sub require_module($) {
301             # Localise %^H to work around [perl #68590], where the bug exists
302             # and this is a satisfactory workaround. The bug consists of
303             # %^H state leaking into each required module, polluting the
304             # module's lexical state.
305 68     68 1 33323 local %^H if _WORK_AROUND_HINT_LEAKAGE;
306 68         119 if(_WORK_AROUND_BROKEN_MODULE_STATE) {
307             my $notional_filename = &module_notional_filename;
308             my $guard = bless([ $notional_filename ],
309             "Module::Runtime::__GUARD__");
310             my $result = CORE::require($notional_filename);
311             pop @$guard;
312             return $result;
313             } else {
314 68         141 return scalar(CORE::require(&module_notional_filename));
315             }
316             }
317              
318             =back
319              
320             =head2 Structured module use
321              
322             =over
323              
324             =item use_module(NAME[, VERSION])
325              
326             This is essentially C in runtime form, but without the importing
327             feature (which is fundamentally a compile-time thing). The I is
328             handled just like in C above: it must be a module name,
329             and the named module is loaded as if by the bareword form of C.
330              
331             If a I is specified, the C method of the loaded module is
332             called with the specified I as an argument. This normally serves to
333             ensure that the version loaded is at least the version required. This is
334             the same functionality provided by the I parameter of C.
335              
336             On success, the name of the module is returned. This is unlike
337             L, and is done so that the entire call to L
338             can be used as a class name to call a constructor, as in the example in
339             the synopsis.
340              
341             =cut
342              
343             sub use_module($;$) {
344 17     17 1 19006 my($name, $version) = @_;
345 17         60 require_module($name);
346 13 100       27944 $name->VERSION($version) if @_ >= 2;
347 12         175 return $name;
348             }
349              
350             =item use_package_optimistically(NAME[, VERSION])
351              
352             This is an analogue of L for the situation where there is
353             uncertainty as to whether a package/class is defined in its own module
354             or by some other means. It attempts to arrange for the named package to
355             be available, either by loading a module or by doing nothing and hoping.
356              
357             An attempt is made to load the named module (as if by the bareword form
358             of C). If the module cannot be found then it is assumed that
359             the package was actually already loaded by other means, and no error
360             is signalled. That's the optimistic bit.
361              
362             I this optional module loading is liable to cause unreliable
363             behaviour, including security problems. It interacts especially badly
364             with having C<.> in C<@INC>, which was the default state of affairs in
365             Perls prior to 5.25.11. If a package is actually defined by some means
366             other than a module, then applying this function to it causes a spurious
367             attempt to load a module that is expected to be non-existent. If a
368             module actually exists under that name then it will be unintentionally
369             loaded. If C<.> is in C<@INC> and this code is ever run with the current
370             directory being one writable by a malicious user (such as F), then
371             the malicious user can easily cause the victim to run arbitrary code, by
372             creating a module file under the predictable spuriously-loaded name in the
373             writable directory. Generally, optional module loading should be avoided.
374              
375             This is mostly the same operation that is performed by the L pragma
376             to ensure that the specified base classes are available. The behaviour
377             of L was simplified in version 2.18, and later improved in version
378             2.20, and on both occasions this function changed to match.
379              
380             If a I is specified, the C method of the loaded package is
381             called with the specified I as an argument. This normally serves
382             to ensure that the version loaded is at least the version required.
383             On success, the name of the package is returned. These aspects of the
384             function work just like L.
385              
386             =cut
387              
388             sub use_package_optimistically($;$) {
389 37     37 1 51038 my($name, $version) = @_;
390 37         130 my $fn = module_notional_filename($name);
391 37         108 eval { local $SIG{__DIE__}; require_module($name); };
  37         143  
  37         97  
392 37 100 66     51300 die $@ if $@ ne "" &&
      66        
393             ($@ !~ /\ACan't locate \Q$fn\E .+ at \Q@{[__FILE__]}\E line/s ||
394             $@ =~ /^Compilation\ failed\ in\ require
395             \ at\ \Q@{[__FILE__]}\E\ line/xm);
396 24 100       180 $name->VERSION($version) if @_ >= 2;
397 22         289 return $name;
398             }
399              
400             =back
401              
402             =head2 Module name composition
403              
404             =over
405              
406             =item is_module_spec(PREFIX, SPEC)
407              
408             Returns a truth value indicating
409             whether I is valid input for L.
410             See below for what that entails. Whether a I is supplied affects
411             the validity of I, but the exact value of the prefix is unimportant,
412             so this function treats I as a truth value.
413              
414             =cut
415              
416             sub is_module_spec($$) {
417 116     116 1 49037 my($prefix, $spec) = @_;
418 116   100     315 return _is_string($spec) &&
419             $spec =~ ($prefix ? qr/\A$sub_module_spec_rx\z/o :
420             qr/\A$top_module_spec_rx\z/o);
421             }
422              
423             =item is_valid_module_spec(PREFIX, SPEC)
424              
425             Deprecated alias for L.
426              
427             =cut
428              
429             *is_valid_module_spec = \&is_module_spec;
430              
431             =item check_module_spec(PREFIX, SPEC)
432              
433             Check whether I is valid input for L.
434             Return normally if it is, or C if it is not.
435              
436             =cut
437              
438             sub check_module_spec($$) {
439 66 100   66 1 167 unless(&is_module_spec) {
440 28 100       137 die +(_is_string($_[1]) ? "`$_[1]'" : "argument").
441             " is not a module specification\n";
442             }
443             }
444              
445             =item compose_module_name(PREFIX, SPEC)
446              
447             This function is intended to make it more convenient for a user to specify
448             a Perl module name at runtime. Users have greater need for abbreviations
449             and context-sensitivity than programmers, and Perl module names get a
450             little unwieldy. I is what the user specifies, and this function
451             translates it into a module name in standard form, which it returns.
452              
453             I has syntax approximately that of a standard module name: it
454             should consist of one or more name segments, each of which consists
455             of one or more identifier characters. However, C is permitted as a
456             separator, in addition to the standard C<::>. The two separators are
457             entirely interchangeable.
458              
459             Additionally, if I is not C then it must be a module
460             name in standard form, and it is prefixed to the user-specified name.
461             The user can inhibit the prefix addition by starting I with a
462             separator (either C or C<::>).
463              
464             =cut
465              
466             sub compose_module_name($$) {
467 16     16 1 105 my($prefix, $spec) = @_;
468 16 100       46 check_module_name($prefix) if defined $prefix;
469 16         36 &check_module_spec;
470 16 100       57 if($spec =~ s#\A(?:/|::)##) {
471             # OK
472             } else {
473 8 100       23 $spec = $prefix."::".$spec if defined $prefix;
474             }
475 16         41 $spec =~ s#/#::#g;
476 16         59 return $spec;
477             }
478              
479             =back
480              
481             =head1 BUGS
482              
483             On Perl versions 5.7.2 to 5.8.8, if C is overridden by the
484             C mechanism, it is likely to break the heuristics used by
485             L, making it signal an error for a missing
486             module rather than assume that it was already loaded. From Perl 5.8.9
487             onwards, and on 5.7.1 and earlier, this module can avoid being confused
488             by such an override. On the affected versions, a C override
489             might be installed by L, if something requires
490             its bugfix but for some reason its XS implementation isn't available.
491              
492             =head1 SEE ALSO
493              
494             L,
495             L,
496             L,
497             L
498              
499             =head1 AUTHOR
500              
501             Andrew Main (Zefram)
502              
503             =head1 COPYRIGHT
504              
505             Copyright (C) 2004, 2006, 2007, 2009, 2010, 2011, 2012, 2014, 2017
506             Andrew Main (Zefram)
507              
508             =head1 LICENSE
509              
510             This module is free software; you can redistribute it and/or modify it
511             under the same terms as Perl itself.
512              
513             =cut
514              
515             1;