script/par.pl untested

filter: Statementstmt 0.0% 0 / 551 Branchbran 0.0% 0 / 200 Conditioncond 0.0% 0 / 128 MC/DCmcdc 0.0% 0 / 75 Subroutinesub 0.0% 0 / 70 Podpod 0.0% 0 / 13 totaltotal 0.0% 0 / 1037 CC 128 SCAR 83.6
CC
128
Cov
0%
BEGIN
8930.0
_set_par_temp
132.0
_set_progname
110.0
CRAP 4276.3
1 #!/usr/local/bin/perl
2 eval 'exec /usr/bin/perl -S $0 ${1+"$@"}'
3 if 0; # not running under some shell
4  
5 package __par_pl;
6  
7 # --- This script must not use any modules at compile time ---
8 # use strict;
9  
10 =head1 NAME
11  
12 par.pl - Make and run Perl Archives
13  
14 =head1 SYNOPSIS
15  
16 (Please see L<pp> for convenient ways to make self-contained
17 executables, scripts or PAR archives from perl programs.)
18  
19 To make a I<PAR distribution> from a CPAN module distribution:
20  
21 % par.pl -p # make a PAR dist under the current path
22 % par.pl -p Foo-0.01 # assume unpacked CPAN dist in Foo-0.01/
23  
24 To manipulate a I<PAR distribution>:
25  
26 % par.pl -i Foo-0.01-i386-freebsd-5.8.0.par # install
27 % par.pl -i http://foo.com/Foo-0.01 # auto-appends archname + perlver
28 % par.pl -i cpan://AUTRIJUS/PAR-0.74 # uses CPAN author directory
29 % par.pl -u Foo-0.01-i386-freebsd-5.8.0.par # uninstall
30 % par.pl -s Foo-0.01-i386-freebsd-5.8.0.par # sign
31 % par.pl -v Foo-0.01-i386-freebsd-5.8.0.par # verify
32  
33 To use F<Hello.pm> from F<./foo.par>:
34  
35 % par.pl -A./foo.par -MHello
36 % par.pl -A./foo -MHello # the .par part is optional
37  
38 Same thing, but search F<foo.par> in the F<@INC>;
39  
40 % par.pl -Ifoo.par -MHello
41 % par.pl -Ifoo -MHello # ditto
42  
43 Run F<test.pl> or F<script/test.pl> from F<foo.par>:
44  
45 % par.pl foo.par test.pl # looks for 'main.pl' by default,
46 # otherwise run 'test.pl'
47  
48 To make a self-containing script containing a PAR file :
49  
50 % par.pl -O./foo.pl foo.par
51 % ./foo.pl test.pl # same as above
52  
53 To embed the necessary non-core modules and shared objects for PAR's
54 execution (like C<Zlib>, C<IO>, C<Cwd>, etc), use the B<-b> flag:
55  
56 % par.pl -b -O./foo.pl foo.par
57 % ./foo.pl test.pl # runs anywhere with core modules installed
58  
59 If you also wish to embed I<core> modules along, use the B<-B> flag
60 instead:
61  
62 % par.pl -B -O./foo.pl foo.par
63 % ./foo.pl test.pl # runs anywhere with the perl interpreter
64  
65 This is particularly useful when making stand-alone binary
66 executables; see L<pp> for details.
67  
68 =head1 DESCRIPTION
69  
70 This stand-alone command offers roughly the same feature as C<perl
71 -MPAR>, except that it takes the pre-loaded F<.par> files via
72 C<-Afoo.par> instead of C<-MPAR=foo.par>.
73  
74 Additionally, it lets you convert a CPAN distribution to a PAR
75 distribution, as well as manipulate such distributions. For more
76 information about PAR distributions, see L<PAR::Dist>.
77  
78 =head2 Binary PAR loader (L<parl>)
79  
80 If you have a C compiler, or a pre-built binary package of B<PAR> is
81 available for your platform, a binary version of B<par.pl> will also be
82 automatically installed as B<parl>. You can use it to run F<.par> files:
83  
84 # runs script/run.pl in archive, uses its lib/* as libraries
85 % parl myapp.par run.pl # runs run.pl or script/run.pl in myapp.par
86 % parl otherapp.pl # also runs normal perl scripts
87  
88 However, if the F<.par> archive contains either F<main.pl> or
89 F<script/main.pl>, it is used instead:
90  
91 % parl myapp.par run.pl # runs main.pl, with 'run.pl' as @ARGV
92  
93 Finally, the C<-O> option makes a stand-alone binary executable from a
94 PAR file:
95  
96 % parl -B -Omyapp myapp.par
97 % ./myapp # run it anywhere without perl binaries
98  
99 With the C<--par-options> flag, generated binaries can act as C<parl>
100 to pack new binaries:
101  
102 % ./myapp --par-options -Omyap2 myapp.par # identical to ./myapp
103 % ./myapp --par-options -Omyap3 myap3.par # now with different PAR
104  
105 =head2 Stand-alone executable format
106  
107 The format for the stand-alone executable is simply concatenating the
108 following elements:
109  
110 =over 4
111  
112 =item * The executable itself
113  
114 Either in plain-text (F<par.pl>) or native executable format (F<parl>
115 or F<parl.exe>).
116  
117 =item * Any number of embedded files
118  
119 These are typically used for bootstrapping PAR's various XS dependencies.
120 Each section contains:
121  
122 =over 4
123  
124 =item The magic string "C<FILE>"
125  
126 =item Length of file name in C<pack('N')> format plus 9
127  
128 =item 8 bytes of hex-encoded CRC32 of file content
129  
130 =item A single slash ("C</>")
131  
132 =item The file name (without path)
133  
134 =item File length in C<pack('N')> format
135  
136 =item The file's content (not compressed)
137  
138 =back
139  
140 =item * One PAR file
141  
142 This is just a zip file beginning with the magic string "C<PK\003\004>".
143  
144 =item * Ending section
145  
146 The pre-computed cache name. A pack('Z40') string of the value of -T
147 (--tempcache) or the hash of the file, followed by C<\0CACHE>. The hash
148 of the file is calculated with L<Digest::SHA>.
149  
150 A pack('N') number of the total length of FILE and PAR sections,
151 followed by a 8-bytes magic string: "C<\012PAR.pm\012>".
152  
153 =back
154  
155 =cut
156  
157 my ($PAR_MAGIC, $FILE_offset_size, $cache_name_size);
158 # NOTE: must initialize them in BEGIN as they are used in BEGIN below
159 BEGIN {
160 $PAR_MAGIC = "\nPAR.pm\n";
161 $FILE_offset_size = 4; # pack("N")
162 $cache_name_size = 40;
163 $PKZIP_MAGIC = "PK\003\004";
164 }
165  
166  
167 # Search $fh for the "\nPAR.pm\n signature backward from the end of the file
168 sub find_par_magic
169 {
170 my ($fh) = @_;
171  
172 my $chunk_size = 64 * 1024;
173 my $buf;
174 my $size = -s $fh;
175  
176 my $pos = ($size-1) - ($size-1) % $chunk_size; # NOTE: $pos is a multiple of $chunk_size
177 while ($pos >= 0) {
178 seek $fh, $pos, 0;
179 read $fh, $buf, $chunk_size + length($PAR_MAGIC);
180 if ((my $i = rindex($buf, $PAR_MAGIC)) >= 0) {
181 return $pos + $i;
182 }
183 $pos -= $chunk_size;
184 }
185 return -1;
186 }
187  
188 my ($par_temp, $progname, @tmpfile, %ModuleCache);
189 END { if ($ENV{PAR_CLEAN}) {
190 require File::Temp;
191 require File::Basename;
192 require File::Spec;
193 my $topdir = File::Basename::dirname($par_temp);
194 outs(qq[Removing files in "$par_temp"]);
195 File::Find::finddepth(sub { ( -d ) ? rmdir : unlink }, $par_temp);
196 rmdir $par_temp;
197 # Don't remove topdir because this causes a race with other apps
198 # that are trying to start.
199  
200 if (-d $par_temp && $^O ne 'MSWin32') {
201 # Something went wrong unlinking the temporary directory. This
202 # typically happens on platforms that disallow unlinking shared
203 # libraries and executables that are in use. Unlink with a background
204 # shell command so the files are no longer in use by this process.
205 # Don't do anything on Windows because our parent process will
206 # take care of cleaning things up.
207  
208 my $tmp = new File::Temp(
209 TEMPLATE => 'tmpXXXXX',
210 DIR => File::Basename::dirname($topdir),
211 SUFFIX => '.cmd',
212 UNLINK => 0,
213 );
214 my $filename = $tmp->filename;
215  
216 print $tmp <<"...";
217 #!/bin/sh
218 x=1; while [ \$x -lt 10 ]; do
219 rm -rf '$par_temp'
220 if [ \! -d '$par_temp' ]; then
221 break
222 fi
223 sleep 1
224 x=`expr \$x + 1`
225 done
226 rm '$filename'
227 ...
228 close $tmp;
229  
230 chmod 0700, $filename;
231 my $cmd = "$filename >/dev/null 2>&1 &";
232 system($cmd);
233 outs(qq[Spawned background process to perform cleanup: $filename]);
234 }
235 } }
236  
237  
238 BEGIN {
239 Internals::PAR::BOOT() if defined &Internals::PAR::BOOT;
240  
241 eval {
242  
243 _par_init_env();
244  
245 my $quiet = !$ENV{PAR_DEBUG};
246  
247 # fix $progname if invoked from PATH
248 my %sys = (
249 path_sep => ($^O =~ /^MSWin/ ? ';' : ':'),
250 _exe => ($^O =~ /^(?:MSWin|OS2|cygwin)/ ? '.exe' : ''),
251 _delim => ($^O =~ /^MSWin|OS2/ ? '\\' : '/'),
252 );
253  
254 _set_progname();
255 outs(qq[\$progname = "$progname"]);
256  
257 _set_par_temp();
258 outs(qq[\$ENV{PAR_TEMP} = "$ENV{PAR_TEMP}"]);
259  
260 # Magic string checking and extracting bundled modules {{{
261 my ($start_pos, $start_of_FILE_section);
262 MAGIC: {
263 local $SIG{__WARN__} = sub {};
264  
265 # Check file type, get start of data section {{{
266 unless (open _FH, '<:raw', $progname) {
267 outs(qq[Can't read from file "$progname"]); # don't use $! here as it requires Errno.pm
268 last MAGIC;
269 }
270  
271 # Search for the "\nPAR.pm\n signature backward from the end of the file
272 my $magic_pos = find_par_magic(*_FH);
273 if ($magic_pos < 0) {
274 outs(qq[Can't find magic string "$PAR_MAGIC" in file "$progname"]);
275 last MAGIC;
276 }
277 outs("Found PAR magic at position $magic_pos");
278  
279 # Check for "\0CACHE" 4 bytes below the signature
280 seek _FH, $magic_pos - $FILE_offset_size - length("\0CACHE"), 0;
281 read _FH, $buf, length("\0CACHE");
282 if ($buf ne "\0CACHE" && $buf ne "\0CLEAN") {
283 outs("No cache marker found");
284 last MAGIC;
285 }
286 outs(qq[Cache marker "$buf" found]);
287  
288 # Seek 4 bytes backward from the signature to get the offset of the
289 # first embedded FILE, then seek to it
290 seek _FH, $magic_pos - $FILE_offset_size, 0;
291 read _FH, $buf, $FILE_offset_size;
292 my $offset = unpack("N", $buf);
293 outs("Offset from start of FILEs is $offset");
294 seek _FH, $magic_pos - $FILE_offset_size - $offset, 0;
295 $start_of_FILE_section = tell _FH;
296  
297 # }}}
298  
299 # Extracting each file into memory {{{
300 my %require_list;
301 read _FH, $buf, 4; # read the first "FILE"
302 while ($buf eq "FILE") {
303 read _FH, $buf, 4;
304 read _FH, $buf, unpack("N", $buf);
305  
306 my $fullname = $buf;
307 outs(qq[Unpacking FILE "$fullname"...]);
308 my $crc = ( $fullname =~ s|^([a-f\d]{8})/|| ) ? $1 : undef;
309 my ($basename, $ext) = ($buf =~ m|(?:.*/)?(.*)(\..*)|);
310  
311 read _FH, $buf, 4;
312 read _FH, $buf, unpack("N", $buf);
313  
314 if (defined($ext) and $ext !~ /\.(?:pm|pl|ix|al)$/i) {
315 my $filename = _save_as("$crc$ext", $buf, 0755);
316 $PAR::Heavy::FullCache{$fullname} = $filename;
317 $PAR::Heavy::FullCache{$filename} = $fullname;
318 }
319 else {
320 $ModuleCache{$fullname} = {
321 buf => $buf,
322 crc => $crc,
323 name => $fullname,
324 };
325 $require_list{$fullname}++;
326 }
327 read _FH, $buf, 4;
328 }
329 # }}}
330  
331 local @INC = (sub {
332 my ($self, $module) = @_;
333  
334 return if ref $module or !$module;
335  
336 my $info = $ModuleCache{$module};
337 return unless $info;
338  
339 delete $require_list{$module};
340  
341 $INC{$module} = "/loader/$info/$module";
342  
343 if ($ENV{PAR_CLEAN} and defined(&IO::File::new)) {
344 my $fh = IO::File->new_tmpfile or die "Can't create temp file: $!";
345 $fh->binmode();
346 $fh->print($info->{buf});
347 $fh->seek(0, 0);
348 return $fh;
349 }
350 else {
351 my $filename = _save_as("$info->{crc}.pm", $info->{buf});
352 $info->{file} = $filename;
353  
354 open my $fh, '<:raw', $filename or die qq[Can't read "$filename": $!];
355 return $fh;
356 }
357  
358 die "Bootstrapping failed: can't find module $module!";
359 }, @INC);
360  
361 # Now load all bundled files {{{
362  
363 # initialize shared object processing
364 require XSLoader;
365 require PAR::Heavy;
366 require Carp::Heavy;
367 require Exporter::Heavy;
368 PAR::Heavy::_init_dynaloader();
369  
370 # now let's try getting helper modules from within
371 require IO::File;
372  
373 # load rest of the group in
374 while (my $filename = (sort keys %require_list)[0]) {
375 #local $INC{'Cwd.pm'} = __FILE__ if $^O ne 'MSWin32';
376 unless ($INC{$filename} or $filename =~ /BSDPAN/) {
377 # require modules, do other executable files
378 if ($filename =~ /\.pmc?$/i) {
379 require $filename;
380 }
381 else {
382 # Skip ActiveState's sitecustomize.pl file:
383 do $filename unless $filename =~ /sitecustomize\.pl$/;
384 }
385 }
386 delete $require_list{$filename};
387 }
388  
389 # }}}
390  
391 if ($buf ne $PKZIP_MAGIC) {
392 outs(qq[No zip found after FILE section in file "$progname"]);
393 last MAGIC ;
394 }
395  
396 $start_pos = (tell _FH) - 4; # start of zip
397 }
398 # }}}
399  
400 # Argument processing {{{
401 my @par_args;
402 my ($out, $bundle, $logfh, $cache_name);
403  
404 delete $ENV{PAR_APP_REUSE}; # sanitize (REUSE may be a security problem)
405  
406 # Don't swallow arguments for compiled executables without --par-options
407 if (!$start_pos or ($ARGV[0] eq '--par-options' && shift)) {
408 my %dist_cmd = qw(
409 p blib_to_par
410 i install_par
411 u uninstall_par
412 s sign_par
413 v verify_par
414 );
415  
416 # if the app is invoked as "appname --par-options --reuse PROGRAM @PROG_ARGV",
417 # use the app to run the given perl code instead of anything from the
418 # app itself (but still set up the normal app environment and @INC)
419 if (@ARGV and $ARGV[0] eq '--reuse') {
420 shift @ARGV;
421 $ENV{PAR_APP_REUSE} = shift @ARGV;
422 }
423 else { # normal parl behaviour
424  
425 my @add_to_inc;
426 while (@ARGV) {
427 $ARGV[0] =~ /^-([AIMOBLbqpiusTv])(.*)/ or last;
428  
429 if ($1 eq 'I') {
430 push @add_to_inc, $2;
431 }
432 elsif ($1 eq 'M') {
433 eval "use $2";
434 }
435 elsif ($1 eq 'A') {
436 unshift @par_args, $2;
437 }
438 elsif ($1 eq 'O') {
439 $out = $2;
440 }
441 elsif ($1 eq 'b') {
442 $bundle = 'site';
443 }
444 elsif ($1 eq 'B') {
445 $bundle = 'all';
446 }
447 elsif ($1 eq 'q') {
448 $quiet = 1;
449 }
450 elsif ($1 eq 'L') {
451 open $logfh, ">>", $2 or die qq[Can't open log file "$2": $!];
452 }
453 elsif ($1 eq 'T') {
454 $cache_name = $2;
455 }
456  
457 shift(@ARGV);
458  
459 if (my $cmd = $dist_cmd{$1}) {
460 delete $ENV{'PAR_TEMP'};
461 init_inc();
462 require PAR::Dist;
463 &{"PAR::Dist::$cmd"}() unless @ARGV;
464 &{"PAR::Dist::$cmd"}($_) for @ARGV;
465 exit;
466 }
467 }
468  
469 unshift @INC, @add_to_inc;
470 }
471 }
472  
473 # XXX -- add --par-debug support!
474  
475 # }}}
476  
477 # Output mode (-O) handling {{{
478 if ($out) {
479 {
480 #local $INC{'Cwd.pm'} = __FILE__ if $^O ne 'MSWin32';
481 require IO::File;
482 require Archive::Zip;
483 require Digest::SHA;
484 }
485  
486 my $par = shift(@ARGV);
487 my $zip;
488  
489  
490 if (defined $par) {
491 open my $fh, '<:raw', $par or die qq[Can't find par file "$par": $!];
492 bless($fh, 'IO::File');
493  
494 $zip = Archive::Zip->new;
495 ( $zip->readFromFileHandle($fh, $par) == Archive::Zip::AZ_OK() )
496 or die qq[Error reading zip archive "$par"];
497 }
498  
499  
500 # Extract the "par" dictionary from META.yml in $zip
501 my %meta_par = do {
502 if ($zip and my $meta = $zip->contents('META.yml')) {
503 $meta =~ s/.*^par:$//ms;
504 $meta =~ s/^\S.*//ms;
505 $meta =~ /^ ([^:]+): (.+)$/mg;
506 }
507 };
508  
509 # Open input and output files {{{
510  
511 if (defined $par) {
512 open my $ph, '<:raw', $par or die qq[Can't read par file "$par": $!];
513 my $buf;
514 read $ph, $buf, 4;
515 die qq["$par" is not a par file] unless $buf eq $PKZIP_MAGIC;
516 close $ph;
517 }
518  
519 CreatePath($out) ;
520  
521 my $fh = IO::File->new(
522 $out,
523 IO::File::O_CREAT() | IO::File::O_RDWR() | IO::File::O_TRUNC(),
524 0777,
525 ) or die qq[Can't create file "$out": $!];
526 $fh->binmode();
527  
528 seek _FH, 0, 0;
529  
530 my $loader;
531 if (defined $start_of_FILE_section) {
532 read _FH, $loader, $start_of_FILE_section;
533 } else {
534 local $/ = undef;
535 $loader = <_FH>;
536 }
537  
538 if (!$ENV{PAR_VERBATIM} and $loader =~ /^(?:#!|\@rem)/) {
539 require PAR::Filter::PodStrip;
540 PAR::Filter::PodStrip->apply(\$loader, $0);
541 }
542  
543 $fh->print($loader)
544 or die qq[Error writing loader to "$out": $!];
545 # }}}
546  
547 # Write bundled modules {{{
548 if ($bundle) {
549 require PAR::Heavy;
550 PAR::Heavy::_init_dynaloader();
551  
552 init_inc();
553  
554 require_modules();
555  
556 # NOTE: use $Config::Config{...} since we only "require" (*not* "use") it - no import
557 my @inc = grep { !/BSDPAN/ }
558 grep {
559 ($bundle ne 'site') or
560 ($_ ne $Config::Config{archlibexp} and
561 $_ ne $Config::Config{privlibexp});
562 } @INC;
563  
564 # normalize paths (remove trailing or multiple consecutive slashes)
565 s|/+|/|g, s|/$|| foreach @inc;
566  
567 # Now determine the files loaded above by require_modules():
568 # Perl source files are found in values %INC and DLLs are
569 # found in @DynaLoader::dl_shared_objects.
570 my %files;
571 $files{$_}++ for @DynaLoader::dl_shared_objects, values %INC;
572  
573 my $lib_ext = $Config::Config{lib_ext}; # XXX lib_ext vs dlext ?
574 my %written;
575  
576 foreach my $key (sort keys %files) {
577 my ($file, $name);
578  
579 if (defined(my $fc = $PAR::Heavy::FullCache{$key})) {
580 ($file, $name) = ($key, $fc);
581 }
582 else {
583 foreach my $dir (@inc) {
584 if ($key =~ m|^\Q$dir\E/(.*)$|i) {
585 ($file, $name) = ($key, $1);
586 last;
587 }
588 if ($key =~ m|^/loader/[^/]+/(.*)$|) {
589 if (my $ref = $ModuleCache{$1}) {
590 ($file, $name) = ($ref, $1);
591 last;
592 }
593 if (-f "$dir/$1") {
594 ($file, $name) = ("$dir/$1", $1);
595 last;
596 }
597 }
598 }
599 }
600 # There are legitimate reasons why we couldn't find $name and $file for a $key:
601 # - cperl has e.g. $INC{"XSLoader.pm"} = "XSLoader.c",
602 # $INC{"DynaLoader.pm"}' = "dlboot_c.PL"
603 next unless defined $name;
604  
605 next if $written{$name}++;
606 next if !ref($file) and $file =~ /\.\Q$lib_ext\E$/i;
607  
608 outs(sprintf(qq[Packing FILE "%s"...], ref $file ? $file->{name} : $file));
609 my $content;
610 if (ref($file)) {
611 $content = $file->{buf};
612 }
613 else {
614 local $/ = undef;
615 open my $th, '<:raw', $file or die qq[Can't read "$file": $!];
616 $content = <$th>;
617 close $th;
618  
619 PAR::Filter::PodStrip->apply(\$content, "<embedded>/$name")
620 if !$ENV{PAR_VERBATIM} and $name =~ /\.(?:pm|ix|al)$/i;
621  
622 PAR::Filter::PatchContent->new->apply(\$content, $file, $name);
623 }
624  
625 $fh->print("FILE",
626 pack('N', length($name) + 9),
627 sprintf("%08x/%s", Archive::Zip::computeCRC32($content), $name),
628 pack('N', length($content)),
629 $content)
630 or die qq[Error writing embedded FILE to "$out": $!];
631  
632 outs(qq[Written as "$name"]);
633 }
634 }
635 # }}}
636  
637 # Now write out the PAR and magic strings {{{
638 if ($zip) {
639 $zip->writeToFileHandle($fh) == Archive::Zip::AZ_OK
640 or die qq[Error writing zip part of "$out"];
641 }
642  
643 if ($meta_par{clean}) {
644 $fh->print("\0CLEAN");
645 }
646 else {
647 if (!defined $cache_name) {
648 my $ctx = Digest::SHA->new(1);
649 seek $fh, 0, 0;
650 $ctx->addfile($fh);
651 seek $fh, 0, 2;
652 $cache_name = $ctx->hexdigest;
653 }
654 # truncate $cache_name to 40 byes and fill with NULs if necessary
655 $cache_name = substr $cache_name, 0, $cache_name_size;
656 $cache_name .= "\0" x ($cache_name_size - length $cache_name);
657 $fh->print($cache_name,
658 "\0CACHE");
659 }
660  
661 # compute the offset from the end of $loader to end of "...\0CACHE" or "\0CLEAN"
662 my $offset = $fh->tell - length($loader);
663 $fh->print(pack('N', $offset),
664 $PAR_MAGIC);
665  
666 $fh->close or die qq[Error writing trailer of "$out": $!];
667 chmod 0755, $out;
668 # }}}
669  
670 exit;
671 }
672 # }}}
673  
674 # Prepare $progname into PAR file cache {{{
675 {
676 last unless defined $start_pos;
677  
678 _fix_progname();
679  
680 # Now load the PAR file and put it into PAR::LibCache {{{
681 require PAR;
682 PAR::Heavy::_init_dynaloader();
683  
684  
685 {
686 #local $INC{'Cwd.pm'} = __FILE__ if $^O ne 'MSWin32';
687 require File::Find;
688 require Archive::Zip;
689 }
690  
691 my $fh = IO::File->new; # Archive::Zip operates on an IO::Handle
692 $fh->fdopen(fileno(_FH), 'r') or die qq[fdopen() failed: $!];
693  
694 # Temporarily increase the chunk size for Archive::Zip so that it will find the EOCD
695 # even if lots of stuff has been appended to the pp'ed exe (e.g. by OSX codesign).
696 Archive::Zip::setChunkSize(-s _FH);
697 my $zip = Archive::Zip->new;
698 ($zip->readFromFileHandle($fh, $progname) == Archive::Zip::AZ_OK())
699 or die qq[Error reading zip archive "$progname"];
700 Archive::Zip::setChunkSize(64 * 1024);
701  
702 push @PAR::LibCache, $zip;
703 $PAR::LibCache{$progname} = $zip;
704  
705  
706 outs("Extracting zip...");
707 if (defined $ENV{PAR_TEMP}) { # should be set at this point!
708 foreach my $member ( $zip->members ) {
709 next if $member->isDirectory;
710 my $member_name = $member->fileName;
711 next unless $member_name =~ m{
712 ^
713 /?shlib/
714 (?:$Config::Config{archname}/)?
715 ([^/]+)
716 $
717 }x;
718 my $extract_name = $1;
719 my $dest_name = File::Spec->catfile($ENV{PAR_TEMP}, $extract_name);
720 if (-f $dest_name && -s _ == $member->uncompressedSize()) {
721 outs(qq[Skipping "$member_name" since it already exists at "$dest_name"]);
722 } else {
723 outs(qq[Extracting "$member_name" to "$dest_name"...]);
724 ($member->extractToFileNamed($dest_name) == Archive::Zip::AZ_OK())
725 or die qq[Error extracting zip member to "$dest_name"];
726 chmod(0555, $dest_name) if $^O eq "hpux";
727 }
728 }
729 }
730 # }}}
731 }
732 # }}}
733  
734 # If there's no main.pl to run, show usage {{{
735 unless ($PAR::LibCache{$progname}) {
736 die << "." unless @ARGV;
737 Usage: $0 [ -Alib.par ] [ -Idir ] [ -Mmodule ] [ src.par ] [ program.pl ]
738 $0 [ -B|-b ] [-Ooutfile] src.par
739 .
740 $ENV{PAR_PROGNAME} = $progname = $0 = shift(@ARGV);
741 }
742 # }}}
743  
744 sub CreatePath {
745 my ($name) = @_;
746  
747 require File::Basename;
748 my ($basename, $path, $ext) = File::Basename::fileparse($name, ('\..*'));
749  
750 require File::Path;
751  
752 File::Path::mkpath($path) unless(-e $path); # mkpath dies with error
753 }
754  
755 sub require_modules {
756  
757 require lib;
758 require DynaLoader;
759 require integer;
760 require strict;
761 require warnings;
762 require vars;
763 require Carp;
764 require Carp::Heavy;
765 require Errno;
766 require Exporter::Heavy;
767 require Exporter;
768 require Fcntl;
769 require File::Temp;
770 require File::Spec;
771 require XSLoader;
772 require Config;
773 require IO::Handle;
774 require IO::File;
775 require Compress::Zlib;
776 require Archive::Zip;
777 require Digest::SHA;
778 require PAR;
779 require PAR::Heavy;
780 require PAR::Dist;
781 require PAR::Filter::PodStrip;
782 require PAR::Filter::PatchContent;
783 require attributes;
784 eval { require Cwd };
785 eval { require Win32 };
786 eval { require Scalar::Util };
787 eval { require Archive::Unzip::Burst };
788 eval { require Tie::Hash::NamedCapture };
789 eval { require PerlIO; require PerlIO::scalar };
790 eval { require utf8 };
791 }
792  
793 # The C version of this code appears in myldr/mktmpdir.c
794 # This code also lives in PAR::SetupTemp as set_par_temp_env!
795 sub _set_par_temp {
796 if (defined $ENV{PAR_TEMP} and $ENV{PAR_TEMP} =~ /(.+)/) {
797 $par_temp = $1;
798 return;
799 }
800  
801 foreach my $path (
802 (map $ENV{$_}, qw( PAR_TMPDIR TMPDIR TEMPDIR TEMP TMP )),
803 qw( C:\\TEMP /tmp . )
804 ) {
805 next unless defined $path and -d $path and -w $path;
806 my $username;
807 my $pwuid;
808 # does not work everywhere:
809 eval {($pwuid) = getpwuid($>) if defined $>;};
810  
811 if ( defined(&Win32::LoginName) ) {
812 $username = &Win32::LoginName;
813 }
814 elsif (defined $pwuid) {
815 $username = $pwuid;
816 }
817 else {
818 $username = $ENV{USERNAME} || $ENV{USER} || 'SYSTEM';
819 }
820  
821 my $stmpdir = "$path$sys{_delim}par-".unpack("H*", $username);
822 mkdir $stmpdir, 0755;
823  
824 my $cache_dir;
825 if ($ENV{PAR_CLEAN}) {
826 $cache_dir = "temp-$$";
827 }
828 else {
829 open my $fh, "<:raw", $progname or die qq[Can't read "$progname": $!];
830 if ((my $magic_pos = find_par_magic($fh)) >= 0) {
831 seek $fh, $magic_pos
832 - $FILE_offset_size
833 - length("\0CACHE"), 0;
834 my $buf;
835 read $fh, $buf, length("\0CACHE");
836 if ($buf eq "\0CACHE") {
837 seek $fh, $magic_pos
838 - $FILE_offset_size
839 - length("\0CACHE")
840 - $cache_name_size, 0;
841 read $fh, $buf, $cache_name_size;
842 $buf =~ s/\0//g;
843 $cache_dir = "cache-$buf";
844 }
845 }
846 close $fh;
847 }
848 if (!$cache_dir) {
849 $cache_dir = "temp-$$";
850 $ENV{PAR_CLEAN} = 1;
851 }
852 $stmpdir .= "$sys{_delim}$cache_dir";
853  
854 mkdir $stmpdir, 0755;
855 $ENV{PAR_TEMP} = $stmpdir;
856 last;
857 }
858  
859 $par_temp = $1 if $ENV{PAR_TEMP} and $ENV{PAR_TEMP} =~ /(.+)/;
860 }
861  
862  
863 # check if $name (relative to $par_temp) already exists;
864 # if not, create a file with a unique temporary name,
865 # fill it with $contents, set its file mode to $mode if present;
866 # finaly rename it to $name;
867 # in any case return the absolute filename
868 sub _save_as {
869 my ($name, $contents, $mode) = @_;
870  
871 my $fullname = "$par_temp/$name";
872 unless (-e $fullname) {
873 my $tempname = "$fullname.$$";
874  
875 my $fh;
876 (open $fh, '>:raw', $tempname)
877 && (print $fh $contents)
878 && (close $fh)
879 or die qq[Error writing "$tempname": $!];
880 chmod $mode, $tempname if defined $mode;
881  
882 rename($tempname, $fullname) or unlink($tempname);
883 # NOTE: The rename() error presumably is something like ETXTBSY
884 # (scenario: another process was faster at extraction $fullname
885 # than us and is already using it in some way); anyway,
886 # let's assume $fullname is "good" and clean up our copy.
887 }
888  
889 return $fullname;
890 }
891  
892 # same code lives in PAR::SetupProgname::set_progname
893 sub _set_progname {
894 if (defined $ENV{PAR_PROGNAME} and $ENV{PAR_PROGNAME} =~ /(.+)/) {
895 $progname = $1;
896 }
897  
898 $progname ||= $0;
899  
900 if ($ENV{PAR_TEMP} and index($progname, $ENV{PAR_TEMP}) >= 0) {
901 $progname = substr($progname, rindex($progname, $sys{_delim}) + 1);
902 }
903  
904 if (!$ENV{PAR_PROGNAME} or index($progname, $sys{_delim}) >= 0) {
905 if (open my $fh, '<', $progname) {
906 return if -s $fh;
907 }
908 if (-s "$progname$sys{_exe}") {
909 $progname .= $sys{_exe};
910 return;
911 }
912 }
913  
914 foreach my $dir (split /\Q$sys{path_sep}\E/, $ENV{PATH}) {
915 next if exists $ENV{PAR_TEMP} and $dir eq $ENV{PAR_TEMP};
916 $dir =~ s/\Q$sys{_delim}\E$//;
917 (($progname = "$dir$sys{_delim}$progname$sys{_exe}"), last)
918 if -s "$dir$sys{_delim}$progname$sys{_exe}";
919 (($progname = "$dir$sys{_delim}$progname"), last)
920 if -s "$dir$sys{_delim}$progname";
921 }
922 }
923  
924 sub _fix_progname {
925 $0 = $progname ||= $ENV{PAR_PROGNAME};
926 if (index($progname, $sys{_delim}) < 0) {
927 $progname = ".$sys{_delim}$progname";
928 }
929  
930 # XXX - hack to make PWD work
931 my $pwd = (defined &Cwd::getcwd) ? Cwd::getcwd()
932 : ((defined &Win32::GetCwd) ? Win32::GetCwd() : `pwd`);
933 chomp($pwd);
934 $progname =~ s/^(?=\.\.?\Q$sys{_delim}\E)/$pwd$sys{_delim}/;
935  
936 $ENV{PAR_PROGNAME} = $progname;
937 }
938  
939 sub _par_init_env {
940 if ( $ENV{PAR_INITIALIZED}++ == 1 ) {
941 return;
942 } else {
943 $ENV{PAR_INITIALIZED} = 2;
944 }
945  
946 for (qw( SPAWNED TEMP CLEAN DEBUG CACHE PROGNAME ) ) {
947 delete $ENV{"PAR_$_"};
948 }
949  
950 for (qw/ TMPDIR TEMP CLEAN DEBUG /) {
951 $ENV{"PAR_$_"} = $ENV{"PAR_GLOBAL_$_"} if exists $ENV{"PAR_GLOBAL_$_"};
952 }
953  
954 if ($ENV{PAR_TEMP}) {
955 delete $ENV{PAR_CLEAN};
956 }
957 }
958  
959 sub outs {
960 return if $quiet;
961 if ($logfh) {
962 print $logfh "@_\n";
963 }
964 else {
965 print "@_\n";
966 }
967 }
968  
969 sub init_inc {
970 require Config;
971 # NOTE: use $Config::Config{...} since we only "require" (*not* "use") it - no import
972 push @INC, grep defined, map $Config::Config{$_}, qw(
973 archlibexp privlibexp sitearchexp sitelibexp
974 vendorarchexp vendorlibexp
975 );
976 }
977  
978 ########################################################################
979 # The main package for script execution
980  
981 package main;
982  
983 require PAR;
984 unshift @INC, \&PAR::find_par;
985 PAR->import(@par_args);
986  
987 die qq[par.pl: Can't open perl script "$progname": No such file or directory\n]
988 unless -e $progname;
989  
990 do $progname;
991 CORE::exit($1) if ($@ =~/^_TK_EXIT_\((\d+)\)/);
992 die $@ if $@;
993  
994 };
995  
996 $::__ERROR = $@ if $@;
997 }
998  
999 CORE::exit($1) if ($::__ERROR =~/^_TK_EXIT_\((\d+)\)/);
1000 die $::__ERROR if $::__ERROR;
1001  
1002 1;
1003  
1004 =head1 SEE ALSO
1005  
1006 L<PAR>, L<PAR::Dist>, L<parl>, L<pp>
1007  
1008 =head1 AUTHORS
1009  
1010 Audrey Tang E<lt>cpan@audreyt.orgE<gt>,
1011 Steffen Mueller E<lt>smueller@cpan.orgE<gt>
1012  
1013 You can write
1014 to the mailing list at E<lt>par@perl.orgE<gt>, or send an empty mail to
1015 E<lt>par-subscribe@perl.orgE<gt> to participate in the discussion.
1016 Archives of the mailing list are available at
1017 E<lt>https://www.mail-archive.com/par@perl.org/E<gt> or E<lt>https://groups.google.com/g/perl.parE<gt>.
1018  
1019 Please submit bug reports to E<lt>https://github.com/rschupp/PAR-Packer/issuesE<gt>.
1020  
1021 =head1 COPYRIGHT
1022  
1023 Copyright 2002-2009 by Audrey Tang E<lt>cpan@audreyt.orgE<gt>.
1024  
1025 Neither this program nor the associated L<parl> program impose any
1026 licensing restrictions on files generated by their execution, in
1027 accordance with the 8th article of the Artistic License:
1028  
1029 "Aggregation of this Package with a commercial distribution is
1030 always permitted provided that the use of this Package is embedded;
1031 that is, when no overt attempt is made to make this Package's
1032 interfaces visible to the end user of the commercial distribution.
1033 Such use shall not be construed as a distribution of this Package."
1034  
1035 Therefore, you are absolutely free to place any license on the resulting
1036 executable, as long as the packed 3rd-party libraries are also available
1037 under the Artistic License.
1038  
1039 This program is free software; you can redistribute it and/or modify it
1040 under the same terms as Perl itself.
1041  
1042 See F<LICENSE>.
1043  
1044 =cut
1045  
1046 __END__