lib/PAR/Packer.pm untested

filter: Statementstmt 0.0% 0 / 892 Branchbran 0.0% 0 / 376 Conditioncond 0.0% 0 / 191 MC/DCmcdc 0.0% 0 / 117 Subroutinesub 0.0% 0 / 83 Podpod 0.0% 0 / 62 totaltotal 0.0% 0 / 1721 CC 188 SCAR 52.1
CC
188
Cov
0%
pack_manifest_hash
1056.0
_parse_opts
462.0
_add_file
72.0
CRAP 183.1
1 package PAR::Packer;
2 use 5.008001;
3 use strict;
4 use warnings;
5  
6 our $VERSION = '1.064';
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 {
1046 local $/ = "\n";
1047 foreach my $list (@$lists) {
1048 my $fh = $self->_open('<', $list, 'text');
1049 while (my $line = <$fh>) {
1050 chomp($line);
1051 push(@$files, $line);
1052 }
1053 }
1054 }
1055  
1056 foreach my $src_dst (grep length, @$files) {
1057 $src_dst =~ s{\\}{/}g;
1058  
1059 my ($src, $dst) = split(";", $src_dst, 2);
1060 $dst = $src unless defined $dst;
1061  
1062 $dst =~ s{^[a-zA-Z]:}{} if $^O eq 'MSWin32';
1063 $dst =~ s{^/}{};
1064 die qq[--addfile/--addlist target path "$src_dst" must not contain components "." or ".."]
1065 if grep { /^\.\.?$/ } split("/", $dst);
1066 push(@$return, [ $src, $dst ]);
1067 }
1068 return $return;
1069 }
1070  
1071 sub add_manifest {
1072 my ($self) = @_;
1073 my $mh = $self->add_manifest_hash();
1074  
1075 my @ma = sort keys(%$mh);
1076 return (\@ma);
1077 }
1078  
1079 sub _add_pack_manifest {
1080 my ($self) = @_;
1081  
1082 my $par_file = $self->{par_file};
1083 my $opt = $self->{options};
1084  
1085 $self->{zip} ||= Archive::Zip->new;
1086 my $zip = $self->{zip};
1087  
1088 my $input = $self->{input};
1089  
1090 $self->_vprint(1, "Writing PAR on $par_file");
1091  
1092 $zip->read($par_file) if ($opt->{'m'} and -e $par_file);
1093  
1094 my $pack_manifest = $self->pack_manifest_hash();
1095  
1096 my $map = $self->{pack_attrib}{map};
1097 my $root = $self->{pack_attrib}{root};
1098 my $shared_libs = $self->{pack_attrib}{shared_libs};
1099  
1100 $zip->addDirectory('', substr($root, 0, -1))->unixFileAttributes(0755) if ($root and %$map);
1101 $zip->addDirectory('', $root . 'lib')->unixFileAttributes(0755) if %$map;
1102  
1103 my $shlib = "shlib/$Config{archname}";
1104 $zip->addDirectory('', $shlib)->unixFileAttributes(0755) if @$shared_libs;
1105  
1106 my @tmp_input = @$input;
1107 @tmp_input = grep !/\.pm\z/i, @tmp_input;
1108  
1109 $zip->addDirectory('', 'script')->unixFileAttributes(0755) if @tmp_input;
1110  
1111 my $in;
1112 foreach $in (sort keys(%$pack_manifest)) {
1113 my $value = $pack_manifest->{$in};
1114 $self->_add_file($zip, $in, $value);
1115 }
1116  
1117 }
1118  
1119 sub dep_files {
1120 my ($self) = @_;
1121  
1122 my $dm = $self->{dep_manifest};
1123 return ([ keys(%$dm) ]) if ($dm);
1124  
1125 }
1126  
1127 sub _add_file {
1128 my ($self, $zip, $in, $value, $manifest) = @_;
1129  
1130 my $level = $self->{options}->{z};
1131 my $method = $level ? Archive::Zip::COMPRESSION_DEFLATED
1132 : Archive::Zip::COMPRESSION_STORED;
1133 my $oldsize = $self->{pack_attrib}{old_size};
1134 my $full_manifest = $self->{full_manifest};
1135  
1136 if ($value->[0] eq 'file') {
1137 my $fn = $value->[1];
1138  
1139 if (-d $fn) {
1140 my ($files, $aliases) = $self->_expand_dir($fn, $in);
1141  
1142 $self->_vprint(1, "... adding $fn as $in\n");
1143  
1144 while (@$files) {
1145 my $file = shift @$files;
1146 my $alias = shift @$aliases;
1147  
1148 if (exists $dep_zip_files{$alias}) {
1149 $dep_zips{$dep_zip_files{$alias}}++;
1150 next;
1151 }
1152 $self->_vprint(1, "... adding $file as $alias\n");
1153  
1154 $full_manifest->{ $alias } = [ file => $file ];
1155 $manifest->{ $alias } = [ file => $file ];
1156  
1157 $oldsize += -s $file;
1158 my $member = $zip->addFile($file, $alias);
1159 $member->desiredCompressionMethod($method);
1160 $member->desiredCompressionLevel($level);
1161 }
1162 }
1163 elsif (-e $fn and -r $fn) {
1164 if (exists $dep_zip_files{$in}) {
1165 $dep_zips{$dep_zip_files{$in}}++;
1166 return;
1167 }
1168 $self->_vprint(1, "... adding $fn as $in\n");
1169  
1170 $oldsize += -s $fn;
1171 my $member = $zip->addFile($fn => $in);
1172 $member->desiredCompressionMethod($method);
1173 $member->desiredCompressionLevel($level);
1174 }
1175 }
1176 else {
1177 if (exists $dep_zip_files{$in}) {
1178 $dep_zips{$dep_zip_files{$in}}++;
1179 return;
1180 }
1181 my $str = $value->[1];
1182 $oldsize += length($str);
1183  
1184 $self->_vprint(1, "... adding <string> as $in");
1185 my $member = $zip->addString($str => $in);
1186 $member->unixFileAttributes(0644);
1187 $member->desiredCompressionMethod($method);
1188 $member->desiredCompressionLevel($level);
1189 }
1190  
1191 $self->{pack_attrib}{old_size} = $oldsize;
1192 }
1193  
1194 sub _expand_dir {
1195 my ($self, $fn, $in) = @_;
1196 my (@return, @alias_return);
1197  
1198 File::Find::find(
1199 {
1200 wanted => sub { push(@return, $File::Find::name) if -f },
1201 follow_fast => ( ($^O eq 'MSWin32') ? 0 : 1 ),
1202 },
1203 $fn
1204 );
1205  
1206 @alias_return = @return;
1207 s/^\Q$fn\E/$in/ for @alias_return;
1208  
1209 return (\@return, \@alias_return);
1210 }
1211  
1212 sub _die {
1213 my ($self, @args) = @_;
1214 $self->_log(@args);
1215  
1216 my $sn = $self->{script_name};
1217 die "$sn: ", @args;
1218 }
1219  
1220 sub _warn {
1221 my ($self, @args) = @_;
1222 $self->_log(@args);
1223  
1224 my $sn = $self->{script_name};
1225 warn "$sn: ", @args;
1226 }
1227  
1228 sub _log {
1229 my ($self, @args) = @_;
1230  
1231 my $opt = $self->{options};
1232 my $logfh = $self->{logfh};
1233 my $sn = $self->{script_name};
1234  
1235 $logfh->print("$sn: ", @args) if ($opt->{L});
1236 }
1237  
1238 sub _name2moddata {
1239 my ($self, $name, $mod, $dat) = @_;
1240  
1241 if ($name =~ /^[\w:]+$/) {
1242 $name =~ s/::/\//g;
1243 push @$mod, "$name.pm";
1244 }
1245 elsif ($name =~ /$PerlExtensionRegex/) {
1246 push @$mod, $name;
1247 }
1248 else {
1249  
1250 if (!-e $name) {
1251 $self->_warn( "-M or -X option file not found: $name\n" );
1252 }
1253 else {
1254 $self->_warn(
1255 "Using -M to add non-library files is deprecated; ",
1256 "try -a instead\n",
1257 ) if $mod != $dat;
1258 push @$dat, $name;
1259 }
1260 }
1261 }
1262  
1263 sub _par_to_exe {
1264 my ($self) = @_;
1265  
1266 my $opt = $self->{options};
1267 my $output = $self->{output};
1268 my $dynperl = $self->{dynperl};
1269 my $par_file = $self->{par_file};
1270  
1271 require PAR::StrippedPARL::Static;
1272 require PAR::StrippedPARL::Dynamic;
1273  
1274 my $parlclass = 'PAR::StrippedPARL::Static';
1275 my $buf;
1276 my $parl = 'parl';
1277  
1278 if ($opt->{d} and $dynperl) {
1279 $parlclass = 'PAR::StrippedPARL::Dynamic';
1280 $parl = 'parldyn';
1281 }
1282 $parl .= $Config{_exe};
1283  
1284 if ($opt->{P}) {
1285 # write as script
1286 $parl = 'par.pl';
1287 unless ( $parl = $self->_can_run($parl, $opt->{P}) ) {
1288 $self->_die("par.pl not found");
1289 }
1290 $self->{parl} = $parl;
1291 }
1292 else {
1293 # binary, either static or dynamic
1294 $parl = $self->_extract_parl($parlclass)
1295 or $self->_die("Can't find par loader");
1296 $self->{parl_is_temporary} = 1;
1297 $self->{parl} = $parl;
1298 }
1299  
1300 if ($^O ne 'MSWin32' or $opt->{p} or $opt->{P}) {
1301 $self->_generate_output();
1302 }
1303 else {
1304 $self->_generate_output();
1305 $self->_fix_console() if $opt->{g};
1306 }
1307 }
1308  
1309 # extracts a parl (static) or parldyn (dynamic) from the appropriate data class
1310 # using the class' write_parl($file) method. Note that 'write_parl' extracts to
1311 # a temporary file first, then uses that plain parl to embed the core modules into
1312 # the file given as argument. This was taken from the PAR bootstrapping process.
1313 # First argument must be the class name.
1314 # Returns the path and name of the file (or the empty list on failure).
1315 sub _extract_parl {
1316 my $self = shift;
1317 my $class = shift;
1318  
1319 $self->_die("First argument to _extract_parl must be a class name")
1320 if not defined $class;
1321 $self->_die("Class '$class' is not a PAR(L) data class. Can't call '${class}->write_parl()'")
1322 if not $class->can('write_parl');
1323  
1324 $self->_vprint(0, "Generating a fresh 'parl'.");
1325 my ($fh, $filename) = tempfile(
1326 "parlXXXXXXX", SUFFIX => $Config{_exe}, TMPDIR => 1, UNLINK => 1);
1327 close $fh;
1328  
1329 my $success = $class->write_parl($filename);
1330 if (not $success) {
1331 $self->_die("Failed to extract a parl from '$class' to file '$filename'");
1332 }
1333  
1334 chmod(oct('755'), $filename);
1335 return $filename;
1336 }
1337  
1338  
1339 sub _move_parl {
1340 my ($self) = @_;
1341  
1342 $self->{orig_parl} = $self->{parl};
1343  
1344 my $cfh;
1345 my $fh = $self->_open($self->{parl});
1346 ($cfh, $self->{parl}) = tempfile(
1347 "parlXXXX", SUFFIX => ".exe", TMPDIR => 1, UNLINK => 1);
1348 binmode($cfh);
1349  
1350 local $/;
1351 print $cfh readline($fh);
1352 close $cfh;
1353  
1354 $self->{fh} = $fh;
1355 }
1356  
1357 sub _generate_output {
1358 my ($self) = @_;
1359  
1360 my $opt = $self->{options};
1361 my $output = $self->{output};
1362 my $par_file = $self->{par_file};
1363  
1364 my @args = ("-O$output", $par_file);
1365 unshift @args, '-q' unless $opt->{v} > 0;
1366 if ($opt->{B}) {
1367 unshift @args, "-B";
1368 }
1369 if ($opt->{L}) {
1370 unshift @args, "-L".$opt->{L};
1371 }
1372 if ($opt->{T}) {
1373 unshift @args, "-T".$opt->{T};
1374 }
1375 if ($opt->{P}) {
1376 unshift @args, $self->{parl};
1377 $self->{parl} = $^X;
1378 }
1379 $self->_vprint(0, "Running $self->{parl} @args");
1380  
1381 # Make sure the parl is callable. Prepend ./ if it's just a file name.
1382 my $parl = $self->{parl};
1383 my ($volume, $path, $file) = splitpath($parl);
1384 if (not defined $path or $path eq '') {
1385 $parl = catfile(curdir(), $parl);
1386 }
1387  
1388 system($parl, @args);
1389 }
1390  
1391 sub _fix_console {
1392 my ($self) = @_;
1393  
1394 my $opt = $self->{options};
1395 my $output = $self->{output};
1396 my $dynperl = $self->{dynperl};
1397  
1398 return unless $opt->{g};
1399  
1400 $self->_vprint(1, "Fixing $output to remove its console window");
1401  
1402 my ($record, $magic, $signature, $offset, $size);
1403  
1404 my $exe = $self->_open('+<', $output);
1405 binmode $exe;
1406 seek $exe, 0, 0;
1407  
1408 # read IMAGE_DOS_HEADER structure
1409 read $exe, $record, 64;
1410 ($magic, $offset) = unpack "Sx58L", $record;
1411  
1412 die "$output is not an MSDOS executable file.\n"
1413 unless $magic == 0x5a4d; # "MZ"
1414  
1415 # read signature, IMAGE_FILE_HEADER and first WORD of IMAGE_OPTIONAL_HEADER
1416 seek $exe, $offset, 0;
1417 read $exe, $record, 4 + 20 + 2;
1418  
1419 ($signature, $size, $magic) = unpack "Lx16Sx2S", $record;
1420  
1421 die "PE header not found" unless $signature == 0x4550; # "PE\0\0"
1422  
1423 die "Optional header is neither in NT32 nor in NT64 format"
1424 unless ($size == 224 && $magic == 0x10b) # IMAGE_NT_OPTIONAL_HDR32_MAGIC
1425 ||
1426 ($size == 240 && $magic == 0x20b); # IMAGE_NT_OPTIONAL_HDR64_MAGIC
1427  
1428 # Offset 68 in the IMAGE_OPTIONAL_HEADER(32|64) is the 16 bit subsystem code
1429 seek $exe, $offset + 4 + 20 + 68, 0;
1430 print $exe pack "S", 2; # IMAGE_WINDOWS
1431 close $exe;
1432 }
1433  
1434 sub _obj_function {
1435 my ($self, $module_or_class, $func_name) = @_;
1436  
1437 my $func;
1438 if (ref($module_or_class)) {
1439 $func = $module_or_class->can($func_name);
1440 die "SYSTEM ERROR: $func_name does not exist in $module_or_class\n"
1441 if (!$func);
1442  
1443 if (%$module_or_class) {
1444 # hack because Module::ScanDeps isn't really object.
1445 return sub { $func->($module_or_class, @_) };
1446 }
1447 else {
1448 return ($func);
1449 }
1450 }
1451 else {
1452 $func = $module_or_class->can($func_name);
1453 return ($func);
1454 }
1455 }
1456  
1457 sub _vprint {
1458 my ($self, $level, $msg) = @_;
1459  
1460 my $opt = $self->{options};
1461 my $logfh = $self->{logfh};
1462  
1463 $msg .= "\n" unless substr($msg, -1) eq "\n";
1464  
1465 my $verb = $ENV{PAR_VERBOSE} || 0;
1466 if ($opt->{v} > $level or $verb > $level) {
1467 if ($opt->{L}) {
1468 print $logfh "$0: $msg";
1469 }
1470 else {
1471 print "$0: $msg";
1472 }
1473 }
1474 }
1475  
1476 sub _check_par {
1477 my ($self, $file) = @_;
1478  
1479 local $/ = \4;
1480 my $handle = $self->_open($file);
1481 return (readline($handle) eq "PK\x03\x04");
1482 }
1483  
1484 # _chase_lib - find the runtime link of a shared library
1485 # Logic based on info found at the following sites:
1486 # http://lists.debian.org/lsb-spec/1999/05/msg00011.html
1487 # http://docs.sun.com/app/docs/doc/806-0641/6j9vuqujh?a=view#chapter5-97360
1488 sub _chase_lib {
1489 my ($self, $file) = @_;
1490  
1491 $file = abs_path($file);
1492  
1493 while ($Config{d_symlink} and -l $file) {
1494 if ($file =~ /^(.*?\.\Q$Config{dlext}\E\.\d+)\..*/) {
1495 return $1 if -e $1;
1496 }
1497  
1498 return $file if $file =~ /\.\Q$Config{dlext}\E\.\d+$/;
1499  
1500 my $dir = dirname($file);
1501 $file = readlink($file);
1502  
1503 unless (file_name_is_absolute($file)) {
1504 $file = rel2abs($file, $dir);
1505 }
1506 }
1507  
1508 if ($file =~ /^(.*?\.\Q$Config{dlext}\E\.\d+)\..*/) {
1509 return $1 if -e $1;
1510 }
1511  
1512 return $file;
1513 }
1514  
1515 sub _chase_lib_darwin {
1516 my ($self, $file) = @_;
1517  
1518 $file = abs_path($file);
1519  
1520 while (-l $file) {
1521 if ($file =~ /^(.*?\.\d+)(\.\d+)*\.dylib$/) {
1522 my $name = $1 . q/.dylib/;
1523 return $name if -e $name;
1524 }
1525  
1526 return $file if $file =~ /\D\.\d+\.dylib$/;
1527  
1528 my $dir = dirname($file);
1529 $file = readlink($file);
1530  
1531 unless (file_name_is_absolute($file)) {
1532 $file = rel2abs($file, $dir);
1533 }
1534 }
1535  
1536 if ($file =~ /^(.*?\.\d+)(\.\d+)*\.dylib$/) {
1537 my $name = $1 . q/.dylib/;
1538 return $name if -e $name;
1539 }
1540  
1541 return $file;
1542 }
1543  
1544  
1545 sub _find_shlib {
1546 my ($self, $file) = @_;
1547  
1548 if (-e $file) {
1549 my $abs_file = abs_path($file);
1550 $self->_vprint(1, "... found library $file: $abs_file");
1551 return $abs_file;
1552 }
1553  
1554 $self->_die("Shared library (option --link) doesn't exist: $file")
1555 if $file =~ /[\/\\]/;
1556  
1557 my @libpath;
1558 if ($^O eq 'MSWin32') {
1559 @libpath = (path(), '.'); # cwd() is always implicitly searched
1560 }
1561 else {
1562 # NOTE: libpth is actually supposed to be the path searched
1563 # by the linker (ld) and *not* the path searched by the runtime
1564 # loader (ld.so). But it's the best guess we've got.
1565 @libpath = split(' ', $Config{libpth});
1566  
1567 # add $ENV{LD_LIBRARY_PATH} (or equivalent) if defined
1568 my $ldlibpath = $ENV{ $Config{ldlibpthname} };
1569 unshift @libpath, split(/\Q$Config{path_sep}\E/, $ldlibpath)
1570 if defined $ldlibpath;
1571 }
1572  
1573 if (my $lib = $self->_find_shlib_in_path($file, @libpath)) {
1574 $self->_vprint(1, "... found library $file: $lib");
1575 return $lib;
1576 }
1577  
1578 $self->_die("Can't find shared library (option --link): $file")
1579 if $^O eq 'MSWin32' || $file =~ /^lib/;
1580  
1581 # be extra magical and prepend "lib" to the filename
1582 if (my $lib = $self->_find_shlib_in_path("lib$file", @libpath)) {
1583 $self->_vprint(1, "... found library $file: $lib");
1584 return $lib;
1585 }
1586  
1587 $self->_die("Can't find shared library (option --link): $file (also tried lib$file)");
1588 }
1589  
1590 sub _find_shlib_in_path
1591 {
1592 my ($self, $file, @path) = @_;
1593  
1594 my $dlext = $^O eq 'darwin' ? 'dylib' : $Config{dlext};
1595 for my $dir (@path)
1596 {
1597 $dir = '.' if $dir eq '';
1598 foreach my $p (catfile($dir, $file), catfile($dir, "$file.$dlext"))
1599 {
1600 return abs_path($p) if -e $p;
1601 }
1602 }
1603 return;
1604 }
1605  
1606 sub _can_run {
1607 my ($self, $command, $no_exec) = @_;
1608  
1609 for my $dir (dirname($0),
1610 split(/\Q$Config{path_sep}\E/, $ENV{PATH}))
1611 {
1612 my $abs = catfile($dir, $command);
1613 return $abs if $no_exec or $abs = MM->maybe_command($abs);
1614 }
1615 return;
1616 }
1617  
1618 sub _main_pl_multi {
1619 my ($self) = @_;
1620  
1621 # insert code for @INC cleaning (in case of bundling core modules)
1622 my $clean_inc = $self->_main_pl_clean();
1623 # insert code for reusable apps
1624 my $reuse_app = $self->_main_pl_reuse();
1625  
1626 # FIXME The $reuse_app code was written for _main_pl_single -- is it correct for this as well?
1627 return $reuse_app . "\n" . <<'__MAIN__' . $clean_inc . "PAR::_run_member(\$member, 1);\n\n";
1628 my $file = $ENV{PAR_PROGNAME};
1629 my $zip = $PAR::LibCache{$ENV{PAR_PROGNAME}} || Archive::Zip->new(__FILE__);
1630 $file =~ s/^.*[\/\\]//;
1631 $file =~ s/\.[^.]*$//i ;
1632 my $member = eval { $zip->memberNamed($file) }
1633 || $zip->memberNamed("$file.pl")
1634 || $zip->memberNamed("script/$file")
1635 || $zip->memberNamed("script/$file.pl")
1636 or die qq(main.pl: Can't open perl script "$file": No such file or directory);
1637  
1638 __MAIN__
1639 }
1640  
1641 sub _open {
1642 my ($self, $mode, $file, $is_text) = @_;
1643 ($mode, $file) = ('<', $mode) if @_ < 3;
1644 open(my $fh, $mode, $file) or $self->_die(
1645 "Cannot open $file for ",
1646 (($mode =~ '>') ? 'writing' : 'reading'),
1647 ": $!",
1648 );
1649 binmode($fh) unless $is_text;
1650 return $fh;
1651 }
1652  
1653 sub _main_pl_single {
1654 my ($self, $file) = @_;
1655  
1656 # insert code for @INC cleaning (in case of bundling core modules)
1657 my $clean_inc = $self->_main_pl_clean();
1658 # insert code for reusable apps
1659 my $reuse_app = $self->_main_pl_reuse();
1660  
1661 return << "__MAIN__";
1662  
1663 $reuse_app
1664  
1665 my \$zip = \$PAR::LibCache{\$ENV{PAR_PROGNAME}} || Archive::Zip->new(__FILE__);
1666 my \$member = eval { \$zip->memberNamed('$file') }
1667 or die qq(main.pl: Can't open perl script "$file": No such file or directory (\$zip));
1668  
1669 $clean_inc
1670  
1671 PAR::_run_member(\$member, 1);
1672  
1673 __MAIN__
1674 }
1675  
1676 sub _main_pl_reuse {
1677 my $self = shift;
1678  
1679 my $opt = $self->{options};
1680  
1681 if (!$opt->{reusable}) {
1682 return <<'__NOT_REUSABLE__';
1683 if (defined $ENV{PAR_APP_REUSE}) {
1684 warn "Executable was created without the --reusable option. See 'perldoc pp'.\n";
1685 exit(1);
1686 }
1687 __NOT_REUSABLE__
1688 }
1689  
1690 # insert code for @INC cleaning (in case of bundling core modules)
1691 my $clean_inc = $self->_main_pl_clean();
1692  
1693 my $reuse = <<__REUSE_APP__;
1694 if (defined \$ENV{PAR_APP_REUSE}) {
1695 my \$filename = \$ENV{PAR_APP_REUSE};
1696 delete \$ENV{PAR_APP_REUSE};
1697 \$ENV{PAR_0} = \$filename;
1698  
1699 $clean_inc
1700  
1701 PAR::_run_external_file(\$filename, 1);
1702 exit();
1703 }
1704 __REUSE_APP__
1705  
1706 return $reuse;
1707 }
1708  
1709 sub _main_pl_clean {
1710 my $self = shift;
1711 my $opt = $self->{options};
1712  
1713 my $clean_inc = '';
1714 if ($opt->{B}) { # bundle core modules
1715 # weed out all @INC entries
1716 # use a canonicalized $ENV{PAR_TEMP}: this path was created by C code
1717 # and may not be in canonical form (so that the match below will
1718 # fail); case inpoint: some versions of FreeBSD have
1719 # #define P_tmpdir "/var/tmp/"
1720 # in /usr/include/stdio.h (note the trailing slash)
1721 $clean_inc = <<'__CLEAN_INC__';
1722 # Remove everything but PAR hooks from @INC
1723 my %keep = (
1724 \&PAR::find_par => 1,
1725 \&PAR::find_par_last => 1,
1726 );
1727 my $par_temp_dir = File::Spec->catdir( $ENV{PAR_TEMP} );
1728 @INC =
1729 grep {
1730 exists($keep{$_})
1731 or $_ =~ /^\Q$par_temp_dir\E/;
1732 }
1733 @INC;
1734 __CLEAN_INC__
1735 };
1736  
1737 return $clean_inc;
1738 }
1739  
1740 sub DESTROY {
1741 my ($self) = @_;
1742  
1743 my $par_file = $self->{par_file};
1744 my $opt = $self->{options};
1745  
1746 unlink $par_file if ($par_file and !$opt->{S} and !$opt->{p});
1747 unlink $self->{parl} if $self->{parl_is_temporary};
1748 }
1749  
1750  
1751  
1752 1;
1753  
1754 =head1 SEE ALSO
1755  
1756 L<PAR>, L<pp>
1757  
1758 L<App::Packer>, L<App::Packer::Backend>
1759  
1760 =head1 ACKNOWLEDGMENTS
1761  
1762 Mattia Barbon for taking the first step in refactoring B<pp> into
1763 B<App::Packer::Backend::PAR>, and Edward S. Peschko for continuing
1764 the work that eventually became this module.
1765  
1766 =head1 AUTHORS
1767  
1768 Audrey Tang E<lt>cpan@audreyt.orgE<gt>
1769  
1770 Steffen Mueller E<lt>smueller@cpan.orgE<gt>
1771  
1772 Roderich Schupp E<lt>roderich.schupp@gmail.comE<gt>
1773  
1774 You can write
1775 to the mailing list at E<lt>par@perl.orgE<gt>, or send an empty mail to
1776 E<lt>par-subscribe@perl.orgE<gt> to participate in the discussion.
1777 Archives of the mailing list are available at
1778 E<lt>https://www.mail-archive.com/par@perl.org/E<gt> or E<lt>https://groups.google.com/g/perl.parE<gt>.
1779  
1780 Please submit bug reports to E<lt>https://github.com/rschupp/PAR-Packer/issuesE<gt>.
1781  
1782 =head1 COPYRIGHT
1783  
1784 Copyright 2004-2010 by Audrey Tang E<lt>cpan@audreyt.orgE<gt>.
1785  
1786 This program is free software; you can redistribute it and/or modify it
1787 under the same terms as Perl itself.
1788  
1789 See F<LICENSE>.
1790  
1791 =cut