lib/PAR/Packer.pm untested

filter: Statementstmt 0.0% 0 / 891 Branchbran 0.0% 0 / 374 Conditioncond 0.0% 0 / 191 Subroutinesub 0.0% 0 / 83 Podpod 0.0% 0 / 62 totaltotal 0.0% 0 / 1601 CC 187 SCAR 52.1
CC
187
Cov
0%
pack_manifest_hash
1056.0
_parse_opts
462.0
_add_file
72.0
CRAP 183.4
1 package PAR::Packer;
2 use 5.008001;
3 use strict;
4 use warnings;
5  
6 our $VERSION = '1.057_001';
7  
8 =head1 NAME
9  
10 PAR::Packer - PAR Packager
11  
12 =head1 DESCRIPTION
13  
14 This module implements the B<App::Packer::Backend> interface, for generating
15 stand-alone executables, perl scripts and PAR files.
16  
17 Currently, this module is used by the command line tool B<pp> internally, as
18 well as by the contributed F<contrib/gui_pp/gpp> program.
19  
20 Since version 0.97 of PAR, this module and its related tools such as C<pp>
21 have been stripped from the PAR distribution and are now distributed as
22 the C<PAR-Packer> distribution so that PAR users need not necessarily
23 have a C compiler.
24  
25 =cut
26  
27 use Config;
28 use Archive::Zip ();
29 use ExtUtils::MakeMaker (); # just for maybe_command()
30 use Cwd qw( abs_path );
31 use File::Basename;
32 use File::Find ();
33 use File::Spec::Functions qw( :ALL );
34 use File::Temp qw( tempfile );
35 use Module::ScanDeps ();
36 use PAR ();
37 use PAR::Filter ();
38 use PAR::Filter::PodStrip ();
39  
40 use constant OPTIONS => {
41 'a|addfile:s@' => 'Additional files to pack',
42 'A|addlist:s@' => 'File containing list of additional files to pack',
43 'B|bundle' => 'Bundle core modules',
44 'C|clean', => 'Clean up temporary files',
45 'c|compile' => 'Compile code to get dependencies',
46 'cd|cachedeps:s' => 'Cache detected dependencies in a file',
47 'd|dependent' => 'Do not include libperl',
48 'e|eval:s' => 'Packing one-liner',
49 'E|evalfeature:s'=> 'Packing one-liner with new syntactic features',
50 'x|execute' => 'Execute code to get dependencies',
51 'xargs:s' => 'Args to pass when executing code',
52 'X|exclude:s@' => 'Exclude modules',
53 'f|filter:s@' => 'Input filters for scripts',
54 'g|gui' => 'No console window',
55 'I|lib:s@' => 'Include directories (for perl)',
56 'l|link:s@' => 'Additional shared libraries to pack',
57 'L|log:s' => 'Where to log packaging process information',
58 'F|modfilter:s@' => 'Input filter for perl modules',
59 'M|module|add:s@'=> 'Include modules',
60 'm|multiarch' => 'Build PAR file for multiple architectures',
61 'n|noscan' => 'Skips static scanning',
62 'o|output:s' => 'Output file',
63 'p|par' => 'Generate PAR file',
64 'P|perlscript' => 'Generate perl script',
65 'r|run' => 'Run the resulting executable',
66 'reusable' => 'Produce reusable executable',
67 'S|save' => 'Preserve intermediate PAR files',
68 's|sign' => 'Sign PAR files',
69 'T|tempcache:s' => 'Temp cache name',
70 'u|unicode' => 'Include Unicode stuff',
71 'v|verbose:i' => 'Verbosity level',
72 'vv|verbose2', => 'Verbosity level 2',
73 'vvv|verbose3', => 'Verbosity level 3',
74 'z|compress:i' => 'Compression level',
75 };
76  
77 my $ValidOptions = {};
78 my $LongToShort = { map { /^(\w+)\|(\w+)/ ? ($1, $2) : () } grep /\|/, keys %{+OPTIONS} };
79 my $ShortToLong = { reverse %$LongToShort };
80 my $PerlExtensionRegex = qr/\.(?:al|ix|p(?:lx|l|h|m))\z/i;
81 my (%dep_zips, %dep_zip_files);
82  
83 sub options { sort keys %{+OPTIONS} }
84  
85 sub new {
86 my ($class, $args, $opt, $frontend) = @_;
87  
88 $SIG{INT} = sub { exit() } if (!$SIG{INT});
89  
90 # exit gracefully and clean up after ourselves.
91 # note.. in constructor because of conflict.
92  
93 my $self = bless {}, $class;
94  
95 $self->set_args($args) if ($args);
96 $self->set_options($opt) if ($opt);
97 $self->set_front($frontend) if ($frontend);
98  
99 return ($self);
100 }
101  
102 sub set_options {
103 my ($self, %opt) = @_;
104  
105 $self->{options} = \%opt;
106 $self->_translate_options($self->{options});
107  
108 # $self->{parl} ||= $self->_extract_parl('PAR::StrippedPARL::Static')
109 # or die("Can't find par loader");
110 # $self->{parl_is_temporary} = 1;
111 $self->{dynperl} ||= $Config{useshrplib} && ($Config{useshrplib} ne 'false');
112 $self->{script_name} = $opt{script_name} || $0;
113 }
114  
115 sub add_options {
116 my ($self, %opts) = @_;
117  
118 my $opt = $self->{options};
119 %$opt = (%$opt, %opts);
120  
121 $self->_translate_options($opt);
122 }
123  
124 sub _translate_options {
125 my ($self, $opt) = @_;
126  
127 $self->_create_valid_hash($self->OPTIONS, $ValidOptions);
128  
129 foreach my $key (keys(%$opt)) {
130 my $value = $opt->{$key};
131  
132 if (!$ValidOptions->{$key}) {
133 $self->_warn("'$key' is not a valid option!\n");
134 $self->_show_usage;
135 }
136 else {
137 $opt->{$key} = $value;
138 my $other = $LongToShort->{$key} || $ShortToLong->{$key};
139 $opt->{$other} = $value if defined $other;
140 }
141 }
142 }
143  
144 sub add_args {
145 my ($self, @arg) = @_;
146 push(@{ $self->{args} }, @arg);
147 }
148  
149 sub set_args {
150 my ($self, @args) = @_;
151 $self->{args} = \@args;
152 }
153  
154 sub set_front {
155 my ($self, $frontend) = @_;
156  
157 my $opt = $self->{options};
158 $self->{frontend} = $frontend || $opt->{frontend};
159 }
160  
161 # check one or more files for read permissions
162 sub _check_read {
163 my ($self, @files) = @_;
164  
165 foreach my $file (@files) {
166 unless (-r $file) {
167 $self->_die("Input file $file is a directory, not a file\n")
168 if (-d _);
169 unless (-e _) {
170 $self->_die("Input file $file was not found\n");
171 }
172 else {
173 $self->_die("Cannot read input file $file: $!\n");
174 }
175 }
176 unless (-f _) {
177 # XXX: die? don't try this on /dev/tty
178 $self->_warn("Input $file is not a plain file\n");
179 }
180 }
181 }
182  
183 # check one or more files for write permissions
184 sub _check_write {
185 my ($self, @files) = @_;
186  
187 foreach my $file (@files) {
188 if (-d $file) {
189 $self->_die("Cannot write on $file, is a directory\n");
190 }
191 if (-e _) {
192 $self->_die("Cannot write on $file: $!\n") unless -w _;
193 }
194 }
195 }
196  
197 # check whether a given file might contain perl code (including .par's)
198 sub _check_perl {
199 my ($self, $file) = @_;
200 return if ($self->_check_par($file));
201  
202 unless (-T $file) {
203 $self->_warn("Binary '$file' sure doesn't smell like perl source!\n");
204  
205 if (my $file_checker = $self->_can_run("file")) {
206 $self->_vprint(0, "Checking file type... ");
207 my $checked = `$file_checker $file`;
208 if (defined $checked) {
209 $self->_vprint(
210 0, "File type checking utility says this "
211 ."about your file:\n$checked\n"
212 );
213 if ($checked =~ /text/) {
214 $self->_vprint(
215 0, "File is a text file, so we'll accept it."
216 );
217 }
218 else {
219 $self->_die("Please try a perlier file!\n");
220 }
221 }
222 else {
223 $self->_die("Please try a perlier file!\n");
224 }
225 }
226 else {
227 $self->_die("Please try a perlier file!\n");
228 }
229 }
230  
231 my $handle = $self->_open($file);
232  
233 local $/ = "\n";
234 local $_ = readline($handle);
235 if (/^#!/ and !/perl/) {
236 $self->_die("$file is a ", /^#!\s*(\S+)/, " script, not perl\n");
237 }
238 }
239  
240 sub _sanity_check {
241 my ($self) = @_;
242  
243 my $input = $self->{input};
244 my $output = $self->{output};
245  
246 # Check the input and output files make sense, are read/writable.
247 if ("@$input" eq $output) {
248 my $a_out = $self->_a_out();
249  
250 if ("@$input" eq $a_out) {
251 $self->_die("Packing $a_out to itself is probably not what you want to do.\n");
252 }
253 else {
254 $self->_warn(
255 "Will not write output on top of input file, ",
256 "packing to $a_out instead\n"
257 );
258 $self->{output} = $a_out;
259 }
260 }
261 }
262  
263 sub _a_out {
264 my ($self) = @_;
265  
266 my $opt = $self->{options};
267  
268 return 'a' . (
269 $opt->{p} ? '.par'
270 : $opt->{P} ? '.pl'
271 : ($Config{_exe} || '.out')
272 );
273 }
274  
275 sub _parse_opts {
276 my ($self) = @_;
277  
278 my $args = $self->{args};
279 my $opt = $self->{options};
280  
281 $self->_verify_opts($opt);
282 $opt->{L} = (defined($opt->{L})) ? $opt->{L} : '';
283 $opt->{p} = 1 if ($opt->{m});
284 $opt->{v} = (defined($opt->{v})) ? ($opt->{v} || 1) : 0;
285 $opt->{v} = 2 if ($opt->{vv});
286 $opt->{v} = 3 if ($opt->{vvv});
287 $opt->{B} = 1 unless ($opt->{p} || $opt->{P});
288 $opt->{z} = (defined($opt->{z})) ? $opt->{z} : Archive::Zip::COMPRESSION_LEVEL_DEFAULT;
289 $opt->{z} = Archive::Zip::COMPRESSION_LEVEL_DEFAULT if $opt->{z} < 0;
290 $opt->{z} = 9 if $opt->{z} > 9;
291  
292 $opt->{o} = $opt->{o} || $self->_a_out();
293 $self->{output} = $opt->{o};
294 $self->{script_name} = $self->{script_name} || $opt->{script_name} || $0;
295  
296 $self->{logfh} = $self->_open('>>', $opt->{L})
297 if length $opt->{L};
298  
299 if (defined $opt->{E}) {
300 $opt->{e} = "use $];\n#line 1\n$opt->{E}";
301 # XXX This is how we should also include additional default modules in the future instead of in require_modules in par.pl!
302 push @{ $opt->{M} ||= [] }, 'feature' if $] >= 5.009;
303 }
304  
305 if (defined $opt->{e}) {
306 $self->_warn("Using -e 'code' as input file, ignoring @$args\n")
307 if (@$args and !$opt->{r});
308  
309 my ($fh, $fake_input) = tempfile(
310 "ppXXXXX", SUFFIX => ".pl", TMPDIR => 1, UNLINK => 1);
311  
312 print $fh $opt->{e};
313 close $fh;
314 $self->{input} = [$fake_input];
315 }
316 else {
317 $self->{input} ||= [];
318  
319 # Reject main.pl as input file to avoid beginner confusion
320 if ( grep /(?:^|[\/\\])main\.pl$/,
321 ($opt->{r} ? ($args->[0]) : @$args) )
322 {
323 # -r means "run this" => extra args are execution parameters
324  
325 $self->_die( "Cannot package 'main.pl' script. This file name "
326 ."is used by PAR::Packer internally for bootstrapping.");
327 }
328 push(@{ $self->{input} }, shift @$args) if (@$args);
329  
330 push(@{ $self->{input} }, @$args) if (@$args and !$opt->{r});
331 my $in = $self->{input};
332  
333 $self->_check_read(@$in) if (@$in);
334 $self->_check_perl(@$in) if (@$in);
335 $self->_sanity_check();
336 }
337 }
338  
339 sub _verify_opts {
340 my ($self, $opt) = @_;
341  
342 $self->_create_valid_hash($self->OPTIONS, $ValidOptions);
343  
344 my $show_usage = 0;
345 foreach my $key (keys(%$opt)) {
346 if (!$ValidOptions->{$key}) {
347 $self->_warn("'$key' is not a valid option!\n");
348 $show_usage = 1;
349 }
350 }
351  
352 $self->_show_usage() if ($show_usage);
353 }
354  
355 sub _create_valid_hash {
356 my ($self, $hashin, $hashout) = @_;
357  
358 return () if (%$hashout);
359  
360 foreach my $key (keys(%$hashin)) {
361 my (@keys) = $key =~ /(?<!:)(\w+)/g;
362 @{$hashout}{@keys} = ($hashin->{$key}) x @keys;
363 }
364 }
365  
366 # prints a dump of the OPTIONS hash
367 sub _show_usage {
368 my ($self) = @_;
369  
370 foreach my $key ($self->options) {
371 print STDERR "\n$key"
372 . " " x (20 - length($key))
373 . $self->OPTIONS->{$key} . "\n";
374 }
375 print STDERR "\n\n";
376 }
377  
378 sub go {
379 my ($self) = @_;
380  
381 local $| = 1;
382 $self->_parse_opts();
383  
384 my $opt = $self->{options};
385  
386 $self->_setup_run();
387 $self->generate_pack({ nosetup => 1 });
388 $self->run_pack({ nosetup => 1 }) if ($opt->{r});
389 }
390  
391 sub _setup_run {
392 my ($self) = @_;
393  
394 my $opt = $self->{options};
395 my $args = $self->{args};
396 my $output = $self->{output};
397  
398 $self->_die("No input files specified\n")
399 unless @{ $self->{input} } or $opt->{M};
400  
401 $self->_check_write($output);
402 }
403  
404 sub generate_pack {
405 my ($self, $config) = @_;
406  
407 $config ||= {};
408 $self->_parse_opts() if (!$config->{nosetup});
409 $self->_setup_run() if (!$config->{nosetup});
410  
411 my $input = $self->{input};
412 my $opt = $self->{options};
413  
414 $self->_vprint(0, "Packing @$input");
415  
416 if ($self->_check_par($input->[0])) {
417 # invoked as "pp foo.par" - never unlink it
418 $self->{par_file} = $input->[0];
419 $opt->{S} = 1;
420 $self->_par_to_exe();
421 }
422 else {
423 $self->_compile_par();
424 }
425 }
426  
427 sub run_pack {
428 my ($self, $config) = @_;
429  
430 $config ||= {};
431  
432 $self->_parse_opts() if (!$config->{nosetup});
433 $self->_setup_run() if (!$config->{nosetup});
434  
435 my $opt = $self->{options};
436 my $output = $self->{output};
437 my $args = $self->{args};
438  
439 if (!file_name_is_absolute($output)) {
440 $output = catfile(".", $output);
441 }
442  
443 my @loader = ();
444 push(@loader, $^X) if ($opt->{P});
445 push(@loader, $^X, "-MPAR") if ($opt->{p});
446 $self->_vprint(0, "Running @loader $output @$args");
447 system(@loader, $output, @$args);
448 exit(0);
449 }
450  
451 sub _compile_par {
452 my ($self) = @_;
453  
454 local (@INC) = @INC;
455  
456 my $lose = $self->{pack_attrib}{lose};
457 my $opt = $self->{options};
458  
459 my $par_file = $self->get_par_file();
460  
461 $self->_add_pack_manifest();
462 $self->_add_add_manifest();
463 $self->_make_manifest();
464 $self->_write_zip();
465  
466 $self->_sign_par() if ($opt->{s});
467 $self->_par_to_exe() unless ($opt->{p});
468  
469 if ($lose) {
470 $self->_vprint(2, "Unlinking $par_file");
471 unlink $par_file or $self->_die("Can't unlink $par_file: $!");
472 }
473 }
474  
475 sub _write_zip {
476 my ($self) = @_;
477  
478 my $old_member = $self->{pack_attrib}{old_member};
479 my $oldsize = $self->{pack_attrib}{old_size};
480 my $par_file = $self->{par_file};
481 my $add_manifest = $self->add_manifest();
482  
483 my $zip = $self->{zip};
484  
485 if ($old_member) {
486 $zip->overwrite();
487 }
488 else {
489 $zip->writeToFileNamed($par_file);
490 }
491  
492 my $newsize = -s $par_file;
493 $self->_vprint(
494 2,
495 sprintf( "*** %s: %d bytes read, %d compressed, %2.2d%% saved.\n",
496 $par_file, $oldsize,
497 $newsize, (100 - ($newsize / $oldsize * 100))
498 )
499 );
500 }
501  
502 sub _sign_par {
503 my ($self) = @_;
504  
505 my $opt = $self->{options};
506 my $par_file = $self->{par_file};
507  
508 if (eval {
509 require PAR::Dist;
510 require Module::Signature;
511 Module::Signature->VERSION >= 0.25;
512 }
513 )
514 {
515 $self->_vprint(0, "Signing $par_file");
516 PAR::Dist::sign_par($par_file);
517 }
518 else {
519 $self->_vprint(-1,
520 "*** Signing requires PAR::Dist with Module::Signature 0.25 or later. Skipping"
521 );
522 }
523 }
524  
525 sub _add_add_manifest {
526 my ($self) = @_;
527  
528 my $opt = $self->{options};
529 my $add_manifest = $self->add_manifest_hash();
530 my $par_file = $self->{par_file};
531  
532 $self->_vprint(1, "Writing extra files to $par_file") if (%$add_manifest);
533 $self->{zip} ||= Archive::Zip->new;
534 my $zip = $self->{zip};
535  
536 my $in;
537 foreach $in (sort keys(%$add_manifest)) {
538 my $value = $add_manifest->{$in};
539 $self->_add_file($zip, $in, $value);
540 }
541 }
542  
543 sub _make_manifest {
544 my ($self) = @_;
545  
546 my $full_manifest = $self->{full_manifest};
547 my $add_manifest = $self->{add_manifest};
548  
549 my $opt = $self->{options};
550 my $par_file = $self->{par_file};
551 my $output = $self->{output};
552  
553 my $clean = ($opt->{C} ? 1 : 0);
554 my $dist_name = ($opt->{p} ? $par_file : $output);
555 my $verbatim = ($ENV{PAR_VERBATIM} || 0);
556  
557 my $manifest = join("\n",
558 ' <!-- accessible as jar:file:///NAME.par!/MANIFEST in compliant browsers -->',
559 (sort keys %$full_manifest, keys %$add_manifest),
560 q( # <html><body onload="var X=document.body.innerHTML.split(/\n/);var Y='<iframe src=&quot;META.yml&quot; style=&quot;float:right;height:40%;width:40%&quot;></iframe><ul>';for(var x in X){if(!X[x].match(/^\s*#/)&&X[x].length)Y+='<li><a href=&quot;'+X[x]+'&quot;>'+X[x]+'</a>'}document.body.innerHTML=Y">)
561 );
562  
563 my ($class, $version) = (ref($self), $self->VERSION);
564 my $meta_yaml = << "YAML";
565 build_requires: {}
566 conflicts: {}
567 dist_name: $dist_name
568 distribution_type: par
569 dynamic_config: 0
570 generated_by: '$class version $version'
571 license: unknown
572 par:
573 clean: $clean
574 signature: ''
575 verbatim: $verbatim
576 version: $PAR::VERSION
577 YAML
578  
579 my $zip = $self->{zip};
580  
581 if (keys %dep_zips) {
582 $self->_vprint(2, "... updating main.pl");
583 my $dep_list = join ' ', keys %dep_zips;
584 my $main_pl = $zip->contents('script/main.pl');
585 $main_pl = "use PAR qw( $dep_list );\n$main_pl";
586 $zip->contents( 'script/main.pl', $main_pl );
587 $dep_list = join ', ', keys %dep_zips;
588 $self->_vprint(0, "$self->{output} will require $dep_list at runtime");
589  
590 $manifest =~ s/\Q$_\E\n// for (keys %dep_zip_files);
591 }
592  
593 $self->_vprint(2, "... updating $_") for qw(MANIFEST META.yml);
594 $zip->contents( 'MANIFEST', $manifest );
595 $zip->contents( 'META.yml', $meta_yaml );
596 }
597  
598 sub get_par_file {
599 my ($self) = @_;
600  
601 return ($self->{par_file}) if ($self->{par_file});
602  
603 my $input = $self->{input};
604 my $output = $self->{output};
605  
606 my $par_file;
607 my $cfh;
608  
609 my $opt = $self->{options};
610  
611 if ($opt->{S} or $opt->{p}) {
612 # We need to keep it.
613  
614 if (defined $opt->{e} or !@$input) {
615 $par_file = (defined $output ? $output : "a.par");
616 }
617 else {
618 $par_file = $input->[0];
619  
620 # File off extension if present
621 $par_file =~ s/$PerlExtensionRegex//;
622 $par_file .= ".par";
623 }
624  
625 $par_file = $output if $opt->{p};
626  
627 $self->_check_write($par_file);
628 }
629 else {
630 # Don't need to keep it, be safe with a tempfile.
631  
632 $self->{pack_attrib}{lose} = 1;
633 ($cfh, $par_file) = tempfile(
634 "ppXXXXX", SUFFIX => ".par", TMPDIR => 1, UNLINK => 1);
635 close $cfh; # See comment just below
636 }
637 $self->{par_file} = $par_file;
638 return ($par_file);
639 }
640  
641 sub set_par_file {
642 my ($self, $file) = @_;
643  
644 $self->{par_file} = $file;
645 $self->_check_write($file);
646 }
647  
648 sub pack_manifest_hash {
649 my ($self) = @_;
650  
651 my @SharedLibs;
652 return ($self->{pack_manifest}) if ($self->{pack_manifest});
653  
654 $self->{pack_manifest} ||= {};
655 $self->{full_manifest} ||= {};
656 my $full_manifest = $self->{full_manifest};
657 my $dep_manifest = $self->{pack_manifest};
658  
659 my $sn = $self->{script_name};
660 my $fe = $self->{frontend};
661  
662 my $opt = $self->{options};
663 my $input = $self->{input};
664 my $output = $self->{output};
665  
666 my $root = '';
667 $root = "$Config{archname}/" if ($opt->{m});
668 $self->{pack_attrib}{root} = '';
669  
670 my $par_file = $self->{par_file};
671 my (@modules, @data, @exclude);
672  
673 # Search for scannable code in all -I'd paths
674 # NOTE: We need this early, because Module::ScanDeps::_find_in_inc
675 # and others refer to @IncludeLibs.
676 push @Module::ScanDeps::IncludeLibs, @{$opt->{I}} if $opt->{I};
677  
678 foreach my $name (@{ $opt->{M} || [] }) {
679 if ($name =~ s/^([\w:]+)::(\*{0,2})$/$1/) {
680 my $ns = length $2; # namespace depth indicator
681  
682 if ($ns == 0) {
683 # "-MFoo::" shorthand for "-MFoo -MFoo::**"
684 $self->_name2moddata($name, \@modules, \@data);
685 $ns = 2;
686 }
687  
688 (my $mod = $name) =~ s/::/\//g;
689 my @mods_in_ns = $ns == 1
690 ? Module::ScanDeps::_glob_in_inc_1($mod, 1)
691 : Module::ScanDeps::_glob_in_inc($mod, 1);
692 $self->_name2moddata($_, \@modules, \@data) foreach @mods_in_ns;
693 }
694 else {
695 $self->_name2moddata($name, \@modules, \@data);
696 }
697 }
698  
699 if ($opt->{u}) {
700 if ($] lt '5.031006') {
701 push @modules, "utf8_heavy.pl";
702 }
703 else {
704 $self->_warn("'-u' is not needed for Perl >= 5.31.6");
705 }
706 }
707  
708 # Skip either
709 # a) all files from a .par file or
710 # b) A module
711 foreach my $name ('PAR', @{ $opt->{X} || [] }) {
712 if (-f $name and my $dep_zip = Archive::Zip->new($name)) {
713 for ($dep_zip->memberNames()) {
714 next if ( /MANIFEST/ or /META.yml/ or /^script\// );
715 $dep_zip_files{$_} ||= $name;
716 }
717 }
718 else {
719 $self->_name2moddata($name, \@exclude, \@exclude);
720 }
721 }
722  
723 my %map;
724  
725 unshift(@INC, @{ $opt->{I} || [] });
726 unshift(@SharedLibs, map $self->_find_shlib($_), @{ $opt->{l} || [] });
727  
728 # Note: _find_in_inc() may return ()
729 my %skip = map { $_ => 1 } grep { defined } map { Module::ScanDeps::_find_in_inc($_) } @exclude;
730 if ($^O eq 'MSWin32') {
731 %skip = (%skip, map { s{\\}{/}g; lc($_) => 1 } @SharedLibs);
732 }
733 else {
734 %skip = (%skip, map { $_ => 1 } @SharedLibs);
735 }
736  
737 my $add_deps = $self->_obj_function($fe, 'add_deps');
738  
739 if ($opt->{x} && defined $opt->{xargs}) {
740 require Text::ParseWords;
741 $opt->{x} = [ Text::ParseWords::shellwords($opt->{xargs}) ];
742 }
743  
744 if (!$opt->{n}) {
745 my @files = @$input;
746  
747 # apply %Preload to the -M'd modules and add them to the list of files to scan
748 foreach my $module (@modules) {
749 my $file = Module::ScanDeps::_find_in_inc($module)
750 or $self->_die("Cannot find module $module (specified with -M)\n");
751 push @files, $file;
752  
753 my @preload = Module::ScanDeps::_get_preload($module) or next;
754  
755 $add_deps->(
756 used_by => $file,
757 rv => \%map,
758 modules => \@preload,
759 skip => \%skip,
760 );
761 }
762  
763 # run static scan on the augmented file list
764 $self->_obj_function($fe, 'scan_deps')->(
765 rv => \%map,
766 files => \@files,
767 skip => \%skip,
768 recurse => 1,
769 ($opt->{cachedeps}) ? (cache_file => $opt->{cachedeps}) : (),
770 );
771 }
772  
773 if ($opt->{c} || $opt->{x}) {
774 # run dynamic scan in the original $input files
775 $self->_obj_function($fe, 'scan_deps_runtime')->(
776 rv => \%map,
777 files => $input,
778 execute => $opt->{x},
779 compile => $opt->{c},
780 skip => \%skip,
781 ($opt->{cachedeps}) ? (cache_file => $opt->{cachedeps}) : (),
782 );
783 }
784  
785 # Note: _find_in_inc() may return ()
786 %skip = map { $_ => 1 } grep { defined } map { Module::ScanDeps::_find_in_inc($_) } @exclude;
787 %skip = (%skip, map { $_ => 1 } @SharedLibs);
788  
789 $add_deps->(
790 rv => \%map,
791 modules => \@modules,
792 skip => \%skip,
793 );
794  
795 my %text;
796  
797 $text{$_} = ($map{$_}{type} =~ /^(?:module|autoload)$/) for keys %map;
798 $map{$_} = $map{$_}{file} for keys %map;
799  
800 $self->{pack_attrib}{text} = \%text;
801 $self->{pack_attrib}{map} = \%map;
802 $self->{pack_attrib}{shared_libs} = \@SharedLibs;
803  
804 my $size = 0;
805 my $old_member;
806  
807 if ($opt->{m} and -e $par_file) {
808 my $tmpzip = Archive::Zip->new();
809 $tmpzip->read($par_file);
810  
811 if ($old_member = $tmpzip->memberNamed('MANIFEST')) {
812 $full_manifest->{$_} = [ file => $_ ]
813 for (grep /^\S/, split(/\n/, $old_member->contents));
814 $dep_manifest->{$_} = [ file => $_ ]
815 for (grep /^\S/, split(/\n/, $old_member->contents));
816 }
817 else {
818 $old_member = 1;
819 }
820 $self->{pack_attrib}{old_member} = $old_member;
821 }
822  
823 # generate a selective set of filters from the options passed in via -F
824 my $mod_filter = _generate_filter($opt, 'F');
825  
826 my ($privlib, $archlib) = map { (my $lib = $_) =~ s{\\}{/}g; $lib }
827 @Config{qw(privlibexp archlibexp)};
828  
829 foreach my $pfile (sort grep length $map{$_}, keys %map) {
830 next if !$opt->{B} and (
831 ($map{$pfile} eq "$privlib/$pfile") or
832 ($map{$pfile} eq "$archlib/$pfile")
833 );
834  
835 $self->_vprint(2, "... adding $map{$pfile} as ${root}lib/$pfile");
836  
837 if ($text{$pfile} or $pfile =~ /utf8_heavy\.pl$/i) {
838 my $content_ref = $mod_filter->($map{$pfile}, $pfile);
839  
840 $full_manifest->{ $root . "lib/$pfile" } =
841 [ string => $content_ref ];
842 $dep_manifest->{ $root . "lib/$pfile" } =
843 [ string => $content_ref ];
844 }
845 else {
846 $full_manifest->{ $root . "lib/$pfile" } =
847 [ file => $map{$pfile} ];
848 $dep_manifest->{ $root . "lib/$pfile" } =
849 [ file => $map{$pfile} ];
850 }
851 }
852  
853 # For -f, we just accept normal filters - no selection of files.
854 my $script_filter = _generate_filter($opt, 'f');
855 $script_filter = PAR::Filter->new(@{ $opt->{f} }) if ($opt->{f});
856  
857 my $in;
858 foreach my $in (@$input) {
859 my $name = basename($in);
860  
861 if ($script_filter) {
862 my $string = $script_filter->apply($in, $name);
863  
864 $full_manifest->{"script/$name"} = [ string => $string ];
865 $dep_manifest->{"script/$name"} = [ string => $string ];
866 }
867 else {
868 $full_manifest->{"script/$name"} = [ file => $in ];
869 $dep_manifest->{"script/$name"} = [ file => $in ];
870 }
871  
872 delete $full_manifest->{$root . "lib/$name"};
873 delete $dep_manifest->{$root . "lib/$name"};
874 }
875  
876 my $shlib = "shlib/$Config{archname}";
877  
878 foreach my $in (@SharedLibs) {
879 next unless -e $in;
880  
881 my $name;
882  
883 # try to find the name the runtime loader will be looking for
884 if ($^O =~ /linux|solaris|freebsd|openbsd/i) {
885 # try "objdump" to extract SONAME
886 my $od = qx( objdump -p $in );
887 if ($? == 0 && $od =~ /^\s* SONAME \s+ (\S+)/mx) {
888 $name = $1;
889 $self->_vprint(1, "... objdump: library $in has SONAME $name");
890 }
891 }
892 elsif ($^O eq 'darwin') {
893 # try "otool -D $file", expect itwo lines of output like
894 # $file:
895 # path
896 # Note: some versions of otool report just a name in the
897 # second line, others report a pathname
898 chomp(my @ot = qx( otool -D $in ));
899 if ($? == 0) {
900 $name = basename($ot[1]);
901 $self->_vprint(1, "... otool: library $in has install name $name");
902 }
903 else {
904 # fallback to old "chasing symlinks" method
905 $name = basename($self->_chase_lib_darwin($in));
906 }
907 }
908  
909 # fallback to old "chasing symlinks" method if nothing else worked
910 $name = basename($self->_chase_lib($in)) unless defined $name;
911  
912 $dep_manifest->{"$shlib/$name"} = [ file => $in ];
913 $full_manifest->{"$shlib/$name"} = [ file => $in ];
914 }
915  
916 foreach my $in (@data) {
917 unless (-r $in and !-d $in) {
918 $self->_warn("'$in' does not exist or is not readable; skipping\n");
919 next;
920 }
921 $full_manifest->{$in} = [ file => $in ];
922 $dep_manifest->{$in} = [ file => $in ];
923 }
924  
925 if (@$input and (@$input == 1 or !$opt->{p})) {
926 my $string =
927 (@$input == 1)
928 ? $self->_main_pl_single("script/" . basename($input->[0]))
929 : $self->_main_pl_multi();
930  
931 $full_manifest->{"script/main.pl"} = [ string => $string ];
932 $dep_manifest->{"script/main.pl"} = [ string => $string ];
933 }
934  
935 $full_manifest->{'MANIFEST'} = [ string => "<<placeholder>>" ];
936 $full_manifest->{'META.yml'} = [ string => "<<placeholder>>" ];
937  
938 $dep_manifest->{'MANIFEST'} = [ string => "<<placeholder>>" ];
939 $dep_manifest->{'META.yml'} = [ string => "<<placeholder>>" ];
940 return ($dep_manifest);
941 }
942  
943  
944 sub _generate_filter {
945 my $opt = shift; # options hash
946 my $key = shift; # F or f? modules or script?
947  
948 my $verbatim = ($ENV{PAR_VERBATIM} || 0);
949  
950 # List of filters. If the regex is undefined or matches the
951 # file name (e.g. Foo/Bar.pm), apply filter to this module.
952 my @filters = (
953 { regex => undef, filter => PAR::Filter->new('PatchContent') },
954 );
955  
956 foreach my $option (@{ $opt->{$key} }) {
957 my ($filter, $regex) = split /=/, $option, 2;
958 push @filters, {
959 regex => (defined $regex ? qr/$regex/ : $regex),
960 filter => PAR::Filter->new($filter)
961 };
962 }
963  
964 my $filtersub = sub {
965 my $ref = shift;
966 my $name = shift;
967 my $filtered = 0;
968 foreach my $filterspec (@filters) {
969 if (
970 not defined $filterspec->{regex}
971 or $name =~ $filterspec->{regex}
972 ) {
973 $filtered++;
974 $ref = $filterspec->{filter}->apply($ref, $name);
975 }
976 }
977  
978 # PodStrip by default, overridden by -F or $ENV{PAR_VERBATIM}
979 if ($filtered == 1 and not $verbatim) {
980 $ref = PAR::Filter::PodStrip->apply($ref, '');
981 }
982 return $ref;
983 };
984  
985 return $filtersub;
986 }
987  
988 sub full_manifest_hash {
989 my ($self) = @_;
990  
991 $self->pack_manifest_hash();
992 return ($self->{full_manifest});
993 }
994  
995 sub full_manifest {
996 my ($self) = @_;
997  
998 $self->pack_manifest_hash();
999 my $mh = $self->{full_manifest};
1000 return ([ sort keys(%$mh) ]);
1001 }
1002  
1003 sub add_manifest_hash {
1004 my ($self) = @_;
1005 return ($self->{add_manifest}) if ($self->{add_manifest});
1006 my $mh = $self->{add_manifest} = {};
1007  
1008 my $ma = $self->_add_manifest();
1009  
1010 my $elt;
1011  
1012 foreach $elt (@$ma) {
1013 my ($file, $alias) = @$elt;
1014  
1015 if (!-e $file) {
1016 $self->_warn("Cannot find file or directory $file for packing\n");
1017 }
1018 elsif (!-r _) {
1019 $self->_warn("Cannot read file or directory $file for packing\n");
1020 }
1021 elsif (-d _) {
1022 my ($files, $aliases) = $self->_expand_dir(@$elt);
1023 while (@$files) {
1024 $mh->{ shift(@$aliases) } = [ file => shift(@$files) ];
1025 }
1026 }
1027 else {
1028 $mh->{ $alias } = [ file => $file ];
1029 }
1030 }
1031 return ($mh);
1032 }
1033  
1034 sub _add_manifest {
1035 my ($self) = @_;
1036  
1037 my $opt = $self->{options};
1038 my $return = [];
1039 my $files = [];
1040 my $lists = [];
1041  
1042 $files = $opt->{a} if ($opt->{a});
1043 $lists = $opt->{A} if ($opt->{A});
1044  
1045 local $/ = "\n";
1046 foreach my $list (@$lists) {
1047 my $fh = $self->_open('<', $list, 'text');
1048 while (my $line = <$fh>) {
1049 chomp($line);
1050 push(@$files, $line);
1051 }
1052 }
1053  
1054 foreach my $file (grep length, @$files) {
1055 $file =~ s{\\}{/}g;
1056  
1057 if ($file =~ /;/) {
1058 push(@$return, [ split(/;/, $file) ]);
1059 }
1060 else {
1061 my $alias = $file;
1062 $alias =~ s{^[a-zA-Z]:}{} if $^O eq 'MSWin32';
1063 $alias =~ s{^/}{};
1064 push(@$return, [ $file, $alias ]);
1065 }
1066 }
1067 return ($return);
1068 }
1069  
1070 sub add_manifest {
1071 my ($self) = @_;
1072 my $mh = $self->add_manifest_hash();
1073  
1074 my @ma = sort keys(%$mh);
1075 return (\@ma);
1076 }
1077  
1078 sub _add_pack_manifest {
1079 my ($self) = @_;
1080  
1081 my $par_file = $self->{par_file};
1082 my $opt = $self->{options};
1083  
1084 $self->{zip} ||= Archive::Zip->new;
1085 my $zip = $self->{zip};
1086  
1087 my $input = $self->{input};
1088  
1089 $self->_vprint(1, "Writing PAR on $par_file");
1090  
1091 $zip->read($par_file) if ($opt->{'m'} and -e $par_file);
1092  
1093 my $pack_manifest = $self->pack_manifest_hash();
1094  
1095 my $map = $self->{pack_attrib}{map};
1096 my $root = $self->{pack_attrib}{root};
1097 my $shared_libs = $self->{pack_attrib}{shared_libs};
1098  
1099 $zip->addDirectory('', substr($root, 0, -1))->unixFileAttributes(0755) if ($root and %$map);
1100 $zip->addDirectory('', $root . 'lib')->unixFileAttributes(0755) if %$map;
1101  
1102 my $shlib = "shlib/$Config{archname}";
1103 $zip->addDirectory('', $shlib)->unixFileAttributes(0755) if @$shared_libs;
1104  
1105 my @tmp_input = @$input;
1106 @tmp_input = grep !/\.pm\z/i, @tmp_input;
1107  
1108 $zip->addDirectory('', 'script')->unixFileAttributes(0755) if @tmp_input;
1109  
1110 my $in;
1111 foreach $in (sort keys(%$pack_manifest)) {
1112 my $value = $pack_manifest->{$in};
1113 $self->_add_file($zip, $in, $value);
1114 }
1115  
1116 }
1117  
1118 sub dep_files {
1119 my ($self) = @_;
1120  
1121 my $dm = $self->{dep_manifest};
1122 return ([ keys(%$dm) ]) if ($dm);
1123  
1124 }
1125  
1126 sub _add_file {
1127 my ($self, $zip, $in, $value, $manifest) = @_;
1128  
1129 my $level = $self->{options}->{z};
1130 my $method = $level ? Archive::Zip::COMPRESSION_DEFLATED
1131 : Archive::Zip::COMPRESSION_STORED;
1132 my $oldsize = $self->{pack_attrib}{old_size};
1133 my $full_manifest = $self->{full_manifest};
1134  
1135 if ($value->[0] eq 'file') {
1136 my $fn = $value->[1];
1137  
1138 if (-d $fn) {
1139 my ($files, $aliases) = $self->_expand_dir($fn, $in);
1140  
1141 $self->_vprint(1, "... adding $fn as $in\n");
1142  
1143 while (@$files) {
1144 my $file = shift @$files;
1145 my $alias = shift @$aliases;
1146  
1147 if (exists $dep_zip_files{$alias}) {
1148 $dep_zips{$dep_zip_files{$alias}}++;
1149 next;
1150 }
1151 $self->_vprint(1, "... adding $file as $alias\n");
1152  
1153 $full_manifest->{ $alias } = [ file => $file ];
1154 $manifest->{ $alias } = [ file => $file ];
1155  
1156 $oldsize += -s $file;
1157 my $member = $zip->addFile($file, $alias);
1158 $member->desiredCompressionMethod($method);
1159 $member->desiredCompressionLevel($level);
1160 }
1161 }
1162 elsif (-e $fn and -r $fn) {
1163 if (exists $dep_zip_files{$in}) {
1164 $dep_zips{$dep_zip_files{$in}}++;
1165 return;
1166 }
1167 $self->_vprint(1, "... adding $fn as $in\n");
1168  
1169 $oldsize += -s $fn;
1170 my $member = $zip->addFile($fn => $in);
1171 $member->desiredCompressionMethod($method);
1172 $member->desiredCompressionLevel($level);
1173 }
1174 }
1175 else {
1176 if (exists $dep_zip_files{$in}) {
1177 $dep_zips{$dep_zip_files{$in}}++;
1178 return;
1179 }
1180 my $str = $value->[1];
1181 $oldsize += length($str);
1182  
1183 $self->_vprint(1, "... adding <string> as $in");
1184 my $member = $zip->addString($str => $in);
1185 $member->unixFileAttributes(0644);
1186 $member->desiredCompressionMethod($method);
1187 $member->desiredCompressionLevel($level);
1188 }
1189  
1190 $self->{pack_attrib}{old_size} = $oldsize;
1191 }
1192  
1193 sub _expand_dir {
1194 my ($self, $fn, $in) = @_;
1195 my (@return, @alias_return);
1196  
1197 File::Find::find(
1198 {
1199 wanted => sub { push(@return, $File::Find::name) if -f },
1200 follow_fast => ( ($^O eq 'MSWin32') ? 0 : 1 ),
1201 },
1202 $fn
1203 );
1204  
1205 @alias_return = @return;
1206 s/^\Q$fn\E/$in/ for @alias_return;
1207  
1208 return (\@return, \@alias_return);
1209 }
1210  
1211 sub _die {
1212 my ($self, @args) = @_;
1213 $self->_log(@args);
1214  
1215 my $sn = $self->{script_name};
1216 die "$sn: ", @args;
1217 }
1218  
1219 sub _warn {
1220 my ($self, @args) = @_;
1221 $self->_log(@args);
1222  
1223 my $sn = $self->{script_name};
1224 warn "$sn: ", @args;
1225 }
1226  
1227 sub _log {
1228 my ($self, @args) = @_;
1229  
1230 my $opt = $self->{options};
1231 my $logfh = $self->{logfh};
1232 my $sn = $self->{script_name};
1233  
1234 $logfh->print("$sn: ", @args) if ($opt->{L});
1235 }
1236  
1237 sub _name2moddata {
1238 my ($self, $name, $mod, $dat) = @_;
1239  
1240 if ($name =~ /^[\w:]+$/) {
1241 $name =~ s/::/\//g;
1242 push @$mod, "$name.pm";
1243 }
1244 elsif ($name =~ /$PerlExtensionRegex/) {
1245 push @$mod, $name;
1246 }
1247 else {
1248  
1249 if (!-e $name) {
1250 $self->_warn( "-M or -X option file not found: $name\n" );
1251 }
1252 else {
1253 $self->_warn(
1254 "Using -M to add non-library files is deprecated; ",
1255 "try -a instead\n",
1256 ) if $mod != $dat;
1257 push @$dat, $name;
1258 }
1259 }
1260 }
1261  
1262 sub _par_to_exe {
1263 my ($self) = @_;
1264  
1265 my $opt = $self->{options};
1266 my $output = $self->{output};
1267 my $dynperl = $self->{dynperl};
1268 my $par_file = $self->{par_file};
1269  
1270 require PAR::StrippedPARL::Static;
1271 require PAR::StrippedPARL::Dynamic;
1272  
1273 my $parlclass = 'PAR::StrippedPARL::Static';
1274 my $buf;
1275 my $parl = 'parl';
1276  
1277 if ($opt->{d} and $dynperl) {
1278 $parlclass = 'PAR::StrippedPARL::Dynamic';
1279 $parl = 'parldyn';
1280 }
1281 $parl .= $Config{_exe};
1282  
1283 if ($opt->{P}) {
1284 # write as script
1285 $parl = 'par.pl';
1286 unless ( $parl = $self->_can_run($parl, $opt->{P}) ) {
1287 $self->_die("par.pl not found");
1288 }
1289 $self->{parl} = $parl;
1290 }
1291 else {
1292 # binary, either static or dynamic
1293 $parl = $self->_extract_parl($parlclass)
1294 or $self->_die("Can't find par loader");
1295 $self->{parl_is_temporary} = 1;
1296 $self->{parl} = $parl;
1297 }
1298  
1299 if ($^O ne 'MSWin32' or $opt->{p} or $opt->{P}) {
1300 $self->_generate_output();
1301 }
1302 else {
1303 $self->_generate_output();
1304 $self->_fix_console() if $opt->{g};
1305 }
1306 }
1307  
1308 # extracts a parl (static) or parldyn (dynamic) from the appropriate data class
1309 # using the class' write_parl($file) method. Note that 'write_parl' extracts to
1310 # a temporary file first, then uses that plain parl to embed the core modules into
1311 # the file given as argument. This was taken from the PAR bootstrapping process.
1312 # First argument must be the class name.
1313 # Returns the path and name of the file (or the empty list on failure).
1314 sub _extract_parl {
1315 my $self = shift;
1316 my $class = shift;
1317  
1318 $self->_die("First argument to _extract_parl must be a class name")
1319 if not defined $class;
1320 $self->_die("Class '$class' is not a PAR(L) data class. Can't call '${class}->write_parl()'")
1321 if not $class->can('write_parl');
1322  
1323 $self->_vprint(0, "Generating a fresh 'parl'.");
1324 my ($fh, $filename) = tempfile(
1325 "parlXXXXXXX", SUFFIX => $Config{_exe}, TMPDIR => 1, UNLINK => 1);
1326 close $fh;
1327  
1328 my $success = $class->write_parl($filename);
1329 if (not $success) {
1330 $self->_die("Failed to extract a parl from '$class' to file '$filename'");
1331 }
1332  
1333 chmod(oct('755'), $filename);
1334 return $filename;
1335 }
1336  
1337  
1338 sub _move_parl {
1339 my ($self) = @_;
1340  
1341 $self->{orig_parl} = $self->{parl};
1342  
1343 my $cfh;
1344 my $fh = $self->_open($self->{parl});
1345 ($cfh, $self->{parl}) = tempfile(
1346 "parlXXXX", SUFFIX => ".exe", TMPDIR => 1, UNLINK => 1);
1347 binmode($cfh);
1348  
1349 local $/;
1350 print $cfh readline($fh);
1351 close $cfh;
1352  
1353 $self->{fh} = $fh;
1354 }
1355  
1356 sub _generate_output {
1357 my ($self) = @_;
1358  
1359 my $opt = $self->{options};
1360 my $output = $self->{output};
1361 my $par_file = $self->{par_file};
1362  
1363 my @args = ("-O$output", $par_file);
1364 unshift @args, '-q' unless $opt->{v} > 0;
1365 if ($opt->{B}) {
1366 unshift @args, "-B";
1367 }
1368 if ($opt->{L}) {
1369 unshift @args, "-L".$opt->{L};
1370 }
1371 if ($opt->{T}) {
1372 unshift @args, "-T".$opt->{T};
1373 }
1374 if ($opt->{P}) {
1375 unshift @args, $self->{parl};
1376 $self->{parl} = $^X;
1377 }
1378 $self->_vprint(0, "Running $self->{parl} @args");
1379  
1380 # Make sure the parl is callable. Prepend ./ if it's just a file name.
1381 my $parl = $self->{parl};
1382 my ($volume, $path, $file) = splitpath($parl);
1383 if (not defined $path or $path eq '') {
1384 $parl = catfile(curdir(), $parl);
1385 }
1386  
1387 system($parl, @args);
1388 }
1389  
1390 sub _fix_console {
1391 my ($self) = @_;
1392  
1393 my $opt = $self->{options};
1394 my $output = $self->{output};
1395 my $dynperl = $self->{dynperl};
1396  
1397 return unless $opt->{g};
1398  
1399 $self->_vprint(1, "Fixing $output to remove its console window");
1400  
1401 my ($record, $magic, $signature, $offset, $size);
1402  
1403 my $exe = $self->_open('+<', $output);
1404 binmode $exe;
1405 seek $exe, 0, 0;
1406  
1407 # read IMAGE_DOS_HEADER structure
1408 read $exe, $record, 64;
1409 ($magic, $offset) = unpack "Sx58L", $record;
1410  
1411 die "$output is not an MSDOS executable file.\n"
1412 unless $magic == 0x5a4d; # "MZ"
1413  
1414 # read signature, IMAGE_FILE_HEADER and first WORD of IMAGE_OPTIONAL_HEADER
1415 seek $exe, $offset, 0;
1416 read $exe, $record, 4 + 20 + 2;
1417  
1418 ($signature, $size, $magic) = unpack "Lx16Sx2S", $record;
1419  
1420 die "PE header not found" unless $signature == 0x4550; # "PE\0\0"
1421  
1422 die "Optional header is neither in NT32 nor in NT64 format"
1423 unless ($size == 224 && $magic == 0x10b) # IMAGE_NT_OPTIONAL_HDR32_MAGIC
1424 ||
1425 ($size == 240 && $magic == 0x20b); # IMAGE_NT_OPTIONAL_HDR64_MAGIC
1426  
1427 # Offset 68 in the IMAGE_OPTIONAL_HEADER(32|64) is the 16 bit subsystem code
1428 seek $exe, $offset + 4 + 20 + 68, 0;
1429 print $exe pack "S", 2; # IMAGE_WINDOWS
1430 close $exe;
1431 }
1432  
1433 sub _obj_function {
1434 my ($self, $module_or_class, $func_name) = @_;
1435  
1436 my $func;
1437 if (ref($module_or_class)) {
1438 $func = $module_or_class->can($func_name);
1439 die "SYSTEM ERROR: $func_name does not exist in $module_or_class\n"
1440 if (!$func);
1441  
1442 if (%$module_or_class) {
1443 # hack because Module::ScanDeps isn't really object.
1444 return sub { $func->($module_or_class, @_) };
1445 }
1446 else {
1447 return ($func);
1448 }
1449 }
1450 else {
1451 $func = $module_or_class->can($func_name);
1452 return ($func);
1453 }
1454 }
1455  
1456 sub _vprint {
1457 my ($self, $level, $msg) = @_;
1458  
1459 my $opt = $self->{options};
1460 my $logfh = $self->{logfh};
1461  
1462 $msg .= "\n" unless substr($msg, -1) eq "\n";
1463  
1464 my $verb = $ENV{PAR_VERBOSE} || 0;
1465 if ($opt->{v} > $level or $verb > $level) {
1466 if ($opt->{L}) {
1467 print $logfh "$0: $msg";
1468 }
1469 else {
1470 print "$0: $msg";
1471 }
1472 }
1473 }
1474  
1475 sub _check_par {
1476 my ($self, $file) = @_;
1477  
1478 local $/ = \4;
1479 my $handle = $self->_open($file);
1480 return (readline($handle) eq "PK\x03\x04");
1481 }
1482  
1483 # _chase_lib - find the runtime link of a shared library
1484 # Logic based on info found at the following sites:
1485 # http://lists.debian.org/lsb-spec/1999/05/msg00011.html
1486 # http://docs.sun.com/app/docs/doc/806-0641/6j9vuqujh?a=view#chapter5-97360
1487 sub _chase_lib {
1488 my ($self, $file) = @_;
1489  
1490 $file = abs_path($file);
1491  
1492 while ($Config{d_symlink} and -l $file) {
1493 if ($file =~ /^(.*?\.\Q$Config{dlext}\E\.\d+)\..*/) {
1494 return $1 if -e $1;
1495 }
1496  
1497 return $file if $file =~ /\.\Q$Config{dlext}\E\.\d+$/;
1498  
1499 my $dir = dirname($file);
1500 $file = readlink($file);
1501  
1502 unless (file_name_is_absolute($file)) {
1503 $file = rel2abs($file, $dir);
1504 }
1505 }
1506  
1507 if ($file =~ /^(.*?\.\Q$Config{dlext}\E\.\d+)\..*/) {
1508 return $1 if -e $1;
1509 }
1510  
1511 return $file;
1512 }
1513  
1514 sub _chase_lib_darwin {
1515 my ($self, $file) = @_;
1516  
1517 $file = abs_path($file);
1518  
1519 while (-l $file) {
1520 if ($file =~ /^(.*?\.\d+)(\.\d+)*\.dylib$/) {
1521 my $name = $1 . q/.dylib/;
1522 return $name if -e $name;
1523 }
1524  
1525 return $file if $file =~ /\D\.\d+\.dylib$/;
1526  
1527 my $dir = dirname($file);
1528 $file = readlink($file);
1529  
1530 unless (file_name_is_absolute($file)) {
1531 $file = rel2abs($file, $dir);
1532 }
1533 }
1534  
1535 if ($file =~ /^(.*?\.\d+)(\.\d+)*\.dylib$/) {
1536 my $name = $1 . q/.dylib/;
1537 return $name if -e $name;
1538 }
1539  
1540 return $file;
1541 }
1542  
1543  
1544 sub _find_shlib {
1545 my ($self, $file) = @_;
1546  
1547 if (-e $file) {
1548 my $abs_file = abs_path($file);
1549 $self->_vprint(1, "... found library $file: $abs_file");
1550 return $abs_file;
1551 }
1552  
1553 $self->_die("Shared library (option --link) doesn't exist: $file")
1554 if $file =~ /[\/\\]/;
1555  
1556 my @libpath;
1557 if ($^O eq 'MSWin32') {
1558 @libpath = (path(), '.'); # cwd() is always implicitly searched
1559 }
1560 else {
1561 # NOTE: libpth is actually supposed to be the path searched
1562 # by the linker (ld) and *not* the path searched by the runtime
1563 # loader (ld.so). But it's the best guess we've got.
1564 @libpath = split(' ', $Config{libpth});
1565  
1566 # add $ENV{LD_LIBRARY_PATH} (or equivalent) if defined
1567 my $ldlibpath = $ENV{ $Config{ldlibpthname} };
1568 unshift @libpath, split(/\Q$Config{path_sep}\E/, $ldlibpath)
1569 if defined $ldlibpath;
1570 }
1571  
1572 if (my $lib = $self->_find_shlib_in_path($file, @libpath)) {
1573 $self->_vprint(1, "... found library $file: $lib");
1574 return $lib;
1575 }
1576  
1577 $self->_die("Can't find shared library (option --link): $file")
1578 if $^O eq 'MSWin32' || $file =~ /^lib/;
1579  
1580 # be extra magical and prepend "lib" to the filename
1581 if (my $lib = $self->_find_shlib_in_path("lib$file", @libpath)) {
1582 $self->_vprint(1, "... found library $file: $lib");
1583 return $lib;
1584 }
1585  
1586 $self->_die("Can't find shared library (option --link): $file (also tried lib$file)");
1587 }
1588  
1589 sub _find_shlib_in_path
1590 {
1591 my ($self, $file, @path) = @_;
1592  
1593 my $dlext = $^O eq 'darwin' ? 'dylib' : $Config{dlext};
1594 for my $dir (@path)
1595 {
1596 $dir = '.' if $dir eq '';
1597 foreach my $p (catfile($dir, $file), catfile($dir, "$file.$dlext"))
1598 {
1599 return abs_path($p) if -e $p;
1600 }
1601 }
1602 return;
1603 }
1604  
1605 sub _can_run {
1606 my ($self, $command, $no_exec) = @_;
1607  
1608 for my $dir (dirname($0),
1609 split(/\Q$Config{path_sep}\E/, $ENV{PATH}))
1610 {
1611 my $abs = catfile($dir, $command);
1612 return $abs if $no_exec or $abs = MM->maybe_command($abs);
1613 }
1614 return;
1615 }
1616  
1617 sub _main_pl_multi {
1618 my ($self) = @_;
1619  
1620 # insert code for @INC cleaning (in case of bundling core modules)
1621 my $clean_inc = $self->_main_pl_clean();
1622 # insert code for reusable apps
1623 my $reuse_app = $self->_main_pl_reuse();
1624  
1625 # FIXME The $reuse_app code was written for _main_pl_single -- is it correct for this as well?
1626 return $reuse_app . "\n" . <<'__MAIN__' . $clean_inc . "PAR::_run_member(\$member, 1);\n\n";
1627 my $file = $ENV{PAR_PROGNAME};
1628 my $zip = $PAR::LibCache{$ENV{PAR_PROGNAME}} || Archive::Zip->new(__FILE__);
1629 $file =~ s/^.*[\/\\]//;
1630 $file =~ s/\.[^.]*$//i ;
1631 my $member = eval { $zip->memberNamed($file) }
1632 || $zip->memberNamed("$file.pl")
1633 || $zip->memberNamed("script/$file")
1634 || $zip->memberNamed("script/$file.pl")
1635 or die qq(main.pl: Can't open perl script "$file": No such file or directory);
1636  
1637 __MAIN__
1638 }
1639  
1640 sub _open {
1641 my ($self, $mode, $file, $is_text) = @_;
1642 ($mode, $file) = ('<', $mode) if @_ < 3;
1643 open(my $fh, $mode, $file) or $self->_die(
1644 "Cannot open $file for ",
1645 (($mode =~ '>') ? 'writing' : 'reading'),
1646 ": $!",
1647 );
1648 binmode($fh) unless $is_text;
1649 return $fh;
1650 }
1651  
1652 sub _main_pl_single {
1653 my ($self, $file) = @_;
1654  
1655 # insert code for @INC cleaning (in case of bundling core modules)
1656 my $clean_inc = $self->_main_pl_clean();
1657 # insert code for reusable apps
1658 my $reuse_app = $self->_main_pl_reuse();
1659  
1660 return << "__MAIN__";
1661  
1662 $reuse_app
1663  
1664 my \$zip = \$PAR::LibCache{\$ENV{PAR_PROGNAME}} || Archive::Zip->new(__FILE__);
1665 my \$member = eval { \$zip->memberNamed('$file') }
1666 or die qq(main.pl: Can't open perl script "$file": No such file or directory (\$zip));
1667  
1668 $clean_inc
1669  
1670 PAR::_run_member(\$member, 1);
1671  
1672 __MAIN__
1673 }
1674  
1675 sub _main_pl_reuse {
1676 my $self = shift;
1677  
1678 my $opt = $self->{options};
1679  
1680 if (!$opt->{reusable}) {
1681 return <<'__NOT_REUSABLE__';
1682 if (defined $ENV{PAR_APP_REUSE}) {
1683 warn "Executable was created without the --reusable option. See 'perldoc pp'.\n";
1684 exit(1);
1685 }
1686 __NOT_REUSABLE__
1687 }
1688  
1689 # insert code for @INC cleaning (in case of bundling core modules)
1690 my $clean_inc = $self->_main_pl_clean();
1691  
1692 my $reuse = <<__REUSE_APP__;
1693 if (defined \$ENV{PAR_APP_REUSE}) {
1694 my \$filename = \$ENV{PAR_APP_REUSE};
1695 delete \$ENV{PAR_APP_REUSE};
1696 \$ENV{PAR_0} = \$filename;
1697  
1698 $clean_inc
1699  
1700 PAR::_run_external_file(\$filename, 1);
1701 exit();
1702 }
1703 __REUSE_APP__
1704  
1705 return $reuse;
1706 }
1707  
1708 sub _main_pl_clean {
1709 my $self = shift;
1710 my $opt = $self->{options};
1711  
1712 my $clean_inc = '';
1713 if ($opt->{B}) { # bundle core modules
1714 # weed out all @INC entries
1715 # use a canonicalized $ENV{PAR_TEMP}: this path was created by C code
1716 # and may not be in canonical form (so that the match below will
1717 # fail); case inpoint: some versions of FreeBSD have
1718 # #define P_tmpdir "/var/tmp/"
1719 # in /usr/include/stdio.h (note the trailing slash)
1720 $clean_inc = <<'__CLEAN_INC__';
1721 # Remove everything but PAR hooks from @INC
1722 my %keep = (
1723 \&PAR::find_par => 1,
1724 \&PAR::find_par_last => 1,
1725 );
1726 my $par_temp_dir = File::Spec->catdir( $ENV{PAR_TEMP} );
1727 @INC =
1728 grep {
1729 exists($keep{$_})
1730 or $_ =~ /^\Q$par_temp_dir\E/;
1731 }
1732 @INC;
1733 __CLEAN_INC__
1734 };
1735  
1736 return $clean_inc;
1737 }
1738  
1739 sub DESTROY {
1740 my ($self) = @_;
1741  
1742 my $par_file = $self->{par_file};
1743 my $opt = $self->{options};
1744  
1745 unlink $par_file if ($par_file and !$opt->{S} and !$opt->{p});
1746 unlink $self->{parl} if $self->{parl_is_temporary};
1747 }
1748  
1749  
1750  
1751 1;
1752  
1753 =head1 SEE ALSO
1754  
1755 L<PAR>, L<pp>
1756  
1757 L<App::Packer>, L<App::Packer::Backend>
1758  
1759 =head1 ACKNOWLEDGMENTS
1760  
1761 Mattia Barbon for taking the first step in refactoring B<pp> into
1762 B<App::Packer::Backend::PAR>, and Edward S. Peschko for continuing
1763 the work that eventually became this module.
1764  
1765 =head1 AUTHORS
1766  
1767 Audrey Tang E<lt>cpan@audreyt.orgE<gt>
1768  
1769 Steffen Mueller E<lt>smueller@cpan.orgE<gt>
1770  
1771 Roderich Schupp E<lt>rschupp@cpan.orgE<gt>
1772  
1773 You can write
1774 to the mailing list at E<lt>par@perl.orgE<gt>, or send an empty mail to
1775 E<lt>par-subscribe@perl.orgE<gt> to participate in the discussion.
1776  
1777 Please submit bug reports to E<lt>bug-par-packer@rt.cpan.orgE<gt>.
1778  
1779 =head1 COPYRIGHT
1780  
1781 Copyright 2004-2010 by Audrey Tang E<lt>cpan@audreyt.orgE<gt>.
1782  
1783 This program is free software; you can redistribute it and/or modify it
1784 under the same terms as Perl itself.
1785  
1786 See F<LICENSE>.
1787  
1788 =cut